Partial backport of core#19610:
https://github.com/bitcoin/bitcoin/pull/19610/commits/42ca5618cae0fd9ef97d2006b17d896bc58cc17c?diff=split&w=1
This will help narrowing the cs_main scope when introducing the proofs.
There are more simplifications and de-duplication to come in follow-up
backports.
Depends on D9501.
Note that the commit
https://github.com/bitcoin/bitcoin/pull/19610/commits/39f1dc944554218911b0945fff7e6d06f3dab284
is skipped because it is a segwit only commit.