Partial backport of [[https://github.com/bitcoin/bitcoin/pull/20811 | core#20811:]]:
https://github.com/bitcoin/bitcoin/pull/20811/commits/a568b82febb3ecbd5ebb7c3f9da27e762b0c68f6
Note that the cpp file deserves a good reordering, but that's out of scope for this diff.
Depends on D10886.
Ref T1696.