Partial backport of core PR11651 (commit e7b3163)
https://github.com/bitcoin/bitcoin/pull/11651/commits/e7b31631c78a8fc021336c7ecda44f6bc4b4b1f1
Not much remaining here as most of the refactors have already been done
as part of T417 or angle bracket transition.