github.com/koko1123/flow-go-1@v0.29.6/ledger/partial/ptrie/node.go (about)

     1  package ptrie
     2  
     3  import (
     4  	"encoding/hex"
     5  
     6  	"github.com/koko1123/flow-go-1/ledger"
     7  	"github.com/koko1123/flow-go-1/ledger/common/hash"
     8  )
     9  
    10  // Root hash of a node
    11  type Root hash.Hash
    12  
    13  func (r Root) String() string {
    14  	return hex.EncodeToString(r[:])
    15  }
    16  
    17  // node is a struct for constructing our Tree.
    18  // Height Definition: the height of a node v in a tree is the number
    19  // of edges on the longest downward path between v and a tree leaf.
    20  type node struct {
    21  	lChild    *node           // Left Child
    22  	rChild    *node           // Right Child
    23  	height    int             // Height where the node is at
    24  	payload   *ledger.Payload // payload
    25  	hashValue hash.Hash       // hash value
    26  }
    27  
    28  // newNode creates a new node with the provided height and hash
    29  func newNode(v hash.Hash, height int) *node {
    30  	n := new(node)
    31  	n.hashValue = v
    32  	n.height = height
    33  	n.lChild = nil
    34  	n.rChild = nil
    35  	return n
    36  }
    37  
    38  // Hash returns the node's pre-computed hash value
    39  func (n *node) Hash() hash.Hash { return n.hashValue }
    40  
    41  // forceComputeHash computes (and updates) the hashes of _all interim nodes_
    42  // of this sub-trie. Caution: this is an expensive operation!
    43  func (n *node) forceComputeHash() hash.Hash {
    44  	// leaf node
    45  	if n.lChild == nil && n.rChild == nil {
    46  		return n.hashValue
    47  	}
    48  	// otherwise compute
    49  	var h1, h2 hash.Hash
    50  	if n.lChild != nil {
    51  		h1 = n.lChild.forceComputeHash()
    52  	} else {
    53  		h1 = ledger.GetDefaultHashForHeight(n.height - 1)
    54  	}
    55  
    56  	if n.rChild != nil {
    57  		h2 = n.rChild.forceComputeHash()
    58  	} else {
    59  		h2 = ledger.GetDefaultHashForHeight(n.height - 1)
    60  	}
    61  	n.hashValue = hash.HashInterNode(h1, h2)
    62  	return n.hashValue
    63  }