1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Limenka developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 6 #include <merkleblock.h>
7 8 #include <hash.h>
9 #include <consensus/consensus.h>
10 #include <consensus/validation.h>
11 12 13 std::vector<unsigned char> BitsToBytes(const std::vector<bool>& bits)
14 {
15 std::vector<unsigned char> ret((bits.size() + 7) / 8);
16 for (unsigned int p = 0; p < bits.size(); p++) {
17 ret[p / 8] |= bits[p] << (p % 8);
18 }
19 return ret;
20 }
21 22 std::vector<bool> BytesToBits(const std::vector<unsigned char>& bytes)
23 {
24 std::vector<bool> ret(bytes.size() * 8);
25 for (unsigned int p = 0; p < ret.size(); p++) {
26 ret[p] = (bytes[p / 8] & (1 << (p % 8))) != 0;
27 }
28 return ret;
29 }
30 31 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<Txid>* txids, const bool prove_witness)
32 {
33 header = block.GetBlockHeader();
34 35 std::vector<bool> vMatch;
36 std::vector<uint256> vHashes;
37 std::vector<uint256> wtxids;
38 39 vMatch.reserve(block.vtx.size());
40 vHashes.reserve(block.vtx.size());
41 if (prove_witness) {
42 wtxids.reserve(block.vtx.size());
43 wtxids.emplace_back(); // generation tx has null wtxid
44 }
45 46 for (unsigned int i = 0; i < block.vtx.size(); i++)
47 {
48 const Txid& hash{block.vtx[i]->GetHash()};
49 if (txids && txids->count(hash)) {
50 vMatch.push_back(true);
51 } else if (filter && filter->IsRelevantAndUpdate(*block.vtx[i])) {
52 vMatch.push_back(true);
53 vMatchedTxn.emplace_back(i, hash);
54 } else {
55 vMatch.push_back(false);
56 }
57 vHashes.push_back(hash);
58 if (prove_witness && i) {
59 wtxids.push_back(block.vtx[i]->GetWitnessHash());
60 }
61 }
62 63 if (prove_witness) {
64 m_prove_gentx = vMatch[0];
65 m_gentx = block.vtx[0];
66 const int witness_commit_outidx = GetWitnessCommitmentIndex(*m_gentx);
67 if (witness_commit_outidx != NO_WITNESS_COMMITMENT) {
68 m_wtxid_tree = CPartialMerkleTree(wtxids, vMatch);
69 vMatch.assign(vMatch.size(), false);
70 }
71 vMatch[0] = true; // include the generation tx in the txid merkle tree so we can check the wtxid root or lack thereof
72 }
73 74 txn = CPartialMerkleTree(vHashes, vMatch);
75 }
76 77 // NOLINTNEXTLINE(misc-no-recursion)
78 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
79 //we can never have zero txs in a merkle block, we always need the coinbase tx
80 //if we do not have this assert, we can hit a memory access violation when indexing into vTxid
81 assert(vTxid.size() != 0);
82 if (height == 0) {
83 // hash at height 0 is the txids themselves
84 return vTxid[pos];
85 } else {
86 // calculate left hash
87 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
88 // calculate right hash if not beyond the end of the array - copy left hash otherwise
89 if (pos*2+1 < CalcTreeWidth(height-1))
90 right = CalcHash(height-1, pos*2+1, vTxid);
91 else
92 right = left;
93 // combine subhashes
94 return Hash(left, right);
95 }
96 }
97 98 // NOLINTNEXTLINE(misc-no-recursion)
99 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
100 // determine whether this node is the parent of at least one matched txid
101 bool fParentOfMatch = false;
102 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
103 fParentOfMatch |= vMatch[p];
104 // store as flag bit
105 vBits.push_back(fParentOfMatch);
106 if (height==0 || !fParentOfMatch) {
107 // if at height 0, or nothing interesting below, store hash and stop
108 vHash.push_back(CalcHash(height, pos, vTxid));
109 } else {
110 // otherwise, don't store any hash, but descend into the subtrees
111 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
112 if (pos*2+1 < CalcTreeWidth(height-1))
113 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
114 }
115 }
116 117 // NOLINTNEXTLINE(misc-no-recursion)
118 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
119 if (nBitsUsed >= vBits.size()) {
120 // overflowed the bits array - failure
121 fBad = true;
122 return uint256();
123 }
124 bool fParentOfMatch = vBits[nBitsUsed++];
125 if (height==0 || !fParentOfMatch) {
126 // if at height 0, or nothing interesting below, use stored hash and do not descend
127 if (nHashUsed >= vHash.size()) {
128 // overflowed the hash array - failure
129 fBad = true;
130 return uint256();
131 }
132 const uint256 &hash = vHash[nHashUsed++];
133 if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid
134 vMatch.push_back(hash);
135 vnIndex.push_back(pos);
136 }
137 return hash;
138 } else {
139 // otherwise, descend into the subtrees to extract matched txids and hashes
140 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right;
141 if (pos*2+1 < CalcTreeWidth(height-1)) {
142 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex);
143 if (right == left) {
144 // The left and right branches should never be identical, as the transaction
145 // hashes covered by them must each be unique.
146 fBad = true;
147 }
148 } else {
149 right = left;
150 }
151 // and combine them before returning
152 return Hash(left, right);
153 }
154 }
155 156 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
157 // reset state
158 vBits.clear();
159 vHash.clear();
160 161 // calculate height of tree
162 int nHeight = 0;
163 while (CalcTreeWidth(nHeight) > 1)
164 nHeight++;
165 166 // traverse the partial tree
167 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
168 }
169 170 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
171 172 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
173 vMatch.clear();
174 // An empty set will not work
175 if (nTransactions == 0)
176 return uint256();
177 // check for excessively high numbers of transactions
178 if (nTransactions > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT)
179 return uint256();
180 // there can never be more hashes provided than one for every txid
181 if (vHash.size() > nTransactions)
182 return uint256();
183 // there must be at least one bit per node in the partial tree, and at least one node per hash
184 if (vBits.size() < vHash.size())
185 return uint256();
186 // calculate height of tree
187 int nHeight = 0;
188 while (CalcTreeWidth(nHeight) > 1)
189 nHeight++;
190 // traverse the partial tree
191 unsigned int nBitsUsed = 0, nHashUsed = 0;
192 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex);
193 // verify that no problems occurred during the tree traversal
194 if (fBad)
195 return uint256();
196 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
197 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
198 return uint256();
199 // verify that all hashes were consumed
200 if (nHashUsed != vHash.size())
201 return uint256();
202 return hashMerkleRoot;
203 }
204