Extracted from #19573 to make review easier. I also reviewed it myself.
I added some comments to the test: https://github.com/bitcoin/bitcoin/pull/19573/commits/bae9a452191a7a83478f7d508a54f4a04d385505#r585486781
I also moved some TestState
changes from the second to the first commit, to reduce the latter diff.