Skip to content

Commit 842dc24

Browse files
committed
Accurate sigop/sighash accounting and limits
Adds a ValidationCostTracker class that is passed to CheckInputs() / CScriptCheck() to keep track of the exact number of signature operations required to validate a block, and the exact number of bytes hashed to compute signature hashes. Also extends CHashWriter to keep track of number of bytes hashed. Signature operations per block are limited to MAX_BLOCK_SIGOPS (unchanged at 20,000) Bytes hashed to compute signatures is limited to MAX_BLOCK_SIGHASH (1.3 GB in this commit).
1 parent d86ff54 commit 842dc24

8 files changed

Lines changed: 143 additions & 30 deletions

File tree

src/consensus/consensus.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@
1010
static const unsigned int MAX_BLOCK_SIZE = 2000000;
1111
/** The old block size limit */
1212
static const unsigned int OLD_MAX_BLOCK_SIZE = 1000000;
13-
/** pre-2MB-fork limit on signature operations in a block */
13+
/** limit on signature operations in a block */
1414
static const unsigned int MAX_BLOCK_SIGOPS = OLD_MAX_BLOCK_SIZE/50;
15+
/** limit on number of bytes hashed to compute signatures in a block */
16+
static const unsigned int MAX_BLOCK_SIGHASH = 1300 * 1000 * 1000; // 1.3 gigabytes
1517
/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
1618
static const int COINBASE_MATURITY = 100;
1719

src/hash.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,15 +123,17 @@ class CHashWriter
123123
{
124124
private:
125125
CHash256 ctx;
126+
size_t nBytesHashed;
126127

127128
public:
128129
int nType;
129130
int nVersion;
130131

131-
CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {}
132+
CHashWriter(int nTypeIn, int nVersionIn) : nBytesHashed(0), nType(nTypeIn), nVersion(nVersionIn) {}
132133

133134
CHashWriter& write(const char *pch, size_t size) {
134135
ctx.Write((const unsigned char*)pch, size);
136+
nBytesHashed += size;
135137
return (*this);
136138
}
137139

@@ -141,6 +143,9 @@ class CHashWriter
141143
ctx.Finalize((unsigned char*)&result);
142144
return result;
143145
}
146+
size_t GetNumBytesHashed() const {
147+
return nBytesHashed;
148+
}
144149

145150
template<typename T>
146151
CHashWriter& operator<<(const T& obj) {

src/main.cpp

Lines changed: 53 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,7 +1092,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
10921092

10931093
// Check against previous transactions
10941094
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
1095-
if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1095+
if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, NULL))
10961096
{
10971097
return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
10981098
}
@@ -1106,7 +1106,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
11061106
// There is a similar check in CreateNewBlock() to prevent creating
11071107
// invalid blocks, however allowing such transactions into the mempool
11081108
// can be exploited as a DoS attack.
1109-
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1109+
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, NULL))
11101110
{
11111111
return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
11121112
}
@@ -1445,14 +1445,23 @@ void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCach
14451445
}
14461446

14471447
bool CScriptCheck::operator()() {
1448+
if (costTracker && !costTracker->IsWithinLimits())
1449+
return false; // Don't do any more checks if already past limits
1450+
14481451
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1449-
if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1452+
CachingTransactionSignatureChecker checker(ptxTo, nIn, cacheStore);
1453+
if (!VerifyScript(scriptSig, scriptPubKey, nFlags, checker, &error)) {
14501454
return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
14511455
}
1456+
if (costTracker) {
1457+
if (!costTracker->Update(ptxTo->GetHash(), checker.GetNumSigops(), checker.GetBytesHashed()))
1458+
return ::error("CScriptCheck(): %s:%d sigop and/or sighash byte limit exceeded",
1459+
ptxTo->GetHash().ToString(), nIn);
1460+
}
14521461
return true;
14531462
}
14541463

