github.com/decred/dcrd/blockchain@v1.2.1/merkle.go (about)

     1  // Copyright (c) 2013-2016 The btcsuite developers
     2  // Copyright (c) 2015-2019 The Decred developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package blockchain
     7  
     8  import (
     9  	"math"
    10  
    11  	"github.com/decred/dcrd/chaincfg/chainhash"
    12  	"github.com/decred/dcrd/dcrutil"
    13  	"github.com/decred/dcrd/wire"
    14  )
    15  
    16  // nextPowerOfTwo returns the next highest power of two from a given number if
    17  // it is not already a power of two.  This is a helper function used during the
    18  // calculation of a merkle tree.
    19  func nextPowerOfTwo(n int) int {
    20  	// Return the number if it's already a power of 2.
    21  	if n&(n-1) == 0 {
    22  		return n
    23  	}
    24  
    25  	// Figure out and return the next power of two.
    26  	exponent := uint(math.Log2(float64(n))) + 1
    27  	return 1 << exponent // 2^exponent
    28  }
    29  
    30  // HashMerkleBranches takes two hashes, treated as the left and right tree
    31  // nodes, and returns the hash of their concatenation.  This is a helper
    32  // function used to aid in the generation of a merkle tree.
    33  //
    34  // Deprecated: Use standalone.CalcMerkleRoot instead.
    35  func HashMerkleBranches(left *chainhash.Hash, right *chainhash.Hash) *chainhash.Hash {
    36  	// Concatenate the left and right nodes.
    37  	var hash [chainhash.HashSize * 2]byte
    38  	copy(hash[:chainhash.HashSize], left[:])
    39  	copy(hash[chainhash.HashSize:], right[:])
    40  
    41  	newHash := chainhash.HashH(hash[:])
    42  	return &newHash
    43  }
    44  
    45  // populateMerkleStore constructs the merkle tree from all transaction hashes
    46  // before offset, saving the merkle hashes to the remaining entries in merkles
    47  // beginning at offset.
    48  func populateMerkleStore(offset int, merkles []*chainhash.Hash) {
    49  	// Start the array offset after the last transaction and adjusted to the
    50  	// next power of two.
    51  	for i := 0; i < len(merkles)-1; i += 2 {
    52  		switch {
    53  		// When there is no left child node, the parent is nil too.
    54  		case merkles[i] == nil:
    55  			merkles[offset] = nil
    56  
    57  		// When there is no right child, the parent is generated by
    58  		// hashing the concatenation of the left child with itself.
    59  		case merkles[i+1] == nil:
    60  			newHash := HashMerkleBranches(merkles[i], merkles[i])
    61  			merkles[offset] = newHash
    62  
    63  		// The normal case sets the parent node to the hash of the
    64  		// concatenation of the left and right children.
    65  		default:
    66  			newHash := HashMerkleBranches(merkles[i], merkles[i+1])
    67  			merkles[offset] = newHash
    68  		}
    69  		offset++
    70  	}
    71  }
    72  
    73  // BuildMerkleTreeStore creates a merkle tree from a slice of transactions,
    74  // stores it using a linear array, and returns a slice of the backing array.  A
    75  // linear array was chosen as opposed to an actual tree structure since it uses
    76  // about half as much memory.  The following describes a merkle tree and how it
    77  // is stored in a linear array.
    78  //
    79  // A merkle tree is a tree in which every non-leaf node is the hash of its
    80  // children nodes.  A diagram depicting how this works for Decred transactions
    81  // where h(x) is a blake256 hash follows:
    82  //
    83  //	         root = h1234 = h(h12 + h34)
    84  //	        /                           \
    85  //	  h12 = h(h1 + h2)            h34 = h(h3 + h4)
    86  //	   /            \              /            \
    87  //	h1 = h(tx1)  h2 = h(tx2)    h3 = h(tx3)  h4 = h(tx4)
    88  //
    89  // The above stored as a linear array is as follows:
    90  //
    91  // 	[h1 h2 h3 h4 h12 h34 root]
    92  //
    93  // As the above shows, the merkle root is always the last element in the array.
    94  //
    95  // The number of inputs is not always a power of two which results in a
    96  // balanced tree structure as above.  In that case, parent nodes with no
    97  // children are also zero and parent nodes with only a single left node
    98  // are calculated by concatenating the left node with itself before hashing.
    99  // Since this function uses nodes that are pointers to the hashes, empty nodes
   100  // will be nil.
   101  //
   102  // Deprecated: Use standalone.CalcTxTreeMerkleRoot instead.
   103  func BuildMerkleTreeStore(transactions []*dcrutil.Tx) []*chainhash.Hash {
   104  	// If there's an empty stake tree, return totally zeroed out merkle tree root
   105  	// only.
   106  	if len(transactions) == 0 {
   107  		return []*chainhash.Hash{new(chainhash.Hash)}
   108  	}
   109  
   110  	// Calculate how many entries are required to hold the binary merkle
   111  	// tree as a linear array and create an array of that size.
   112  	nextPoT := nextPowerOfTwo(len(transactions))
   113  	arraySize := nextPoT*2 - 1
   114  	merkles := make([]*chainhash.Hash, arraySize)
   115  
   116  	// Create the base transaction hashes and populate the array with them.
   117  	for i, tx := range transactions {
   118  		msgTx := tx.MsgTx()
   119  		txHashFull := msgTx.TxHashFull()
   120  		merkles[i] = &txHashFull
   121  	}
   122  
   123  	// Construct the merkle tree in the remaining entries of the merkles slice.
   124  	populateMerkleStore(nextPoT, merkles)
   125  
   126  	return merkles
   127  }
   128  
   129  // BuildMsgTxMerkleTreeStore is identical to BuildMerkleTreeStore but takes a
   130  // slice of the wire.MsgTx transaction type instead of the dcrutil.Tx wrapper.
   131  // See BuildMerkleTreeStore for more details.
   132  //
   133  // Deprecated: Use standalone.CalcTxTreeMerkleRoot instead.
   134  func BuildMsgTxMerkleTreeStore(transactions []*wire.MsgTx) []*chainhash.Hash {
   135  	// If there's an empty stake tree, return totally zeroed out merkle tree root
   136  	// only.
   137  	if len(transactions) == 0 {
   138  		return []*chainhash.Hash{new(chainhash.Hash)}
   139  	}
   140  
   141  	// Calculate how many entries are required to hold the binary merkle
   142  	// tree as a linear array and create an array of that size.
   143  	nextPoT := nextPowerOfTwo(len(transactions))
   144  	arraySize := nextPoT*2 - 1
   145  	merkles := make([]*chainhash.Hash, arraySize)
   146  
   147  	// Create the base transaction hashes and populate the array with them.
   148  	for i, tx := range transactions {
   149  		txHashFull := tx.TxHashFull()
   150  		merkles[i] = &txHashFull
   151  	}
   152  
   153  	// Construct the merkle tree in the remaining entries of the merkles slice.
   154  	populateMerkleStore(nextPoT, merkles)
   155  
   156  	return merkles
   157  }