Skip to content

Commit 308dd2e

Browse files
adamjonasaureleoulesdanra
committed
Sanity assert GetAncestor() != nullptr where appropriate
Add sanity asserts for return value of `CBlockIndex::GetAncestor()` where appropriate. In validation.cpp `CheckSequenceLocks`, check the return value of `tip->GetAncestor(maxInputHeight)` stored into `lp->maxInputBlock`. If it ever returns `nullptr` because the ancestor isn't found, it's going to be a bad bug to keep going, since a `LockPoints` object with the `maxInputBlock` member set to `nullptr` signifies no relative lock time. In the other places, the added asserts would prevent accidental dereferencing of a null pointer which is undefined behavior. Co-Authored-By: Aurèle Oulès <[email protected]> Co-Authored-By: danra <[email protected]>
1 parent b1c5991 commit 308dd2e

File tree

5 files changed

+39
-28
lines changed

5 files changed

+39
-28
lines changed

src/consensus/tx_verify.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <consensus/validation.h>
1212
#include <primitives/transaction.h>
1313
#include <script/interpreter.h>
14+
#include <util/check.h>
1415
#include <util/moneystr.h>
1516

1617
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
@@ -74,7 +75,7 @@ std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags
7475
int nCoinHeight = prevHeights[txinIndex];
7576

7677
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
77-
int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
78+
const int64_t nCoinTime{Assert(block.GetAncestor(std::max(nCoinHeight - 1, 0)))->GetMedianTimePast()};
7879
// NOTE: Subtract 1 to maintain nLockTime semantics
7980
// BIP 68 relative lock times have the semantics of calculating
8081
// the first block or time at which the transaction would be

src/rpc/blockchain.cpp

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1618,9 +1618,9 @@ static RPCHelpMan getchaintxstats()
16181618
}
16191619
}
16201620

1621-
const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount);
1622-
int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast();
1623-
int nTxDiff = pindex->nChainTx - pindexPast->nChainTx;
1621+
const CBlockIndex& past_block{*CHECK_NONFATAL(pindex->GetAncestor(pindex->nHeight - blockcount))};
1622+
const int64_t nTimeDiff{pindex->GetMedianTimePast() - past_block.GetMedianTimePast()};
1623+
const int nTxDiff = pindex->nChainTx - past_block.nChainTx;
16241624

16251625
UniValue ret(UniValue::VOBJ);
16261626
ret.pushKV("time", (int64_t)pindex->nTime);
@@ -1761,8 +1761,7 @@ static RPCHelpMan getblockstats()
17611761
{
17621762
ChainstateManager& chainman = EnsureAnyChainman(request.context);
17631763
LOCK(cs_main);
1764-
const CBlockIndex* pindex{ParseHashOrHeight(request.params[0], chainman)};
1765-
CHECK_NONFATAL(pindex != nullptr);
1764+
const CBlockIndex& pindex{*CHECK_NONFATAL(ParseHashOrHeight(request.params[0], chainman))};
17661765

17671766
std::set<std::string> stats;
17681767
if (!request.params[1].isNull()) {
@@ -1773,8 +1772,8 @@ static RPCHelpMan getblockstats()
17731772
}
17741773
}
17751774

1776-
const CBlock block = GetBlockChecked(chainman.m_blockman, pindex);
1777-
const CBlockUndo blockUndo = GetUndoChecked(chainman.m_blockman, pindex);
1775+
const CBlock& block = GetBlockChecked(chainman.m_blockman, &pindex);
1776+
const CBlockUndo& blockUndo = GetUndoChecked(chainman.m_blockman, &pindex);
17781777

