PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/src/merkleblock.h

http://github.com/bitcoin/bitcoin
C Header | 173 lines | 65 code | 29 blank | 79 comment | 5 complexity | 89b976c64a5c909cb7fcbb92c002f236 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, MIT
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2018 The Bitcoin 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. #ifndef BITCOIN_MERKLEBLOCK_H
  6. #define BITCOIN_MERKLEBLOCK_H
  7. #include <serialize.h>
  8. #include <uint256.h>
  9. #include <primitives/block.h>
  10. #include <bloom.h>
  11. #include <vector>
  12. /** Data structure that represents a partial merkle tree.
  13. *
  14. * It represents a subset of the txid's of a known block, in a way that
  15. * allows recovery of the list of txid's and the merkle root, in an
  16. * authenticated way.
  17. *
  18. * The encoding works as follows: we traverse the tree in depth-first order,
  19. * storing a bit for each traversed node, signifying whether the node is the
  20. * parent of at least one matched leaf txid (or a matched txid itself). In
  21. * case we are at the leaf level, or this bit is 0, its merkle node hash is
  22. * stored, and its children are not explored further. Otherwise, no hash is
  23. * stored, but we recurse into both (or the only) child branch. During
  24. * decoding, the same depth-first traversal is performed, consuming bits and
  25. * hashes as they written during encoding.
  26. *
  27. * The serialization is fixed and provides a hard guarantee about the
  28. * encoded size:
  29. *
  30. * SIZE <= 10 + ceil(32.25*N)
  31. *
  32. * Where N represents the number of leaf nodes of the partial tree. N itself
  33. * is bounded by:
  34. *
  35. * N <= total_transactions
  36. * N <= 1 + matched_transactions*tree_height
  37. *
  38. * The serialization format:
  39. * - uint32 total_transactions (4 bytes)
  40. * - varint number of hashes (1-3 bytes)
  41. * - uint256[] hashes in depth-first order (<= 32*N bytes)
  42. * - varint number of bytes of flag bits (1-3 bytes)
  43. * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
  44. * The size constraints follow from this.
  45. */
  46. class CPartialMerkleTree
  47. {
  48. protected:
  49. /** the total number of transactions in the block */
  50. unsigned int nTransactions;
  51. /** node-is-parent-of-matched-txid bits */
  52. std::vector<bool> vBits;
  53. /** txids and internal hashes */
  54. std::vector<uint256> vHash;
  55. /** flag set when encountering invalid data */
  56. bool fBad;
  57. /** helper function to efficiently calculate the number of nodes at given height in the merkle tree */
  58. unsigned int CalcTreeWidth(int height) const {
  59. return (nTransactions+(1 << height)-1) >> height;
  60. }
  61. /** calculate the hash of a node in the merkle tree (at leaf level: the txid's themselves) */
  62. uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
  63. /** recursive function that traverses tree nodes, storing the data as bits and hashes */
  64. void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
  65. /**
  66. * recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
  67. * it returns the hash of the respective node and its respective index.
  68. */
  69. uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex);
  70. public:
  71. /** serialization implementation */
  72. ADD_SERIALIZE_METHODS;
  73. template <typename Stream, typename Operation>
  74. inline void SerializationOp(Stream& s, Operation ser_action) {
  75. READWRITE(nTransactions);
  76. READWRITE(vHash);
  77. std::vector<unsigned char> vBytes;
  78. if (ser_action.ForRead()) {
  79. READWRITE(vBytes);
  80. CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
  81. us.vBits.resize(vBytes.size() * 8);
  82. for (unsigned int p = 0; p < us.vBits.size(); p++)
  83. us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
  84. us.fBad = false;
  85. } else {
  86. vBytes.resize((vBits.size()+7)/8);
  87. for (unsigned int p = 0; p < vBits.size(); p++)
  88. vBytes[p / 8] |= vBits[p] << (p % 8);
  89. READWRITE(vBytes);
  90. }
  91. }
  92. /** Construct a partial merkle tree from a list of transaction ids, and a mask that selects a subset of them */
  93. CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
  94. CPartialMerkleTree();
  95. /**
  96. * extract the matching txid's represented by this partial merkle tree
  97. * and their respective indices within the partial tree.
  98. * returns the merkle root, or 0 in case of failure
  99. */
  100. uint256 ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex);
  101. /** Get number of transactions the merkle proof is indicating for cross-reference with
  102. * local blockchain knowledge.
  103. */
  104. unsigned int GetNumTransactions() const { return nTransactions; };
  105. };
  106. /**
  107. * Used to relay blocks as header + vector<merkle branch>
  108. * to filtered nodes.
  109. *
  110. * NOTE: The class assumes that the given CBlock has *at least* 1 transaction. If the CBlock has 0 txs, it will hit an assertion.
  111. */
  112. class CMerkleBlock
  113. {
  114. public:
  115. /** Public only for unit testing */
  116. CBlockHeader header;
  117. CPartialMerkleTree txn;
  118. /**
  119. * Public only for unit testing and relay testing (not relayed).
  120. *
  121. * Used only when a bloom filter is specified to allow
  122. * testing the transactions which matched the bloom filter.
  123. */
  124. std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
  125. /**
  126. * Create from a CBlock, filtering transactions according to filter
  127. * Note that this will call IsRelevantAndUpdate on the filter for each transaction,
  128. * thus the filter will likely be modified.
  129. */
  130. CMerkleBlock(const CBlock& block, CBloomFilter& filter) : CMerkleBlock(block, &filter, nullptr) { }
  131. // Create from a CBlock, matching the txids in the set
  132. CMerkleBlock(const CBlock& block, const std::set<uint256>& txids) : CMerkleBlock(block, nullptr, &txids) { }
  133. CMerkleBlock() {}
  134. ADD_SERIALIZE_METHODS;
  135. template <typename Stream, typename Operation>
  136. inline void SerializationOp(Stream& s, Operation ser_action) {
  137. READWRITE(header);
  138. READWRITE(txn);
  139. }
  140. private:
  141. // Combined constructor to consolidate code
  142. CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<uint256>* txids);
  143. };
  144. #endif // BITCOIN_MERKLEBLOCK_H