1455-
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1464+
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, ValidationCostTracker* costTracker, std::vector<CScriptCheck> *pvChecks)
14561465
{
14571466
if (!tx.IsCoinBase())
14581467
{
@@ -1521,7 +1530,7 @@ bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsVi
15211530
assert(coins);
15221531

15231532
// Verify signature
1524-
CScriptCheck check(*coins, tx, i, flags, cacheStore);
1533+
CScriptCheck check(costTracker, *coins, tx, i, flags, cacheStore);
15251534
if (pvChecks) {
15261535
pvChecks->push_back(CScriptCheck());
15271536
check.swap(pvChecks->back());
@@ -1533,7 +1542,7 @@ bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsVi
15331542
// arguments; if so, don't trigger DoS protection to
15341543
// avoid splitting the network between upgraded and
15351544
// non-upgraded nodes.
1536-
CScriptCheck check(*coins, tx, i,
1545+
CScriptCheck check(NULL, *coins, tx, i,
15371546
flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
15381547
if (check())
15391548
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
@@ -1906,12 +1915,18 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
19061915

19071916
CBlockUndo blockundo;
19081917

1918+
int64_t nTimeStart = GetTimeMicros();
1919+
1920+
// Pre-fork, legacy sigop counting is used, unlimited resource tracker
1921+
// Post-fork, accurately counted sigop/sighash limits are used
1922+
ValidationCostTracker costTracker(MaxBlockSigops(block.nTime), MaxBlockSighash(block.nTime));
1923+
19091924
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
19101925

1911-
int64_t nTimeStart = GetTimeMicros();
19121926
CAmount nFees = 0;
19131927
int nInputs = 0;
1914-
unsigned int nSigOps = 0;
1928+
uint32_t nSigOps = 0;
1929+
uint32_t nMaxLegacySigops = MaxLegacySigops(block.nTime);
19151930
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
19161931
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
19171932
vPos.reserve(block.vtx.size());
@@ -1922,7 +1937,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
19221937

19231938
nInputs += tx.vin.size();
19241939
nSigOps += GetLegacySigOpCount(tx);
1925-
if (nSigOps > MAX_BLOCK_SIGOPS)
1940+
if (nSigOps > nMaxLegacySigops)
19261941
return state.DoS(100, error("ConnectBlock(): too many sigops"),
19271942
REJECT_INVALID, "bad-blk-sigops");
19281943

@@ -1938,15 +1953,16 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
19381953
// this is to prevent a "rogue miner" from creating
19391954
// an incredibly-expensive-to-validate block.
19401955
nSigOps += GetP2SHSigOpCount(tx, view);
1941-
if (nSigOps > MAX_BLOCK_SIGOPS)
1956+
if (nSigOps > nMaxLegacySigops)
19421957
return state.DoS(100, error("ConnectBlock(): too many sigops"),
19431958
REJECT_INVALID, "bad-blk-sigops");
19441959
}
19451960

19461961
nFees += view.GetValueIn(tx)-tx.GetValueOut();
19471962

19481963
std::vector<CScriptCheck> vChecks;
1949-
if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1964+
if (!CheckInputs(tx, state, view, fScriptChecks, flags, false,
1965+
&costTracker, nScriptCheckThreads ? &vChecks : NULL))
19501966
return false;
19511967
control.Add(vChecks);
19521968
}
@@ -1972,6 +1988,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
19721988

19731989
if (!control.Wait())
19741990
return state.DoS(100, false);
1991+
19751992
int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
19761993
LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
19771994

@@ -2170,7 +2187,7 @@ void static UpdateTip(CBlockIndex *pindexNew) {
21702187
const CBlockIndex* pindex = chainActive.Tip();
21712188
for (int i = 0; i < 100 && pindex != NULL; i++)
21722189
{
2173-
if (!Block::VersionKnown(pindex->nVersion))
2190+
if (!CBlock::VersionKnown(pindex->nVersion))
21742191
++nUpgraded;
21752192
pindex = pindex->pprev;
21762193
}
@@ -2805,7 +2822,7 @@ bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bo
28052822
{
28062823
nSigOps += GetLegacySigOpCount(tx);
28072824
}
2808-
if (nSigOps > MAX_BLOCK_SIGOPS)
2825+
if (nSigOps > MaxLegacySigops(block.nTime))
28092826
return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
28102827
REJECT_INVALID, "bad-blk-sigops", true);
28112828

@@ -5270,6 +5287,29 @@ unsigned int MaxBlockSize(uint32_t nBlockTime)
52705287
return MAX_BLOCK_SIZE;
52715288
}
52725289

5290+
/** Maximum size of a block */
5291+
unsigned int MaxBlockSigops(uint32_t nBlockTime)
5292+
{
5293+
if (nBlockTime < sizeForkTime.load())
5294+
return std::numeric_limits<uint32_t>::max(); // Use old way of counting
5295+
return MAX_BLOCK_SIGOPS;
5296+
}
5297+
/** Maximum size of a block */
5298+
unsigned int MaxBlockSighash(uint32_t nBlockTime)
5299+
{
5300+
if (nBlockTime < sizeForkTime.load())
5301+
return std::numeric_limits<uint32_t>::max(); // no limit before
5302+
return MAX_BLOCK_SIGHASH;
5303+
}
5304+
5305+
/** Maximum legacy (miscounted) sigops in a block */
5306+
uint32_t MaxLegacySigops(uint32_t nBlockTime)
5307+
{
5308+
if (nBlockTime < sizeForkTime.load())
5309+
return MAX_BLOCK_SIGOPS;
5310+
return std::numeric_limits<uint32_t>::max(); // Use accurately-counted limit
5311+
}
5312+
52735313
uint32_t ForkBits(uint32_t nTime) {
52745314
uint32_t bits = 0;
52755315
AssertLockHeld(cs_main);

src/main.h

Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,10 @@
3535
#include <utility>
3636
#include <vector>
3737

38+
#include <boost/atomic.hpp>
3839
#include <boost/unordered_map.hpp>
3940

41+
class ValidationCostTracker;
4042
class CBlockIndex;
4143
class CBlockTreeDB;
4244
class CBloomFilter;
@@ -315,7 +317,8 @@ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& ma
315317
* instead of being performed inline.
316318
*/
317319
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
318-
unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks = NULL);
320+
unsigned int flags, bool cacheStore, ValidationCostTracker* costTracker,
321+
std::vector<CScriptCheck> *pvChecks = NULL);
319322

320323
/** Apply the effects of this transaction on the UTXO set represented by view */
321324
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight);
@@ -343,13 +346,52 @@ bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
343346
*/
344347
bool CheckFinalTx(const CTransaction &tx, int flags = -1);
345348

