And add some unit tests for the new functions.
Partial backport of core#28970:
https://github.com/bitcoin/bitcoin/pull/28970/commits/2f51cd680fb4323f1c792dae37d4c4e0e0e35804
https://github.com/bitcoin/bitcoin/pull/28970/commits/d095316c1c23e9460dfbd9fdbaf292063adcd080
Depends on D16491.