17791778
const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default)
17801779
const bool do_mediantxsize = do_all || stats.count("mediantxsize") != 0;
@@ -1892,25 +1891,25 @@ static RPCHelpMan getblockstats()
18921891
ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0);
18931892
ret_all.pushKV("avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0); // Unit: sat/vbyte
18941893
ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
1895-
ret_all.pushKV("blockhash", pindex->GetBlockHash().GetHex());
1894+
ret_all.pushKV("blockhash", pindex.GetBlockHash().GetHex());
18961895
ret_all.pushKV("feerate_percentiles", feerates_res);
1897-
ret_all.pushKV("height", (int64_t)pindex->nHeight);
1896+
ret_all.pushKV("height", (int64_t)pindex.nHeight);
18981897
ret_all.pushKV("ins", inputs);
18991898
ret_all.pushKV("maxfee", maxfee);
19001899
ret_all.pushKV("maxfeerate", maxfeerate);
19011900
ret_all.pushKV("maxtxsize", maxtxsize);
19021901
ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
1903-
ret_all.pushKV("mediantime", pindex->GetMedianTimePast());
1902+
ret_all.pushKV("mediantime", pindex.GetMedianTimePast());
19041903
ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array));
19051904
ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee);
19061905
ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
19071906
ret_all.pushKV("mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize);
19081907
ret_all.pushKV("outs", outputs);
1909-
ret_all.pushKV("subsidy", GetBlockSubsidy(pindex->nHeight, Params().GetConsensus()));
1908+
ret_all.pushKV("subsidy", GetBlockSubsidy(pindex.nHeight, Params().GetConsensus()));
19101909
ret_all.pushKV("swtotal_size", swtotal_size);
19111910
ret_all.pushKV("swtotal_weight", swtotal_weight);
19121911
ret_all.pushKV("swtxs", swtxs);
1913-
ret_all.pushKV("time", pindex->GetBlockTime());
1912+
ret_all.pushKV("time", pindex.GetBlockTime());
19141913
ret_all.pushKV("total_out", total_out);
19151914
ret_all.pushKV("total_size", total_size);
19161915
ret_all.pushKV("total_weight", total_weight);

src/test/miner_tests.cpp

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -446,16 +446,18 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
446446
BOOST_CHECK(CheckFinalTxAtTip(m_node.chainman->ActiveChain().Tip(), CTransaction{tx})); // Locktime passes
447447
BOOST_CHECK(!TestSequenceLocks(CTransaction{tx})); // Sequence locks fail
448448

449-
for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
450-
m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast
451-
449+
const int SEQUENCE_LOCK_TIME = 512; // Sequence locks pass 512 seconds later
450+
for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i)
451+
m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i)->nTime += SEQUENCE_LOCK_TIME; // Trick the MedianTimePast
452452
{
453453
CBlockIndex* active_chain_tip = m_node.chainman->ActiveChain().Tip();
454-
BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, prevheights, CreateBlockIndex(active_chain_tip->nHeight + 1, active_chain_tip))); // Sequence locks pass 512 seconds later
454+
BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, prevheights, CreateBlockIndex(active_chain_tip->nHeight + 1, active_chain_tip)));
455455
}
456456

457-
for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
458-
m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i)->nTime -= 512; //undo tricked MTP
457+
for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i) {
458+
CBlockIndex* ancestor{Assert(m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i))};
459+
ancestor->nTime -= SEQUENCE_LOCK_TIME; // undo tricked MTP
460+
}
459461

460462
// absolute height locked
461463
tx.vin[0].prevout.hash = txFirst[2]->GetHash();
@@ -500,9 +502,11 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
500502
// but relative locked txs will if inconsistently added to mempool.
501503
// For now these will still generate a valid template until BIP68 soft fork
502504
BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3U);
503-
// However if we advance height by 1 and time by 512, all of them should be mined
504-
for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
505-
m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast
505+
// However if we advance height by 1 and time by SEQUENCE_LOCK_TIME, all of them should be mined
506+
for (int i = 0; i < CBlockIndex::nMedianTimeSpan; ++i) {
507+
CBlockIndex* ancestor{Assert(m_node.chainman->ActiveChain().Tip()->GetAncestor(m_node.chainman->ActiveChain().Tip()->nHeight - i))};
508+
ancestor->nTime += SEQUENCE_LOCK_TIME; // Trick the MedianTimePast
509+
}
506510
m_node.chainman->ActiveChain().Tip()->nHeight++;
507511
SetMockTime(m_node.chainman->ActiveChain().Tip()->GetMedianTimePast() + 1);
508512

src/validation.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,12 @@ bool CheckSequenceLocksAtTip(CBlockIndex* tip,
246246
maxInputHeight = std::max(maxInputHeight, height);
247247
}
248248
}
249-
lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
249+
// tip->GetAncestor(maxInputHeight) should never return a nullptr
250+
// because maxInputHeight is always less than the tip height.
251+
// It would, however, be a bad bug to continue execution, since a
252+
// LockPoints object with the maxInputBlock member set to nullptr
253+
// signifies no relative lock time.
254+
lp->maxInputBlock = Assert(tip->GetAncestor(maxInputHeight));
250255
}
251256
}
252257
return EvaluateSequenceLocks(index, lockPair);
@@ -4077,10 +4082,11 @@ bool CChainState::ReplayBlocks()
40774082
// Roll forward from the forking point to the new tip.
40784083
int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
40794084
for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4080-
const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
4081-
LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
4085+
const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};
4086+
4087+
LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(), nHeight);
40824088
uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
4083-
if (!RollforwardBlock(pindex, cache)) return false;
4089+
if (!RollforwardBlock(&pindex, cache)) return false;
40844090
}
40854091

40864092
cache.SetBestBlock(pindexNew->GetBlockHash());

src/versionbits.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
// Distributed under the MIT software license, see the accompanying
33
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
44

5-
#include <versionbits.h>
65
#include <consensus/params.h>
6+
#include <util/check.h>
7+
#include <versionbits.h>
78

89
ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const
910
{
@@ -158,7 +159,7 @@ int AbstractThresholdConditionChecker::GetStateSinceHeightFor(const CBlockIndex*
158159
// if we are computing for the last block of a period, then pindexPrev points to the second to last block of the period, and
159160
// if we are computing for the first block of a period, then pindexPrev points to the last block of the previous period.
160161
// The parent of the genesis block is represented by nullptr.
161-
pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod));
162+
pindexPrev = Assert(pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod)));
162163

163164
const CBlockIndex* previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod);
164165

0 commit comments

Comments
 (0)