349+
/**
350+
* Class that keeps track of number of signature operations
351+
* and bytes hashed to compute signature hashes.
352+
*/
353+
class ValidationCostTracker
354+
{
355+
private:
356+
mutable CCriticalSection cs;
357+
uint32_t nSigops;
358+
const uint32_t nMaxSigops;
359+
uint32_t nSighashBytes;
360+
const uint32_t nMaxSighashBytes;
361+
362+
public:
363+
ValidationCostTracker(uint32_t nMaxSigopsIn, uint32_t nMaxSighashBytesIn) :
364+
nSigops(0), nMaxSigops(nMaxSigopsIn),
365+
nSighashBytes(0), nMaxSighashBytes(nMaxSighashBytesIn) { }
366+
367+
bool IsWithinLimits() const {
368+
LOCK(cs);
369+
return (nSigops <= nMaxSigops && nSighashBytes <= nMaxSighashBytes);
370+
}
371+
bool Update(const uint256& txid, uint32_t nSigopsIn, uint32_t nSighashBytesIn) {
372+
LOCK(cs);
373+
nSigops += nSigopsIn;
374+
nSighashBytes += nSighashBytesIn;
375+
return (nSigops <= nMaxSigops && nSighashBytes <= nMaxSighashBytes);
376+
}
377+
uint32_t GetSigOps() const {
378+
LOCK(cs);
379+
return nSigops;
380+
}
381+
uint32_t GetSighashBytes() const {
382+
LOCK(cs);
383+
return nSighashBytes;
384+
}
385+
};
386+
346387
/**
347388
* Closure representing one script verification
348389
* Note that this stores references to the spending transaction
349390
*/
350391
class CScriptCheck
351392
{
352393
private:
394+
ValidationCostTracker* costTracker;
353395
CScript scriptPubKey;
354396
const CTransaction *ptxTo;
355397
unsigned int nIn;
@@ -358,14 +400,15 @@ class CScriptCheck
358400
ScriptError error;
359401

360402
public:
361-
CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
362-
CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) :
363-
scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
403+
CScriptCheck(): costTracker(NULL), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
404+
CScriptCheck(ValidationCostTracker* costTrackerIn, const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) :
405+
costTracker(costTrackerIn), scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
364406
ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR) { }
365407

