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