Backport of [[https://github.com/bitcoin/bitcoin/pull/26280 | core#26280]].
Includes a commit from [[https://github.com/bitcoin/bitcoin/pull/23047 | core#23047]]:
https://github.com/bitcoin/bitcoin/pull/23047/commits/faca688a8579d7e30d056b6847789fdd56fc0bf4
Depends on D16445.