366408
bool operator()();
367409

368410
void swap(CScriptCheck &check) {
411+
std::swap(costTracker, check.costTracker);
369412
scriptPubKey.swap(check.scriptPubKey);
370413
std::swap(ptxTo, check.ptxTo);
371414
std::swap(nIn, check.nIn);
@@ -495,6 +538,15 @@ extern CBlockTreeDB *pblocktree;
495538
/** Maximum size of a block */
496539
unsigned int MaxBlockSize(uint32_t nBlockTime);
497540

541+
/** Max accurately-counted sigops in a block */
542+
uint32_t MaxBlockSigops(uint32_t nBlockTime);
543+
544+
/** Max accurately-counted bytes hashed to compute signatures, per block */
545+
uint32_t MaxBlockSighash(uint32_t nBlockTime);
546+
547+
/** Maximum number of legacy sigops in a block */
548+
uint32_t MaxLegacySigops(uint32_t nBlockTime);
549+
498550
/** What forks we are expressing support for */
499551
uint32_t ForkBits(uint32_t nTime);
500552

src/miner.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
9999
if(!pblocktemplate.get())
100100
return NULL;
101101
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
102+
ValidationCostTracker resourceTracker(std::numeric_limits<size_t>::max(), std::numeric_limits<size_t>::max());
102103

103104
// -regtest only: allow overriding block.nVersion with
104105
// -blockversion=N to test forking scenarios
@@ -244,6 +245,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
244245
uint64_t nBlockTx = 0;
245246
int nBlockSigOps = 100;
246247
bool fSortedByFee = (nBlockPrioritySize <= 0);
248+
uint32_t nMaxLegacySigops = MaxLegacySigops(pblock->nTime);
247249

248250
TxPriorityCompare comparer(fSortedByFee);
249251
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
@@ -265,7 +267,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
265267

266268
// Legacy limits on sigOps:
267269
unsigned int nTxSigOps = GetLegacySigOpCount(tx);
268-
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
270+
if (nBlockSigOps + nTxSigOps >= nMaxLegacySigops)
269271
continue;
270272

271273
// Skip free transactions if we're past the minimum block size:
@@ -292,14 +294,14 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
292294
CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
293295

294296
nTxSigOps += GetP2SHSigOpCount(tx, view);
295-
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
297+
if (nBlockSigOps + nTxSigOps >= nMaxLegacySigops)
296298
continue;
297299

298300
// Note that flags: we don't want to set mempool/IsStandard()
299301
// policy here, but we still have to ensure that the block we
300302
// create only contains transactions that are valid in new blocks.
301303
CValidationState state;
302-
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
304+
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, &resourceTracker))
303305
continue;
304306

305307
UpdateCoins(tx, state, view, nHeight);

src/script/interpreter.cpp

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,7 +1075,7 @@ class CTransactionSignatureSerializer {
10751075

10761076
} // anon namespace
10771077

1078-
uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1078+
uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, size_t* nHashedOut)
10791079
{
10801080
static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
10811081
if (nIn >= txTo.vin.size()) {
@@ -1097,6 +1097,8 @@ uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsig
10971097
// Serialize and hash
10981098
CHashWriter ss(SER_GETHASH, 0);
10991099
ss << txTmp << nHashType;
1100+
if (nHashedOut != NULL)
1101+
*nHashedOut = ss.GetNumBytesHashed();
11001102
return ss.GetHash();
11011103
}
11021104

@@ -1105,7 +1107,8 @@ bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned cha
11051107
return pubkey.Verify(sighash, vchSig);
11061108
}
11071109

1108-
bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode) const
1110+
bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey,
1111+
const CScript& scriptCode) const
11091112
{
11101113
CPubKey pubkey(vchPubKey);
11111114
if (!pubkey.IsValid())
@@ -1118,7 +1121,10 @@ bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn
11181121
int nHashType = vchSig.back();
11191122
vchSig.pop_back();
11201123

1121-
uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType);
1124+
size_t nHashed = 0;
1125+
uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, &nHashed);
1126+
nBytesHashed += nHashed;
1127+
++nSigops;
11221128

11231129
if (!VerifySignature(vchSig, pubkey, sighash))
11241130
return false;

0 commit comments

Comments
 (0)