2020-05-22 07:37:07 +00:00
|
|
|
package mpt
|
|
|
|
|
|
|
|
import (
|
2020-05-28 05:55:12 +00:00
|
|
|
"encoding/hex"
|
|
|
|
"errors"
|
2020-05-22 07:37:07 +00:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/nspcc-dev/neo-go/pkg/io"
|
|
|
|
"github.com/nspcc-dev/neo-go/pkg/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
// MaxValueLength is a max length of a leaf node value.
|
|
|
|
const MaxValueLength = 1024 * 1024
|
|
|
|
|
|
|
|
// LeafNode represents MPT's leaf node.
|
|
|
|
type LeafNode struct {
|
2020-06-02 20:49:46 +00:00
|
|
|
BaseNode
|
2020-05-22 07:37:07 +00:00
|
|
|
value []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ Node = (*LeafNode)(nil)
|
|
|
|
|
|
|
|
// NewLeafNode returns hash node with the specified value.
|
|
|
|
func NewLeafNode(value []byte) *LeafNode {
|
|
|
|
return &LeafNode{value: value}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Type implements Node interface.
|
|
|
|
func (n LeafNode) Type() NodeType { return LeafT }
|
|
|
|
|
2020-06-02 20:49:46 +00:00
|
|
|
// Hash implements BaseNode interface.
|
2020-05-22 07:37:07 +00:00
|
|
|
func (n *LeafNode) Hash() util.Uint256 {
|
2020-06-02 20:49:46 +00:00
|
|
|
return n.getHash(n)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bytes implements BaseNode interface.
|
|
|
|
func (n *LeafNode) Bytes() []byte {
|
|
|
|
return n.getBytes(n)
|
2020-05-22 07:37:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DecodeBinary implements io.Serializable.
|
|
|
|
func (n *LeafNode) DecodeBinary(r *io.BinReader) {
|
|
|
|
sz := r.ReadVarUint()
|
|
|
|
if sz > MaxValueLength {
|
|
|
|
r.Err = fmt.Errorf("leaf node value is too big: %d", sz)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n.value = make([]byte, sz)
|
|
|
|
r.ReadBytes(n.value)
|
2020-06-02 20:49:46 +00:00
|
|
|
n.invalidateCache()
|
2020-05-22 07:37:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// EncodeBinary implements io.Serializable.
|
|
|
|
func (n LeafNode) EncodeBinary(w *io.BinWriter) {
|
|
|
|
w.WriteVarBytes(n.value)
|
|
|
|
}
|
2020-05-28 05:55:12 +00:00
|
|
|
|
|
|
|
// MarshalJSON implements json.Marshaler.
|
|
|
|
func (n *LeafNode) MarshalJSON() ([]byte, error) {
|
|
|
|
return []byte(`{"value":"` + hex.EncodeToString(n.value) + `"}`), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalJSON implements json.Unmarshaler.
|
|
|
|
func (n *LeafNode) UnmarshalJSON(data []byte) error {
|
|
|
|
var obj NodeObject
|
|
|
|
if err := obj.UnmarshalJSON(data); err != nil {
|
|
|
|
return err
|
|
|
|
} else if u, ok := obj.Node.(*LeafNode); ok {
|
|
|
|
*n = *u
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return errors.New("expected leaf node")
|
|
|
|
}
|