Skip to content

Commit eb6172a

Browse files
committed
Merge pull request #6918
69d373f Don't wipe the sigcache in TestBlockValidity (Pieter Wuille) 0b9e9dc Evict sigcache entries that are seen in a block (Pieter Wuille) 830e3f3 Make sigcache faster and more efficient (Pieter Wuille)
2 parents 54e8bfe + 69d373f commit eb6172a

File tree

4 files changed

+65
-36
lines changed

4 files changed

+65
-36
lines changed

src/init.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include "policy/policy.h"
2626
#include "rpcserver.h"
2727
#include "script/standard.h"
28+
#include "script/sigcache.h"
2829
#include "scheduler.h"
2930
#include "txdb.h"
3031
#include "txmempool.h"
@@ -437,7 +438,7 @@ std::string HelpMessage(HelpMessageMode mode)
437438
strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
438439
strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
439440
strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 1));
440-
strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
441+
strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
441442
}
442443
strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
443444
CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));

src/main.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1851,7 +1851,8 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
18511851
nFees += view.GetValueIn(tx)-tx.GetValueOut();
18521852

18531853
std::vector<CScriptCheck> vChecks;
1854-
if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1854+
bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1855+
if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, nScriptCheckThreads ? &vChecks : NULL))
18551856
return error("ConnectBlock(): CheckInputs on %s failed with %s",
18561857
tx.GetHash().ToString(), FormatStateMessage(state));
18571858
control.Add(vChecks);

src/script/sigcache.cpp

Lines changed: 57 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,29 @@
55

66
#include "sigcache.h"
77

8+
#include "memusage.h"
89
#include "pubkey.h"
910
#include "random.h"
1011
#include "uint256.h"
1112
#include "util.h"
1213

1314
#include <boost/thread.hpp>
14-
#include <boost/tuple/tuple_comparison.hpp>
15+
#include <boost/unordered_set.hpp>
1516

1617
namespace {
1718

19+
/**
20+
* We're hashing a nonce into the entries themselves, so we don't need extra
21+
* blinding in the set hash computation.
22+
*/
23+
class CSignatureCacheHasher
24+
{
25+
public:
26+
size_t operator()(const uint256& key) const {
27+
return key.GetCheapHash();
28+
}
29+
};
30+
1831
/**
1932
* Valid signature cache, to avoid doing expensive ECDSA signature checking
2033
* twice for every transaction (once when accepted into memory pool, and
@@ -23,52 +36,54 @@ namespace {
2336
class CSignatureCache
2437
{
2538
private:
26-
//! sigdata_type is (signature hash, signature, public key):
27-
typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
28-
std::set< sigdata_type> setValid;
39+
//! Entries are SHA256(nonce || signature hash || public key || signature):
40+
uint256 nonce;
41+
typedef boost::unordered_set<uint256, CSignatureCacheHasher> map_type;
42+
map_type setValid;
2943
boost::shared_mutex cs_sigcache;
3044

45+
3146
public:
47+
CSignatureCache()
48+
{
49+
GetRandBytes(nonce.begin(), 32);
50+
}
51+
52+
void
53+
ComputeEntry(uint256& entry, const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubkey)
54+
{
55+
CSHA256().Write(nonce.begin(), 32).Write(hash.begin(), 32).Write(&pubkey[0], pubkey.size()).Write(&vchSig[0], vchSig.size()).Finalize(entry.begin());
56+
}
57+
3258
bool
33-
Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
59+
Get(const uint256& entry)
3460
{
3561
boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
62+
return setValid.count(entry);
63+
}
3664

37-
sigdata_type k(hash, vchSig, pubKey);
38-
std::set<sigdata_type>::iterator mi = setValid.find(k);
39-
if (mi != setValid.end())
40-
return true;
41-
return false;
65+
void Erase(const uint256& entry)
66+
{
67+
boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
68+
setValid.erase(entry);
4269
}
4370

44-
void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
71+
void Set(const uint256& entry)
4572
{
46-
// DoS prevention: limit cache size to less than 10MB
47-
// (~200 bytes per cache entry times 50,000 entries)
48-
// Since there are a maximum of 20,000 signature operations per block
49-
// 50,000 is a reasonable default.
50-
int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
73+
size_t nMaxCacheSize = GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
5174
if (nMaxCacheSize <= 0) return;
5275

5376
boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
54-
55-
while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
77+
while (memusage::DynamicUsage(setValid) > nMaxCacheSize)
5678
{
57-
// Evict a random entry. Random because that helps
58-
// foil would-be DoS attackers who might try to pre-generate
59-
// and re-use a set of valid signatures just-slightly-greater
60-
// than our cache size.
61-
uint256 randomHash = GetRandHash();
62-
std::vector<unsigned char> unused;
63-
std::set<sigdata_type>::iterator it =
64-
setValid.lower_bound(sigdata_type(randomHash, unused, unused));
65-
if (it == setValid.end())
66-
it = setValid.begin();
67-
setValid.erase(*it);
79+
map_type::size_type s = GetRand(setValid.bucket_count());
80+
map_type::local_iterator it = setValid.begin(s);
81+
if (it != setValid.end(s)) {
82+
setValid.erase(*it);
83+
}
6884
}
6985

70-
sigdata_type k(hash, vchSig, pubKey);
71-
setValid.insert(k);
86+
setValid.insert(entry);
7287
}
7388
};
7489

@@ -78,13 +93,21 @@ bool CachingTransactionSignatureChecker::VerifySignature(const std::vector<unsig
7893
{
7994
static CSignatureCache signatureCache;
8095

81-
if (signatureCache.Get(sighash, vchSig, pubkey))
96+
uint256 entry;
97+
signatureCache.ComputeEntry(entry, sighash, vchSig, pubkey);
98+
99+
if (signatureCache.Get(entry)) {
100+
if (!store) {
101+
signatureCache.Erase(entry);
102+
}
82103
return true;
104+
}
83105

84106
if (!TransactionSignatureChecker::VerifySignature(vchSig, pubkey, sighash))
85107
return false;
86108

87-
if (store)
88-
signatureCache.Set(sighash, vchSig, pubkey);
109+
if (store) {
110+
signatureCache.Set(entry);
111+
}
89112
return true;
90113
}

src/script/sigcache.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@
1010

1111
#include <vector>
1212

13+
// DoS prevention: limit cache size to less than 40MB (over 500000
14+
// entries on 64-bit systems).
15+
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE = 40;
16+
1317
class CPubKey;
1418

1519
class CachingTransactionSignatureChecker : public TransactionSignatureChecker

0 commit comments

Comments
 (0)