PRCYCoin  2.0.0.7rc1
P2P Digital Currency
merkleblock.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2015-2018 The PIVX developers
4 // Copyright (c) 2018-2020 The DAPS Project developers
5 // Distributed under the MIT software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 
8 #include "merkleblock.h"
9 
10 #include "consensus/consensus.h"
11 #include "hash.h"
12 #include "primitives/block.h" // for MAX_BLOCK_SIZE
13 #include "utilstrencodings.h"
14 
15 
17 {
18  header = block.GetBlockHeader();
19 
20  std::vector<bool> vMatch;
21  std::vector<uint256> vHashes;
22 
23  vMatch.reserve(block.vtx.size());
24  vHashes.reserve(block.vtx.size());
25 
26  for (unsigned int i = 0; i < block.vtx.size(); i++) {
27  const uint256& hash = block.vtx[i].GetHash();
28  if (filter.IsRelevantAndUpdate(block.vtx[i])) {
29  vMatch.push_back(true);
30  vMatchedTxn.push_back(std::make_pair(i, hash));
31  } else
32  vMatch.push_back(false);
33  vHashes.push_back(hash);
34  }
35 
36  txn = CPartialMerkleTree(vHashes, vMatch);
37 }
38 
39 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256>& vTxid)
40 {
41  //we can never have zero txs in a merkle block, we always need the coinbase tx
42  //if we do not have this assert, we can hit a memory access violation when indexing into vTxid
43  assert(vTxid.size() != 0);
44  if (height == 0) {
45  // hash at height 0 is the txids themself
46  return vTxid[pos];
47  } else {
48  // calculate left hash
49  uint256 left = CalcHash(height - 1, pos * 2, vTxid), right;
50  // calculate right hash if not beyond the end of the array - copy left hash otherwise1
51  if (pos * 2 + 1 < CalcTreeWidth(height - 1))
52  right = CalcHash(height - 1, pos * 2 + 1, vTxid);
53  else
54  right = left;
55  // combine subhashes
56  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
57  }
58 }
59 
60 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch)
61 {
62  // determine whether this node is the parent of at least one matched txid
63  bool fParentOfMatch = false;
64  for (unsigned int p = pos << height; p < (pos + 1) << height && p < nTransactions; p++)
65  fParentOfMatch |= vMatch[p];
66  // store as flag bit
67  vBits.push_back(fParentOfMatch);
68  if (height == 0 || !fParentOfMatch) {
69  // if at height 0, or nothing interesting below, store hash and stop
70  vHash.push_back(CalcHash(height, pos, vTxid));
71  } else {
72  // otherwise, don't store any hash, but descend into the subtrees
73  TraverseAndBuild(height - 1, pos * 2, vTxid, vMatch);
74  if (pos * 2 + 1 < CalcTreeWidth(height - 1))
75  TraverseAndBuild(height - 1, pos * 2 + 1, vTxid, vMatch);
76  }
77 }
78 
79 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int& nBitsUsed, unsigned int& nHashUsed, std::vector<uint256>& vMatch)
80 {
81  if (nBitsUsed >= vBits.size()) {
82  // overflowed the bits array - failure
83  fBad = true;
84  return UINT256_ZERO;
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_ZERO;
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  return hash;
98  } else {
99  // otherwise, descend into the subtrees to extract matched txids and hashes
100  uint256 left = TraverseAndExtract(height - 1, pos * 2, nBitsUsed, nHashUsed, vMatch), right;
101  if (pos * 2 + 1 < CalcTreeWidth(height - 1))
102  right = TraverseAndExtract(height - 1, pos * 2 + 1, nBitsUsed, nHashUsed, vMatch);
103  else
104  right = left;
105  // and combine them before returning
106  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
107  }
108 }
109 
110 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch) : nTransactions(vTxid.size()), fBad(false)
111 {
112  // reset state
113  vBits.clear();
114  vHash.clear();
115 
116  // calculate height of tree
117  int nHeight = 0;
118  while (CalcTreeWidth(nHeight) > 1)
119  nHeight++;
120 
121  // traverse the partial tree
122  TraverseAndBuild(nHeight, 0, vTxid, vMatch);
123 }
124 
125 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
126 
127 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256>& vMatch)
128 {
129  vMatch.clear();
130  // An empty set will not work
131  if (nTransactions == 0)
132  return UINT256_ZERO;
133  // check for excessively high numbers of transactions
134  if (nTransactions > MAX_BLOCK_SIZE_CURRENT / 60) // 60 is the lower bound for the size of a serialized CTransaction
135  return UINT256_ZERO;
136  // there can never be more hashes provided than one for every txid
137  if (vHash.size() > nTransactions)
138  return UINT256_ZERO;
139  // there must be at least one bit per node in the partial tree, and at least one node per hash
140  if (vBits.size() < vHash.size())
141  return UINT256_ZERO;
142  // calculate height of tree
143  int nHeight = 0;
144  while (CalcTreeWidth(nHeight) > 1)
145  nHeight++;
146  // traverse the partial tree
147  unsigned int nBitsUsed = 0, nHashUsed = 0;
148  uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
149  // verify that no problems occured during the tree traversal
150  if (fBad)
151  return UINT256_ZERO;
152  // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
153  if ((nBitsUsed + 7) / 8 != (vBits.size() + 7) / 8)
154  return UINT256_ZERO;
155  // verify that all hashes were consumed
156  if (nHashUsed != vHash.size())
157  return UINT256_ZERO;
158  return hashMerkleRoot;
159 }
block.h
CPartialMerkleTree::TraverseAndExtract
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:79
UINT256_ZERO
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:129
merkleblock.h
CPartialMerkleTree::vBits
std::vector< bool > vBits
node-is-parent-of-matched-txid bits
Definition: merkleblock.h:57
BEGIN
#define BEGIN(a)
Utilities for converting data from/to strings.
Definition: utilstrencodings.h:17
CPartialMerkleTree
Data structure that represents a partial merkle tree.
Definition: merkleblock.h:50
CBloomFilter
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:43
CPartialMerkleTree::ExtractMatches
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
extract the matching txid's represented by this partial merkle tree.
Definition: merkleblock.cpp:127
CMerkleBlock::header
CBlockHeader header
Public only for unit testing.
Definition: merkleblock.h:131
CPartialMerkleTree::CalcHash
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:39
consensus.h
CPartialMerkleTree::TraverseAndBuild
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:60
uint256
256-bit unsigned big integer.
Definition: uint256.h:38
CPartialMerkleTree::fBad
bool fBad
flag set when encountering invalid data
Definition: merkleblock.h:63
CBlock::vtx
std::vector< CTransaction > vtx
Definition: block.h:146
CBlock
Definition: block.h:142
CPartialMerkleTree::nTransactions
unsigned int nTransactions
the total number of transactions in the block
Definition: merkleblock.h:54
END
#define END(a)
Definition: utilstrencodings.h:18
CMerkleBlock::txn
CPartialMerkleTree txn
Definition: merkleblock.h:132
CMerkleBlock::vMatchedTxn
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed)
Definition: merkleblock.h:136
hash.h
CMerkleBlock::CMerkleBlock
CMerkleBlock(const CBlock &block, CBloomFilter &filter)
Create from a CBlock, filtering transactions according to filter Note that this will call IsRelevantA...
Definition: merkleblock.cpp:16
utilstrencodings.h
CBloomFilter::IsRelevantAndUpdate
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes)
Definition: bloom.cpp:131
CPartialMerkleTree::vHash
std::vector< uint256 > vHash
txids and internal hashes
Definition: merkleblock.h:60
CPartialMerkleTree::CalcTreeWidth
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
Hash
std::string Hash(std::string input)
Compute the 256-bit hash of a std::string.
Definition: hash.h:122
CPartialMerkleTree::CPartialMerkleTree
CPartialMerkleTree()
Definition: merkleblock.cpp:125
CBlock::GetBlockHeader
CBlockHeader GetBlockHeader() const
Definition: block.h:194