PIVX Core  5.6.99
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 developers
3 // Copyright (c) 2015-2020 The PIVX 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 "consensus/consensus.h"
10 #include "hash.h"
11 #include "primitives/block.h" // for MAX_BLOCK_SIZE
12 #include "utilstrencodings.h"
13 
14 
15 std::vector<unsigned char> BitsToBytes(const std::vector<bool>& bits)
16 {
17  std::vector<unsigned char> ret((bits.size() + 7) / 8);
18  for (unsigned int p = 0; p < bits.size(); p++) {
19  ret[p / 8] |= bits[p] << (p % 8);
20  }
21  return ret;
22 }
23 
24 std::vector<bool> BytesToBits(const std::vector<unsigned char>& bytes)
25 {
26  std::vector<bool> ret(bytes.size() * 8);
27  for (unsigned int p = 0; p < ret.size(); p++) {
28  ret[p] = (bytes[p / 8] & (1 << (p % 8))) != 0;
29  }
30  return ret;
31 }
32 
33 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<uint256>* txids)
34 {
35  header = block.GetBlockHeader();
36 
37  std::vector<bool> vMatch;
38  std::vector<uint256> vHashes;
39 
40  vMatch.reserve(block.vtx.size());
41  vHashes.reserve(block.vtx.size());
42 
43  for (unsigned int i = 0; i < block.vtx.size(); i++) {
44  const uint256& hash = block.vtx[i]->GetHash();
45  if (txids && txids->count(hash)) {
46  vMatch.push_back(true);
47  } else if (filter && filter->IsRelevantAndUpdate(*block.vtx[i])) {
48  vMatch.push_back(true);
49  vMatchedTxn.emplace_back(i, hash);
50  } else {
51  vMatch.push_back(false);
52  }
53  vHashes.push_back(hash);
54  }
55 
56  txn = CPartialMerkleTree(vHashes, vMatch);
57 }
58 
59 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256>& vTxid)
60 {
61  if (height == 0) {
62  // hash at height 0 is the txids themself
63  return vTxid[pos];
64  } else {
65  // calculate left hash
66  uint256 left = CalcHash(height - 1, pos * 2, vTxid), right;
67  // calculate right hash if not beyond the end of the array - copy left hash otherwise1
68  if (pos * 2 + 1 < CalcTreeWidth(height - 1))
69  right = CalcHash(height - 1, pos * 2 + 1, vTxid);
70  else
71  right = left;
72  // combine subhashes
73  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
74  }
75 }
76 
77 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch)
78 {
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)
97 {
98  if (nBitsUsed >= vBits.size()) {
99  // overflowed the bits array - failure
100  fBad = true;
101  return UINT256_ZERO;
102  }
103  bool fParentOfMatch = vBits[nBitsUsed++];
104  if (height == 0 || !fParentOfMatch) {
105  // if at height 0, or nothing interesting below, use stored hash and do not descend
106  if (nHashUsed >= vHash.size()) {
107  // overflowed the hash array - failure
108  fBad = true;
109  return UINT256_ZERO;
110  }
111  const uint256& hash = vHash[nHashUsed++];
112  if (height == 0 && fParentOfMatch) // in case of height 0, we have a matched txid
113  vMatch.push_back(hash);
114  return hash;
115  } else {
116  // otherwise, descend into the subtrees to extract matched txids and hashes
117  uint256 left = TraverseAndExtract(height - 1, pos * 2, nBitsUsed, nHashUsed, vMatch), right;
118  if (pos * 2 + 1 < CalcTreeWidth(height - 1))
119  right = TraverseAndExtract(height - 1, pos * 2 + 1, nBitsUsed, nHashUsed, vMatch);
120  else
121  right = left;
122  // and combine them before returning
123  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
124  }
125 }
126 
127 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch) : nTransactions(vTxid.size()), fBad(false)
128 {
129  // reset state
130  vBits.clear();
131  vHash.clear();
132 
133  // calculate height of tree
134  int nHeight = 0;
135  while (CalcTreeWidth(nHeight) > 1)
136  nHeight++;
137 
138  // traverse the partial tree
139  TraverseAndBuild(nHeight, 0, vTxid, vMatch);
140 }
141 
142 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
143 
144 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256>& vMatch)
145 {
146  vMatch.clear();
147  // An empty set will not work
148  if (nTransactions == 0)
149  return UINT256_ZERO;
150  // check for excessively high numbers of transactions
151  if (nTransactions > MAX_BLOCK_SIZE_CURRENT / 60) // 60 is the lower bound for the size of a serialized CTransaction
152  return UINT256_ZERO;
153  // there can never be more hashes provided than one for every txid
154  if (vHash.size() > nTransactions)
155  return UINT256_ZERO;
156  // there must be at least one bit per node in the partial tree, and at least one node per hash
157  if (vBits.size() < vHash.size())
158  return UINT256_ZERO;
159  // calculate height of tree
160  int nHeight = 0;
161  while (CalcTreeWidth(nHeight) > 1)
162  nHeight++;
163  // traverse the partial tree
164  unsigned int nBitsUsed = 0, nHashUsed = 0;
165  uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
166  // verify that no problems occurred during the tree traversal
167  if (fBad)
168  return UINT256_ZERO;
169  // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
170  if ((nBitsUsed + 7) / 8 != (vBits.size() + 7) / 8)
171  return UINT256_ZERO;
172  // verify that all hashes were consumed
173  if (nHashUsed != vHash.size())
174  return UINT256_ZERO;
175  return hashMerkleRoot;
176 }
true
Definition: bls_dkg.cpp:153
false
Definition: bls_dkg.cpp:151
Definition: block.h:80
std::vector< CTransactionRef > vtx
Definition: block.h:83
CBlockHeader GetBlockHeader() const
Definition: block.h:118
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:155
CBlockHeader header
Public only for unit testing.
Definition: merkleblock.h:121
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
Definition: merkleblock.h:130
CPartialMerkleTree txn
Definition: merkleblock.h:122
Data structure that represents a partial merkle tree.
Definition: merkleblock.h:56
unsigned int nTransactions
the total number of transactions in the block
Definition: merkleblock.h:59
std::vector< bool > vBits
node-is-parent-of-matched-txid bits
Definition: merkleblock.h:62
bool fBad
flag set when encountering invalid data
Definition: merkleblock.h:68
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
extract the matching txid's represented by this partial merkle tree.
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch)
recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBu...
Definition: merkleblock.cpp:96
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:77
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:59
unsigned int CalcTreeWidth(int height)
helper function to efficiently calculate the number of nodes at given height in the merkle tree
Definition: merkleblock.h:71
std::vector< uint256 > vHash
txids and internal hashes
Definition: merkleblock.h:65
256-bit opaque blob.
Definition: uint256.h:138
uint256 Hash(const T1 pbegin, const T1 pend)
Compute the 256-bit hash of an object.
Definition: hash.h:173
std::vector< bool > BytesToBits(const std::vector< unsigned char > &bytes)
Definition: merkleblock.cpp:24
std::vector< unsigned char > BitsToBytes(const std::vector< bool > &bits)
Definition: merkleblock.cpp:15
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:175
#define BEGIN(a)
Utilities for converting data from/to strings.
#define END(a)