This is extracted from Core PR12194 . The rest of the PR is not interesting for us at this stage, but this part will avoid merge conflicts.
https://github.com/bitcoin/bitcoin/pull/12194/commits/31dbd5af4863d73c3215355ec5cf85bde2ddc5d8
Depends on D3661