Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

merkle.cpp 7.0KB

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