This is a backport of core#16710 [1/2]
https://github.com/bitcoin/bitcoin/pull/16710/commits/de5e91c3034f320f84ee0308a3c31659635d136a
This is backported out of order. In the original PR, it should have
touched db.{h|c}, but the code was moved to bdb.{h|c} in D8615
This brings the code up to date with what it should look like for future
backports.