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