Bitcoin Core  24.99.0
P2P Digital Currency
blockencodings.cpp
Go to the documentation of this file.
1 // Copyright (c) 2016-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <blockencodings.h>
6 #include <consensus/consensus.h>
7 #include <consensus/validation.h>
8 #include <chainparams.h>
9 #include <crypto/sha256.h>
10 #include <crypto/siphash.h>
11 #include <random.h>
12 #include <streams.h>
13 #include <txmempool.h>
14 #include <validation.h>
15 #include <util/system.h>
16 
17 #include <unordered_map>
18 
20  nonce(GetRand<uint64_t>()),
21  shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) {
23  //TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase
24  prefilledtxn[0] = {0, block.vtx[0]};
25  for (size_t i = 1; i < block.vtx.size(); i++) {
26  const CTransaction& tx = *block.vtx[i];
27  shorttxids[i - 1] = GetShortID(tx.GetWitnessHash());
28  }
29 }
30 
32  DataStream stream{};
33  stream << header << nonce;
34  CSHA256 hasher;
35  hasher.Write((unsigned char*)&(*stream.begin()), stream.end() - stream.begin());
36  uint256 shorttxidhash;
37  hasher.Finalize(shorttxidhash.begin());
38  shorttxidk0 = shorttxidhash.GetUint64(0);
39  shorttxidk1 = shorttxidhash.GetUint64(1);
40 }
41 
42 uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256& txhash) const {
43  static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids");
44  return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL;
45 }
46 
47 
48 
49 ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn) {
50  if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty()))
51  return READ_STATUS_INVALID;
52  if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_WEIGHT / MIN_SERIALIZABLE_TRANSACTION_WEIGHT)
53  return READ_STATUS_INVALID;
54 
55  if (!header.IsNull() || !txn_available.empty()) return READ_STATUS_INVALID;
56 
57  header = cmpctblock.header;
58  txn_available.resize(cmpctblock.BlockTxCount());
59 
60  int32_t lastprefilledindex = -1;
61  for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) {
62  if (cmpctblock.prefilledtxn[i].tx->IsNull())
63  return READ_STATUS_INVALID;
64 
65  lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here
66  if (lastprefilledindex > std::numeric_limits<uint16_t>::max())
67  return READ_STATUS_INVALID;
68  if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) {
69  // If we are inserting a tx at an index greater than our full list of shorttxids
70  // plus the number of prefilled txn we've inserted, then we have txn for which we
71  // have neither a prefilled txn or a shorttxid!
72  return READ_STATUS_INVALID;
73  }
74  txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;
75  }
76  prefilled_count = cmpctblock.prefilledtxn.size();
77 
78  // Calculate map of txids -> positions and check mempool to see what we have (or don't)
79  // Because well-formed cmpctblock messages will have a (relatively) uniform distribution
80  // of short IDs, any highly-uneven distribution of elements can be safely treated as a
81  // READ_STATUS_FAILED.
82  std::unordered_map<uint64_t, uint16_t> shorttxids(cmpctblock.shorttxids.size());
83  uint16_t index_offset = 0;
84  for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) {
85  while (txn_available[i + index_offset])
86  index_offset++;
87  shorttxids[cmpctblock.shorttxids[i]] = i + index_offset;
88  // To determine the chance that the number of entries in a bucket exceeds N,
89  // we use the fact that the number of elements in a single bucket is
90  // binomially distributed (with n = the number of shorttxids S, and p =
91  // 1 / the number of buckets), that in the worst case the number of buckets is
92  // equal to S (due to std::unordered_map having a default load factor of 1.0),
93  // and that the chance for any bucket to exceed N elements is at most
94  // buckets * (the chance that any given bucket is above N elements).
95  // Thus: P(max_elements_per_bucket > N) <= S * (1 - cdf(binomial(n=S,p=1/S), N)).
96  // If we assume blocks of up to 16000, allowing 12 elements per bucket should
97  // only fail once per ~1 million block transfers (per peer and connection).
98  if (shorttxids.bucket_size(shorttxids.bucket(cmpctblock.shorttxids[i])) > 12)
99  return READ_STATUS_FAILED;
100  }
101  // TODO: in the shortid-collision case, we should instead request both transactions
102  // which collided. Falling back to full-block-request here is overkill.
103  if (shorttxids.size() != cmpctblock.shorttxids.size())
104  return READ_STATUS_FAILED; // Short ID collision
105 
106  std::vector<bool> have_txn(txn_available.size());
107  {
108  LOCK(pool->cs);
109  for (size_t i = 0; i < pool->vTxHashes.size(); i++) {
110  uint64_t shortid = cmpctblock.GetShortID(pool->vTxHashes[i].first);
111  std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
112  if (idit != shorttxids.end()) {
113  if (!have_txn[idit->second]) {
114  txn_available[idit->second] = pool->vTxHashes[i].second->GetSharedTx();
115  have_txn[idit->second] = true;
116  mempool_count++;
117  } else {
118  // If we find two mempool txn that match the short id, just request it.
119  // This should be rare enough that the extra bandwidth doesn't matter,
120  // but eating a round-trip due to FillBlock failure would be annoying
121  if (txn_available[idit->second]) {
122  txn_available[idit->second].reset();
123  mempool_count--;
124  }
125  }
126  }
127  // Though ideally we'd continue scanning for the two-txn-match-shortid case,
128  // the performance win of an early exit here is too good to pass up and worth
129  // the extra risk.
130  if (mempool_count == shorttxids.size())
131  break;
132  }
133  }
134 
135  for (size_t i = 0; i < extra_txn.size(); i++) {
136  uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first);
137  std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
138  if (idit != shorttxids.end()) {
139  if (!have_txn[idit->second]) {
140  txn_available[idit->second] = extra_txn[i].second;
141  have_txn[idit->second] = true;
142  mempool_count++;
143  extra_count++;
144  } else {
145  // If we find two mempool/extra txn that match the short id, just
146  // request it.
147  // This should be rare enough that the extra bandwidth doesn't matter,
148  // but eating a round-trip due to FillBlock failure would be annoying
149  // Note that we don't want duplication between extra_txn and mempool to
150  // trigger this case, so we compare witness hashes first
151  if (txn_available[idit->second] &&
152  txn_available[idit->second]->GetWitnessHash() != extra_txn[i].second->GetWitnessHash()) {
153  txn_available[idit->second].reset();
154  mempool_count--;
155  extra_count--;
156  }
157  }
158  }
159  // Though ideally we'd continue scanning for the two-txn-match-shortid case,
160  // the performance win of an early exit here is too good to pass up and worth
161  // the extra risk.
162  if (mempool_count == shorttxids.size())
163  break;
164  }
165 
166  LogPrint(BCLog::CMPCTBLOCK, "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of size %lu\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock, PROTOCOL_VERSION));
167 
168  return READ_STATUS_OK;
169 }
170 
172 {
173  if (header.IsNull()) return false;
174 
175  assert(index < txn_available.size());
176  return txn_available[index] != nullptr;
177 }
178 
179 ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing)
180 {
181  if (header.IsNull()) return READ_STATUS_INVALID;
182 
183  uint256 hash = header.GetHash();
184  block = header;
185  block.vtx.resize(txn_available.size());
186 
187  size_t tx_missing_offset = 0;
188  for (size_t i = 0; i < txn_available.size(); i++) {
189  if (!txn_available[i]) {
190  if (vtx_missing.size() <= tx_missing_offset)
191  return READ_STATUS_INVALID;
192  block.vtx[i] = vtx_missing[tx_missing_offset++];
193  } else
194  block.vtx[i] = std::move(txn_available[i]);
195  }
196 
197  // Make sure we can't call FillBlock again.
198  header.SetNull();
199  txn_available.clear();
200 
201  if (vtx_missing.size() != tx_missing_offset)
202  return READ_STATUS_INVALID;
203 
204  BlockValidationState state;
206  if (!check_block(block, state, Params().GetConsensus(), /*fCheckPoW=*/true, /*fCheckMerkleRoot=*/true)) {
207  // TODO: We really want to just check merkle tree manually here,
208  // but that is expensive, and CheckBlock caches a block's
209  // "checked-status" (in the CBlock?). CBlock should be able to
210  // check its own merkle root and cache that check.
212  return READ_STATUS_FAILED; // Possible Short ID collision
214  }
215 
216  LogPrint(BCLog::CMPCTBLOCK, "Successfully reconstructed block %s with %lu txn prefilled, %lu txn from mempool (incl at least %lu from extra pool) and %lu txn requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size());
217  if (vtx_missing.size() < 5) {
218  for (const auto& tx : vtx_missing) {
219  LogPrint(BCLog::CMPCTBLOCK, "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetHash().ToString());
220  }
221  }
222 
223  return READ_STATUS_OK;
224 }
@ READ_STATUS_OK
@ READ_STATUS_INVALID
@ READ_STATUS_CHECKBLOCK_FAILED
@ READ_STATUS_FAILED
enum ReadStatus_t ReadStatus
std::vector< std::pair< uint256, CTransactionRef > > extra_txn
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:94
void FillShortTxIDSelector() const
std::vector< PrefilledTransaction > prefilledtxn
uint64_t GetShortID(const uint256 &txhash) const
static constexpr int SHORTTXIDS_LENGTH
std::vector< uint64_t > shorttxids
void SetNull()
Definition: block.h:39
uint256 GetHash() const
Definition: block.cpp:11
bool IsNull() const
Definition: block.h:49
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
A hasher class for SHA-256.
Definition: sha256.h:14
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:707
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:681
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
const uint256 & GetWitnessHash() const
Definition: transaction.h:338
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:405
unsigned long size() const
Definition: txmempool.h:648
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:186
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< std::pair< uint256, CTransactionRef >> &extra_txn)
const CTxMemPool * pool
CheckBlockFn m_check_block_mock
std::vector< CTransactionRef > txn_available
bool IsTxAvailable(size_t index) const
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
std::function< bool(const CBlock &, BlockValidationState &, const Consensus::Params &, bool, bool)> CheckBlockFn
Result GetResult() const
Definition: validation.h:124
constexpr uint64_t GetUint64(int pos) const
Definition: uint256.h:75
std::string ToString() const
Definition: uint256.cpp:55
constexpr unsigned char * begin()
Definition: uint256.h:67
256-bit opaque blob.
Definition: uint256.h:105
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
static const size_t MIN_SERIALIZABLE_TRANSACTION_WEIGHT
Definition: consensus.h:24
#define LogPrint(category,...)
Definition: logging.h:245
unsigned int nonce
Definition: miner_tests.cpp:72
@ CMPCTBLOCK
Definition: logging.h:52
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition: random.h:80
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1109
uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256 &val)
Optimized SipHash-2-4 implementation for uint256.
Definition: siphash.cpp:94
#define LOCK(cs)
Definition: sync.h:258
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12