PRCYCoin  2.0.0.7rc1
P2P Digital Currency
merkle.cpp
Go to the documentation of this file.
1 #include "merkle.h"
2 #include "hash.h"
3 #include "utilstrencodings.h"
4 
5 /* WARNING! If you're reading this because you're learning about crypto
6  and/or designing a new system that will use merkle trees, keep in mind
7  that the following merkle tree algorithm has a serious flaw related to
8  duplicate txids, resulting in a vulnerability (CVE-2012-2459).
9  The reason is that if the number of hashes in the list at a given time
10  is odd, the last one is duplicated before computing the next level (which
11  is unusual in Merkle trees). This results in certain sequences of
12  transactions leading to the same merkle root. For example, these two
13  trees:
14  A A
15  / \ / \
16  B C B C
17  / \ | / \ / \
18  D E F D E F F
19  / \ / \ / \ / \ / \ / \ / \
20  1 2 3 4 5 6 1 2 3 4 5 6 5 6
21  for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
22  6 are repeated) result in the same root hash A (because the hash of both
23  of (F) and (F,F) is C).
24  The vulnerability results from being able to send a block with such a
25  transaction list, with the same merkle root, and the same block hash as
26  the original without duplication, resulting in failed validation. If the
27  receiving node proceeds to mark that block as permanently invalid
28  however, it will fail to accept further unmodified (and thus potentially
29  valid) versions of the same block. We defend against this by detecting
30  the case where we would hash two identical hashes at the end of the list
31  together, and treating that identically to the block having an invalid
32  merkle root. Assuming no double-SHA256 collisions, this will detect all
33  known ways of changing the transactions without affecting the merkle
34  root.
35 */
36 
37 /* This implements a constant-space merkle root/path calculator, limited to 2^32 leaves. */
38 static void MerkleComputation(const std::vector<uint256>& leaves, uint256* proot, bool* pmutated, uint32_t branchpos, std::vector<uint256>* pbranch) {
39  if (pbranch) pbranch->clear();
40  if (leaves.size() == 0) {
41  if (pmutated) *pmutated = false;
42  if (proot) *proot = uint256();
43  return;
44  }
45  bool mutated = false;
46  // count is the number of leaves processed so far.
47  uint32_t count = 0;
48  // inner is an array of eagerly computed subtree hashes, indexed by tree
49  // level (0 being the leaves).
50  // For example, when count is 25 (11001 in binary), inner[4] is the hash of
51  // the first 16 leaves, inner[3] of the next 8 leaves, and inner[0] equal to
52  // the last leaf. The other inner entries are undefined.
53  uint256 inner[32];
54  // Which position in inner is a hash that depends on the matching leaf.
55  int matchlevel = -1;
56  // First process all leaves into 'inner' values.
57  while (count < leaves.size()) {
58  uint256 h = leaves[count];
59  bool matchh = count == branchpos;
60  count++;
61  int level;
62  // For each of the lower bits in count that are 0, do 1 step. Each
63  // corresponds to an inner value that existed before processing the
64  // current leaf, and each needs a hash to combine it.
65  for (level = 0; !(count & (((uint32_t)1) << level)); level++) {
66  if (pbranch) {
67  if (matchh) {
68  pbranch->push_back(inner[level]);
69  } else if (matchlevel == level) {
70  pbranch->push_back(h);
71  matchh = true;
72  }
73  }
74  mutated |= (inner[level] == h);
75  CHash256().Write(inner[level].begin(), 32).Write(h.begin(), 32).Finalize(h.begin());
76  }
77  // Store the resulting hash at inner position level.
78  inner[level] = h;
79  if (matchh) {
80  matchlevel = level;
81  }
82  }
83  // Do a final 'sweep' over the rightmost branch of the tree to process
84  // odd levels, and reduce everything to a single top value.
85  // Level is the level (counted from the bottom) up to which we've sweeped.
86  int level = 0;
87  // As long as bit number level in count is zero, skip it. It means there
88  // is nothing left at this level.
89  while (!(count & (((uint32_t)1) << level))) {
90  level++;
91  }
92  uint256 h = inner[level];
93  bool matchh = matchlevel == level;
94  while (count != (((uint32_t)1) << level)) {
95  // If we reach this point, h is an inner value that is not the top.
96  // We combine it with itself (Bitcoin's special rule for odd levels in
97  // the tree) to produce a higher level one.
98  if (pbranch && matchh) {
99  pbranch->push_back(h);
100  }
101  CHash256().Write(h.begin(), 32).Write(h.begin(), 32).Finalize(h.begin());
102  // Increment count to the value it would have if two entries at this
103  // level had existed.
104  count += (((uint32_t)1) << level);
105  level++;
106  // And propagate the result upwards accordingly.
107  while (!(count & (((uint32_t)1) << level))) {
108  if (pbranch) {
109  if (matchh) {
110  pbranch->push_back(inner[level]);
111  } else if (matchlevel == level) {
112  pbranch->push_back(h);
113  matchh = true;
114  }
115  }
116  CHash256().Write(inner[level].begin(), 32).Write(h.begin(), 32).Finalize(h.begin());
117  level++;
118  }
119  }
120  // Return result.
121  if (pmutated) *pmutated = mutated;
122  if (proot) *proot = h;
123 }
124 
125 uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated) {
126  uint256 hash;
127  MerkleComputation(leaves, &hash, mutated, -1, NULL);
128  return hash;
129 }
130 
131 std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position) {
132  std::vector<uint256> ret;
133  MerkleComputation(leaves, NULL, NULL, position, &ret);
134  return ret;
135 }
136 
137 uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint256>& vMerkleBranch, uint32_t nIndex) {
138  uint256 hash = leaf;
139  for (std::vector<uint256>::const_iterator it = vMerkleBranch.begin(); it != vMerkleBranch.end(); ++it) {
140  if (nIndex & 1) {
141  hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
142  } else {
143  hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
144  }
145  nIndex >>= 1;
146  }
147  return hash;
148 }
149 
150 uint256 BlockMerkleRoot(const CBlock& block, bool* mutated)
151 {
152  std::vector<uint256> leaves;
153  leaves.resize(block.vtx.size());
154  for (size_t s = 0; s < block.vtx.size(); s++) {
155  leaves[s] = block.vtx[s].GetHash();
156  }
157  return ComputeMerkleRoot(leaves, mutated);
158 }
159 
160 std::vector<uint256> BlockMerkleBranch(const CBlock& block, uint32_t position)
161 {
162  std::vector<uint256> leaves;
163  leaves.resize(block.vtx.size());
164  for (size_t s = 0; s < block.vtx.size(); s++) {
165  leaves[s] = block.vtx[s].GetHash();
166  }
167  return ComputeMerkleBranch(leaves, position);
168 }
CHash256::Finalize
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hash.h:41
ComputeMerkleRoot
uint256 ComputeMerkleRoot(const std::vector< uint256 > &leaves, bool *mutated)
Definition: merkle.cpp:125
BEGIN
#define BEGIN(a)
Utilities for converting data from/to strings.
Definition: utilstrencodings.h:17
base_uint::begin
unsigned char * begin()
Definition: arith_uint256.h:240
ComputeMerkleRootFromBranch
uint256 ComputeMerkleRootFromBranch(const uint256 &leaf, const std::vector< uint256 > &vMerkleBranch, uint32_t nIndex)
Definition: merkle.cpp:137
BlockMerkleBranch
std::vector< uint256 > BlockMerkleBranch(const CBlock &block, uint32_t position)
Definition: merkle.cpp:160
uint256
256-bit unsigned big integer.
Definition: uint256.h:38
CHash256::Write
CHash256 & Write(const unsigned char *data, size_t len)
Definition: hash.h:48
merkle.h
CBlock::vtx
std::vector< CTransaction > vtx
Definition: block.h:146
CBlock
Definition: block.h:142
END
#define END(a)
Definition: utilstrencodings.h:18
ComputeMerkleBranch
std::vector< uint256 > ComputeMerkleBranch(const std::vector< uint256 > &leaves, uint32_t position)
Definition: merkle.cpp:131
CHash256
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:33
utilstrencodings.h
Hash
std::string Hash(std::string input)
Compute the 256-bit hash of a std::string.
Definition: hash.h:122
BlockMerkleRoot
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:150