This is a partial backport of core#26479
https://github.com/bitcoin/bitcoin/pull/26749/commits/15209d97c6aad7d5c199fe007ad39b91c8ee6562
https://github.com/bitcoin/bitcoin/pull/26749/commits/06820032142a75cc3c5b832045058bc6f6f74786
The validation.cpp change was already done in D297