This is a backport of core#19499 [2/2] and core#23740
https://github.com/bitcoin/bitcoin/pull/19499/commits/fadc0c80ae4e526fb2b503f7cc02f6122aaf1de5
The second PR is a temporary fix for an intermittent failure that will later be reverted in core#23758
Depends on D10964