Branch data Line data Source code
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 <chainparams.h>
7 : : #include <common/system.h>
8 : : #include <consensus/consensus.h>
9 : : #include <consensus/validation.h>
10 : : #include <crypto/sha256.h>
11 : : #include <crypto/siphash.h>
12 : : #include <logging.h>
13 : : #include <random.h>
14 : : #include <streams.h>
15 : : #include <txmempool.h>
16 : : #include <validation.h>
17 : :
18 : : #include <unordered_map>
19 : :
20 : 5 : CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, const uint64_t nonce) :
21 : 5 : nonce(nonce),
22 [ + - ]: 5 : shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) {
23 [ + - ]: 5 : FillShortTxIDSelector();
24 : : //TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase
25 [ - + ]: 5 : prefilledtxn[0] = {0, block.vtx[0]};
26 [ + + ]: 13 : for (size_t i = 1; i < block.vtx.size(); i++) {
27 [ + - ]: 8 : const CTransaction& tx = *block.vtx[i];
28 [ + - ]: 8 : shorttxids[i - 1] = GetShortID(tx.GetWitnessHash());
29 : : }
30 [ + - ]: 15 : }
31 : :
32 : 12 : void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const {
33 : 12 : DataStream stream{};
34 [ + - + - ]: 12 : stream << header << nonce;
35 [ + - ]: 12 : CSHA256 hasher;
36 [ + - ]: 12 : hasher.Write((unsigned char*)&(*stream.begin()), stream.end() - stream.begin());
37 : 12 : uint256 shorttxidhash;
38 [ + - ]: 12 : hasher.Finalize(shorttxidhash.begin());
39 : 12 : shorttxidk0 = shorttxidhash.GetUint64(0);
40 : 12 : shorttxidk1 = shorttxidhash.GetUint64(1);
41 : 12 : }
42 : :
43 : 18 : uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const Wtxid& wtxid) const {
44 : 18 : static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids");
45 : 18 : return SipHashUint256(shorttxidk0, shorttxidk1, wtxid) & 0xffffffffffffL;
46 : : }
47 : :
48 : 6 : ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<CTransactionRef>& extra_txn) {
49 [ + - + - ]: 12 : LogDebug(BCLog::CMPCTBLOCK, "Initializing PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
50 [ + - + + : 6 : if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty()))
+ - ]
51 : : return READ_STATUS_INVALID;
52 [ + - ]: 6 : if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_WEIGHT / MIN_SERIALIZABLE_TRANSACTION_WEIGHT)
53 : : return READ_STATUS_INVALID;
54 : :
55 [ + - + - ]: 6 : if (!header.IsNull() || !txn_available.empty()) return READ_STATUS_INVALID;
56 : :
57 : 6 : header = cmpctblock.header;
58 : 6 : txn_available.resize(cmpctblock.BlockTxCount());
59 : :
60 : 6 : int32_t lastprefilledindex = -1;
61 [ + + ]: 13 : for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) {
62 [ + - ]: 7 : if (cmpctblock.prefilledtxn[i].tx->IsNull())
63 : : return READ_STATUS_INVALID;
64 : :
65 : 7 : lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here
66 [ + - ]: 7 : if (lastprefilledindex > std::numeric_limits<uint16_t>::max())
67 : : return READ_STATUS_INVALID;
68 [ + - ]: 7 : 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 : 7 : txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;
75 : : }
76 : 6 : 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 : 6 : std::unordered_map<uint64_t, uint16_t> shorttxids(cmpctblock.shorttxids.size());
83 : : uint16_t index_offset = 0;
84 [ + + ]: 15 : for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) {
85 [ + + ]: 14 : while (txn_available[i + index_offset])
86 : 5 : index_offset++;
87 [ + - ]: 9 : 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 [ + - ]: 9 : 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 [ + - ]: 6 : if (shorttxids.size() != cmpctblock.shorttxids.size())
104 : : return READ_STATUS_FAILED; // Short ID collision
105 : :
106 [ + - + - ]: 12 : std::vector<bool> have_txn(txn_available.size());
107 : 6 : {
108 [ + - ]: 6 : LOCK(pool->cs);
109 [ + + ]: 10 : for (const auto& tx : pool->txns_randomized) {
110 [ + - ]: 5 : uint64_t shortid = cmpctblock.GetShortID(tx->GetWitnessHash());
111 : 5 : std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
112 [ + - ]: 5 : if (idit != shorttxids.end()) {
113 [ + - ]: 5 : if (!have_txn[idit->second]) {
114 : 5 : txn_available[idit->second] = tx;
115 : 5 : have_txn[idit->second] = true;
116 : 5 : 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 [ # # ]: 0 : if (txn_available[idit->second]) {
122 : 0 : txn_available[idit->second].reset();
123 : 0 : 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 [ + + ]: 5 : if (mempool_count == shorttxids.size())
131 : : break;
132 : : }
133 : 0 : }
134 : :
135 [ + + ]: 17 : for (size_t i = 0; i < extra_txn.size(); i++) {
136 [ + + ]: 12 : if (extra_txn[i] == nullptr) {
137 : 10 : continue;
138 : : }
139 [ + - ]: 2 : uint64_t shortid = cmpctblock.GetShortID(extra_txn[i]->GetWitnessHash());
140 : 2 : std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
141 [ + + ]: 2 : if (idit != shorttxids.end()) {
142 [ + - ]: 1 : if (!have_txn[idit->second]) {
143 : 1 : txn_available[idit->second] = extra_txn[i];
144 : 1 : have_txn[idit->second] = true;
145 : 1 : mempool_count++;
146 : 1 : extra_count++;
147 : : } else {
148 : : // If we find two mempool/extra txn that match the short id, just
149 : : // request it.
150 : : // This should be rare enough that the extra bandwidth doesn't matter,
151 : : // but eating a round-trip due to FillBlock failure would be annoying
152 : : // Note that we don't want duplication between extra_txn and mempool to
153 : : // trigger this case, so we compare witness hashes first
154 [ # # # # ]: 0 : if (txn_available[idit->second] &&
155 [ # # # # ]: 0 : txn_available[idit->second]->GetWitnessHash() != extra_txn[i]->GetWitnessHash()) {
156 : 0 : txn_available[idit->second].reset();
157 : 0 : mempool_count--;
158 : 0 : extra_count--;
159 : : }
160 : : }
161 : : }
162 : : // Though ideally we'd continue scanning for the two-txn-match-shortid case,
163 : : // the performance win of an early exit here is too good to pass up and worth
164 : : // the extra risk.
165 [ + + ]: 2 : if (mempool_count == shorttxids.size())
166 : : break;
167 : : }
168 : :
169 [ + - + - : 12 : LogDebug(BCLog::CMPCTBLOCK, "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of %u bytes\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock));
+ - + - +
- + - ]
170 : :
171 : 6 : return READ_STATUS_OK;
172 : 12 : }
173 : :
174 : 16 : bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const
175 : : {
176 [ + - ]: 16 : if (header.IsNull()) return false;
177 : :
178 [ - + ]: 16 : assert(index < txn_available.size());
179 : 16 : return txn_available[index] != nullptr;
180 : : }
181 : :
182 : 8 : ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing)
183 : : {
184 [ + - ]: 8 : if (header.IsNull()) return READ_STATUS_INVALID;
185 : :
186 : 8 : uint256 hash = header.GetHash();
187 : 8 : block = header;
188 : 8 : block.vtx.resize(txn_available.size());
189 : :
190 : 8 : unsigned int tx_missing_size = 0;
191 : 8 : size_t tx_missing_offset = 0;
192 [ + + ]: 25 : for (size_t i = 0; i < txn_available.size(); i++) {
193 [ + + ]: 19 : if (!txn_available[i]) {
194 [ + + ]: 6 : if (vtx_missing.size() <= tx_missing_offset)
195 : : return READ_STATUS_INVALID;
196 : 4 : block.vtx[i] = vtx_missing[tx_missing_offset++];
197 : 4 : tx_missing_size += block.vtx[i]->GetTotalSize();
198 : : } else
199 : 13 : block.vtx[i] = std::move(txn_available[i]);
200 : : }
201 : :
202 : : // Make sure we can't call FillBlock again.
203 : 6 : header.SetNull();
204 : 6 : txn_available.clear();
205 : :
206 [ + - ]: 6 : if (vtx_missing.size() != tx_missing_offset)
207 : : return READ_STATUS_INVALID;
208 : :
209 [ - + ]: 6 : BlockValidationState state;
210 [ - + - - ]: 6 : CheckBlockFn check_block = m_check_block_mock ? m_check_block_mock : CheckBlock;
211 [ + - + - : 6 : if (!check_block(block, state, Params().GetConsensus(), /*fCheckPoW=*/true, /*fCheckMerkleRoot=*/true)) {
+ + ]
212 : : // TODO: We really want to just check merkle tree manually here,
213 : : // but that is expensive, and CheckBlock caches a block's
214 : : // "checked-status" (in the CBlock?). CBlock should be able to
215 : : // check its own merkle root and cache that check.
216 [ - + ]: 2 : if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED)
217 : : return READ_STATUS_FAILED; // Possible Short ID collision
218 : 0 : return READ_STATUS_CHECKBLOCK_FAILED;
219 : : }
220 : :
221 [ + - + - : 8 : LogDebug(BCLog::CMPCTBLOCK, "Successfully reconstructed block %s with %u txn prefilled, %u txn from mempool (incl at least %u from extra pool) and %u txn (%u bytes) requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size(), tx_missing_size);
+ - + - ]
222 [ + - ]: 4 : if (vtx_missing.size() < 5) {
223 [ + + ]: 6 : for (const auto& tx : vtx_missing) {
224 [ + - + - : 4 : LogDebug(BCLog::CMPCTBLOCK, "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetHash().ToString());
+ - + - +
- ]
225 : : }
226 : : }
227 : :
228 : : return READ_STATUS_OK;
229 : 12 : }
|