github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/core/mpt/hash.go (about)

     1  package mpt
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/nspcc-dev/neo-go/pkg/io"
     7  	"github.com/nspcc-dev/neo-go/pkg/util"
     8  )
     9  
    10  // HashNode represents an MPT's hash node.
    11  type HashNode struct {
    12  	BaseNode
    13  	Collapsed bool
    14  }
    15  
    16  var _ Node = (*HashNode)(nil)
    17  
    18  // NewHashNode returns a hash node with the specified hash.
    19  func NewHashNode(h util.Uint256) *HashNode {
    20  	return &HashNode{
    21  		BaseNode: BaseNode{
    22  			hash:      h,
    23  			hashValid: true,
    24  		},
    25  	}
    26  }
    27  
    28  // Type implements Node interface.
    29  func (h *HashNode) Type() NodeType { return HashT }
    30  
    31  // Size implements Node interface.
    32  func (h *HashNode) Size() int {
    33  	return util.Uint256Size
    34  }
    35  
    36  // Hash implements Node interface.
    37  func (h *HashNode) Hash() util.Uint256 {
    38  	if !h.hashValid {
    39  		panic("can't get hash of an empty HashNode")
    40  	}
    41  	return h.hash
    42  }
    43  
    44  // Bytes returns serialized HashNode.
    45  func (h *HashNode) Bytes() []byte {
    46  	return h.getBytes(h)
    47  }
    48  
    49  // DecodeBinary implements io.Serializable.
    50  func (h *HashNode) DecodeBinary(r *io.BinReader) {
    51  	if h.hashValid {
    52  		h.hash.DecodeBinary(r)
    53  	}
    54  }
    55  
    56  // EncodeBinary implements io.Serializable.
    57  func (h HashNode) EncodeBinary(w *io.BinWriter) {
    58  	if !h.hashValid {
    59  		return
    60  	}
    61  	w.WriteBytes(h.hash[:])
    62  }
    63  
    64  // MarshalJSON implements the json.Marshaler.
    65  func (h *HashNode) MarshalJSON() ([]byte, error) {
    66  	return []byte(`{"hash":"` + h.hash.StringLE() + `"}`), nil
    67  }
    68  
    69  // UnmarshalJSON implements the json.Unmarshaler.
    70  func (h *HashNode) UnmarshalJSON(data []byte) error {
    71  	var obj NodeObject
    72  	if err := obj.UnmarshalJSON(data); err != nil {
    73  		return err
    74  	} else if u, ok := obj.Node.(*HashNode); ok {
    75  		*h = *u
    76  		return nil
    77  	}
    78  	return errors.New("expected hash node")
    79  }
    80  
    81  // Clone implements Node interface.
    82  func (h *HashNode) Clone() Node {
    83  	res := *h
    84  	res.Collapsed = false
    85  	return &res
    86  }