Dogecoin Core  1.14.2
P2P Digital Currency
merkleblock.cpp
Go to the documentation of this file.
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.
5 
6 #include "merkleblock.h"
7 
8 #include "hash.h"
9 #include "consensus/consensus.h"
10 #include "utilstrencodings.h"
11 
13 {
14  header = block.GetBlockHeader();
15 
16  std::vector<bool> vMatch;
17  std::vector<uint256> vHashes;
18 
19  vMatch.reserve(block.vtx.size());
20  vHashes.reserve(block.vtx.size());
21 
22  for (unsigned int i = 0; i < block.vtx.size(); i++)
23  {
24  const uint256& hash = block.vtx[i]->GetHash();
25  if (filter.IsRelevantAndUpdate(*block.vtx[i]))
26  {
27  vMatch.push_back(true);
28  vMatchedTxn.push_back(std::make_pair(i, hash));
29  }
30  else
31  vMatch.push_back(false);
32  vHashes.push_back(hash);
33  }
34 
35  txn = CPartialMerkleTree(vHashes, vMatch);
36 }
37 
38 CMerkleBlock::CMerkleBlock(const CBlock& block, const std::set<uint256>& txids)
39 {
40  header = block.GetBlockHeader();
41 
42  std::vector<bool> vMatch;
43  std::vector<uint256> vHashes;
44 
45  vMatch.reserve(block.vtx.size());
46  vHashes.reserve(block.vtx.size());
47 
48  for (unsigned int i = 0; i < block.vtx.size(); i++)
49  {
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);
56  }
57 
58  txn = CPartialMerkleTree(vHashes, vMatch);
59 }
60 
61 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
62  if (height == 0) {
63  // hash at height 0 is the txids themself
64  return vTxid[pos];
65  } else {
66  // calculate left hash
67  uint256 left = CalcHash(height-1, pos*2, vTxid), right;
68  // calculate right hash if not beyond the end of the array - copy left hash otherwise
69  if (pos*2+1 < CalcTreeWidth(height-1))
70  right = CalcHash(height-1, pos*2+1, vTxid);
71  else
72  right = left;
73  // combine subhashes
74  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
75  }
76 }
77 
78 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
79  // determine whether this node is the parent of at least one matched txid
80  bool fParentOfMatch = false;
81  for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
82  fParentOfMatch |= vMatch[p];
83  // store as flag bit
84  vBits.push_back(fParentOfMatch);
85  if (height==0 || !fParentOfMatch) {
86  // if at height 0, or nothing interesting below, store hash and stop
87  vHash.push_back(CalcHash(height, pos, vTxid));
88  } else {
89  // otherwise, don't store any hash, but descend into the subtrees
90  TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
91  if (pos*2+1 < CalcTreeWidth(height-1))
92  TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
93  }
94 }
95 
96 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
97  if (nBitsUsed >= vBits.size()) {
98  // overflowed the bits array - failure
99  fBad = true;
100  return uint256();
101  }
102  bool fParentOfMatch = vBits[nBitsUsed++];
103  if (height==0 || !fParentOfMatch) {
104  // if at height 0, or nothing interesting below, use stored hash and do not descend
105  if (nHashUsed >= vHash.size()) {
106  // overflowed the hash array - failure
107  fBad = true;
108  return uint256();
109  }
110  const uint256 &hash = vHash[nHashUsed++];
111  if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid
112  vMatch.push_back(hash);
113  vnIndex.push_back(pos);
114  }
115  return hash;
116  } else {
117  // otherwise, descend into the subtrees to extract matched txids and hashes
118  uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right;
119  if (pos*2+1 < CalcTreeWidth(height-1)) {
120  right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex);
121  if (right == left) {
122  // The left and right branches should never be identical, as the transaction
123  // hashes covered by them must each be unique.
124  fBad = true;
125  }
126  } else {
127  right = left;
128  }
129  // and combine them before returning
130  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
131  }
132 }
133 
134 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
135  // reset state
136  vBits.clear();
137  vHash.clear();
138 
139  // calculate height of tree
140  int nHeight = 0;
141  while (CalcTreeWidth(nHeight) > 1)
142  nHeight++;
143 
144  // traverse the partial tree
145  TraverseAndBuild(nHeight, 0, vTxid, vMatch);
146 }
147 
148 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
149 
150 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
151  vMatch.clear();
152  // An empty set will not work
153  if (nTransactions == 0)
154  return uint256();
155  // check for excessively high numbers of transactions
156  if (nTransactions > MAX_BLOCK_BASE_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
157  return uint256();
158  // there can never be more hashes provided than one for every txid
159  if (vHash.size() > nTransactions)
160  return uint256();
161  // there must be at least one bit per node in the partial tree, and at least one node per hash
162  if (vBits.size() < vHash.size())
163  return uint256();
164  // calculate height of tree
165  int nHeight = 0;
166  while (CalcTreeWidth(nHeight) > 1)
167  nHeight++;
168  // traverse the partial tree
169  unsigned int nBitsUsed = 0, nHashUsed = 0;
170  uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex);
171  // verify that no problems occurred during the tree traversal
172  if (fBad)
173  return uint256();
174  // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
175  if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
176  return uint256();
177  // verify that all hashes were consumed
178  if (nHashUsed != vHash.size())
179  return uint256();
180  return hashMerkleRoot;
181 }
Definition: block.h:67
std::vector< CTransactionRef > vtx
Definition: block.h:70
CBlockHeader GetBlockHeader() const
Definition: block.h:101
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:45
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes)
Definition: bloom.cpp:134
CBlockHeader header
Public only for unit testing.
Definition: merkleblock.h:129
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed)
Definition: merkleblock.h:134
CPartialMerkleTree txn
Definition: merkleblock.h:130
Data structure that represents a partial merkle tree.
Definition: merkleblock.h:51
unsigned int nTransactions
the total number of transactions in the block
Definition: merkleblock.h:54
std::vector< bool > vBits
node-is-parent-of-matched-txid bits
Definition: merkleblock.h:57
bool fBad
flag set when encountering invalid data
Definition: merkleblock.h:63
uint256 ExtractMatches(std::vector< uint256 > &vMatch, std::vector< unsigned int > &vnIndex)
extract the matching txid's represented by this partial merkle tree and their respective indices with...
void TraverseAndBuild(int height, unsigned int pos, const std::vector< uint256 > &vTxid, const std::vector< bool > &vMatch)
recursive function that traverses tree nodes, storing the data as bits and hashes
Definition: merkleblock.cpp:78
uint256 CalcHash(int height, unsigned int pos, const std::vector< uint256 > &vTxid)
calculate the hash of a node in the merkle tree (at leaf level: the txid's themselves)
Definition: merkleblock.cpp:61
unsigned int CalcTreeWidth(int height)
helper function to efficiently calculate the number of nodes at given height in the merkle tree
Definition: merkleblock.h:66
std::vector< uint256 > vHash
txids and internal hashes
Definition: merkleblock.h:60
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch, std::vector< unsigned int > &vnIndex)
recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBu...
Definition: merkleblock.cpp:96
256-bit opaque blob.
Definition: uint256.h:123
uint256 Hash(const T1 pbegin, const T1 pend)
Compute the 256-bit hash of an object.
Definition: hash.h:70
#define BEGIN(a)
Utilities for converting data from/to strings.
#define END(a)