This is a partial backport of core#21202 and concludes backport of core#24931
https://github.com/bitcoin/bitcoin/pull/24931/commits/ce893c0497fc9b8ab9752153dfcc77c9f427545e
The code change from core#21202 was done independently by us in D4581
Depends on D14894