Motivation: minor optimizations to slightly speed up validation by reducing resource usage.
I realize this touches consensus critical code and changes should not be made lightly. Open to feedback that the changes are not worth the performance gain, though I believe these changes can be made safely. To be specific:
- Duplicate input check (CheckTransaction): replace the std::set with a pairwise scan for transactions up to 96 inputs. 2X to 3X speedup.
- Relative lock times (EvaluateSequenceLocks): CalculateSequenceLocks returns {-1,-1} when no input has an active relative lock, so consult the previous block's median time past only when lockPair.second >= 0. Avoids an 11-entry walk plus sort for the large majority of transactions.
- ConnectBlock: skip the per-input coin lookups that fill prevheights when BIP68 is not enforced for the block, the tx version is below 2, or every input sets SEQUENCE_LOCKTIME_DISABLE_FLAG. Correct because none of those cases can read a height.
- Sigop cost (GetTransactionSigOpCost): fold the P2SH and witness counts into one pass over the inputs, halving coin cache lookups for P2SH txs.
I ran a few benchmarks / performance tests on this change. One set of benchmarks on my 8 core laptop solely for the duplicate input check change:
| inputs | old | new | speedup |
|---|---|---|---|
| 1 | 9.61 ns | 7.65 ns | 1.26× |
| 2 | 20.09 ns | 9.12 ns | 2.20× |
| 2 (mixed idx) | 20.42 ns | 9.11 ns | 2.24× |
| 4 | 39.86 ns | 15.08 ns | 2.64× |
| 4 (mixed) | 39.29 ns | 15.03 ns | 2.61× |
| 8 | 79.50 ns | 30.70 ns | 2.59× |
| 16 | 248.71 ns | 79.39 ns | 3.13× |
| 32 | 577.75 ns | 224.12 ns | 2.58× |
| 64 | 1429.95 ns | 768.97 ns | 1.86× |
| 96 | 2355.97 ns | 1618.86 ns | 1.46× |
| 128 | 3208.11 ns | 3230.06 ns | 0.99× |
| 256 | 7682.29 ns | 7375.42 ns | 1.04× |
I also ran two sequential runs of bitcoind --reindex-chainstate on my 6 core desktop to try to compare before and after, the aggregate effect of all 4 changes.
Bitcoin Core v32.1 completed to block height 974,000 in 4 hours, 14 min, 25 sec. This patch on master branch completed to block height 974,000 in 4 hours, 11 min, 58 sec.
Thus a performance speedup of 2 min 27 sec.