Completes backport of [[https://github.com/bitcoin/bitcoin/pull/21726 | core#21726]]:
https://github.com/bitcoin/bitcoin/pull/21726/commits/825d19839bf71245306d4c8edde040e5941caa46
https://github.com/bitcoin/bitcoin/pull/21726/commits/de08932efa953e9a237cbf879460488ad8947411
https://github.com/bitcoin/bitcoin/pull/21726/commits/71c3f0356c01521a95c64fba1e7375aea6286bb0
Depends on D17389.