Merge #9980: Fix mem access violation merkleblock
[bitcoinplatinum.git] / src / merkleblock.cpp
blobf0abea0611b9314c2e150bc8382bdd08172e786f
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "merkleblock.h"
8 #include "hash.h"
9 #include "consensus/consensus.h"
10 #include "utilstrencodings.h"
12 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
14 header = block.GetBlockHeader();
16 std::vector<bool> vMatch;
17 std::vector<uint256> vHashes;
19 vMatch.reserve(block.vtx.size());
20 vHashes.reserve(block.vtx.size());
22 for (unsigned int i = 0; i < block.vtx.size(); i++)
24 const uint256& hash = block.vtx[i]->GetHash();
25 if (filter.IsRelevantAndUpdate(*block.vtx[i]))
27 vMatch.push_back(true);
28 vMatchedTxn.push_back(std::make_pair(i, hash));
30 else
31 vMatch.push_back(false);
32 vHashes.push_back(hash);
35 txn = CPartialMerkleTree(vHashes, vMatch);
38 CMerkleBlock::CMerkleBlock(const CBlock& block, const std::set<uint256>& txids)
40 header = block.GetBlockHeader();
42 std::vector<bool> vMatch;
43 std::vector<uint256> vHashes;
45 vMatch.reserve(block.vtx.size());
46 vHashes.reserve(block.vtx.size());
48 for (unsigned int i = 0; i < block.vtx.size(); i++)
50 const uint256& hash = block.vtx[i]->GetHash();
51 if (txids.count(hash))
52 vMatch.push_back(true);
53 else
54 vMatch.push_back(false);
55 vHashes.push_back(hash);
58 txn = CPartialMerkleTree(vHashes, vMatch);
61 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
62 //we can never have zero txs in a merkle block, we always need the coinbase tx
63 //if we do not have this assert, we can hit a memory access violation when indexing into vTxid
64 assert(vTxid.size() != 0);
65 if (height == 0) {
66 // hash at height 0 is the txids themself
67 return vTxid[pos];
68 } else {
69 // calculate left hash
70 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
71 // calculate right hash if not beyond the end of the array - copy left hash otherwise
72 if (pos*2+1 < CalcTreeWidth(height-1))
73 right = CalcHash(height-1, pos*2+1, vTxid);
74 else
75 right = left;
76 // combine subhashes
77 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
81 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
82 // determine whether this node is the parent of at least one matched txid
83 bool fParentOfMatch = false;
84 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
85 fParentOfMatch |= vMatch[p];
86 // store as flag bit
87 vBits.push_back(fParentOfMatch);
88 if (height==0 || !fParentOfMatch) {
89 // if at height 0, or nothing interesting below, store hash and stop
90 vHash.push_back(CalcHash(height, pos, vTxid));
91 } else {
92 // otherwise, don't store any hash, but descend into the subtrees
93 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
94 if (pos*2+1 < CalcTreeWidth(height-1))
95 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
99 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
100 if (nBitsUsed >= vBits.size()) {
101 // overflowed the bits array - failure
102 fBad = true;
103 return uint256();
105 bool fParentOfMatch = vBits[nBitsUsed++];
106 if (height==0 || !fParentOfMatch) {
107 // if at height 0, or nothing interesting below, use stored hash and do not descend
108 if (nHashUsed >= vHash.size()) {
109 // overflowed the hash array - failure
110 fBad = true;
111 return uint256();
113 const uint256 &hash = vHash[nHashUsed++];
114 if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid
115 vMatch.push_back(hash);
116 vnIndex.push_back(pos);
118 return hash;
119 } else {
120 // otherwise, descend into the subtrees to extract matched txids and hashes
121 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right;
122 if (pos*2+1 < CalcTreeWidth(height-1)) {
123 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex);
124 if (right == left) {
125 // The left and right branches should never be identical, as the transaction
126 // hashes covered by them must each be unique.
127 fBad = true;
129 } else {
130 right = left;
132 // and combine them before returning
133 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
137 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
138 // reset state
139 vBits.clear();
140 vHash.clear();
142 // calculate height of tree
143 int nHeight = 0;
144 while (CalcTreeWidth(nHeight) > 1)
145 nHeight++;
147 // traverse the partial tree
148 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
151 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
153 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
154 vMatch.clear();
155 // An empty set will not work
156 if (nTransactions == 0)
157 return uint256();
158 // check for excessively high numbers of transactions
159 if (nTransactions > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT)
160 return uint256();
161 // there can never be more hashes provided than one for every txid
162 if (vHash.size() > nTransactions)
163 return uint256();
164 // there must be at least one bit per node in the partial tree, and at least one node per hash
165 if (vBits.size() < vHash.size())
166 return uint256();
167 // calculate height of tree
168 int nHeight = 0;
169 while (CalcTreeWidth(nHeight) > 1)
170 nHeight++;
171 // traverse the partial tree
172 unsigned int nBitsUsed = 0, nHashUsed = 0;
173 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex);
174 // verify that no problems occurred during the tree traversal
175 if (fBad)
176 return uint256();
177 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
178 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
179 return uint256();
180 // verify that all hashes were consumed
181 if (nHashUsed != vHash.size())
182 return uint256();
183 return hashMerkleRoot;