Improvements and cleanups by John Newbery
This is from PR11403 : https://github.com/bitcoin/bitcoin/pull/11403/commits/b224a47a1a5feac380506abff63fae91d7a93b39
We initially decided not to backport it because we don't have this feature, but it turns out it exercice various parts of the code and is useful. In addition, it makes backport easier.
Also include a trick similar to PR17124 to significantly speedup the test.