Partial backport of core PR11817 (commit 6f7f5bc)
https://github.com/bitcoin/bitcoin/pull/11817/commits/6f7f5bc0026df12b64935b4e9db32cfc7b6e8829
Depends on D3561
Very few changes remain from this commit due to previous refactoring and
linter actions.
Because a lot of changes are erased by later commits, I backported it
last (it is the first commit in core PR) so that it is easier to review.