This PR seems to have been backported by pieces over time, and this diff adds what remains.
Most comes from the commit 8c2d695:
https://github.com/bitcoin/bitcoin/pull/12954/commits/8c2d695c4a45bdd9378c7970b0fcba6e1efc01f9
Completes backport of core PR12954:
https://github.com/bitcoin/bitcoin/pull/12954/files