github.com/MetalBlockchain/subnet-evm@v0.4.9/trie/node.go (about)

     1  // (c) 2020-2021, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2014 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package trie
    28  
    29  import (
    30  	"fmt"
    31  	"io"
    32  	"strings"
    33  
    34  	"github.com/ethereum/go-ethereum/common"
    35  	"github.com/ethereum/go-ethereum/rlp"
    36  )
    37  
    38  var indices = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "[17]"}
    39  
    40  type node interface {
    41  	cache() (hashNode, bool)
    42  	encode(w rlp.EncoderBuffer)
    43  	fstring(string) string
    44  }
    45  
    46  type (
    47  	fullNode struct {
    48  		Children [17]node // Actual trie node data to encode/decode (needs custom encoder)
    49  		flags    nodeFlag
    50  	}
    51  	shortNode struct {
    52  		Key   []byte
    53  		Val   node
    54  		flags nodeFlag
    55  	}
    56  	hashNode  []byte
    57  	valueNode []byte
    58  )
    59  
    60  // nilValueNode is used when collapsing internal trie nodes for hashing, since
    61  // unset children need to serialize correctly.
    62  var nilValueNode = valueNode(nil)
    63  
    64  // EncodeRLP encodes a full node into the consensus RLP format.
    65  func (n *fullNode) EncodeRLP(w io.Writer) error {
    66  	eb := rlp.NewEncoderBuffer(w)
    67  	n.encode(eb)
    68  	return eb.Flush()
    69  }
    70  
    71  func (n *fullNode) copy() *fullNode   { copy := *n; return &copy }
    72  func (n *shortNode) copy() *shortNode { copy := *n; return &copy }
    73  
    74  // nodeFlag contains caching-related metadata about a node.
    75  type nodeFlag struct {
    76  	hash  hashNode // cached hash of the node (may be nil)
    77  	dirty bool     // whether the node has changes that must be written to the database
    78  }
    79  
    80  func (n *fullNode) cache() (hashNode, bool)  { return n.flags.hash, n.flags.dirty }
    81  func (n *shortNode) cache() (hashNode, bool) { return n.flags.hash, n.flags.dirty }
    82  func (n hashNode) cache() (hashNode, bool)   { return nil, true }
    83  func (n valueNode) cache() (hashNode, bool)  { return nil, true }
    84  
    85  // Pretty printing.
    86  func (n *fullNode) String() string  { return n.fstring("") }
    87  func (n *shortNode) String() string { return n.fstring("") }
    88  func (n hashNode) String() string   { return n.fstring("") }
    89  func (n valueNode) String() string  { return n.fstring("") }
    90  
    91  func (n *fullNode) fstring(ind string) string {
    92  	resp := fmt.Sprintf("[\n%s  ", ind)
    93  	for i, node := range &n.Children {
    94  		if node == nil {
    95  			resp += fmt.Sprintf("%s: <nil> ", indices[i])
    96  		} else {
    97  			resp += fmt.Sprintf("%s: %v", indices[i], node.fstring(ind+"  "))
    98  		}
    99  	}
   100  	return resp + fmt.Sprintf("\n%s] ", ind)
   101  }
   102  func (n *shortNode) fstring(ind string) string {
   103  	return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+"  "))
   104  }
   105  func (n hashNode) fstring(ind string) string {
   106  	return fmt.Sprintf("<%x> ", []byte(n))
   107  }
   108  func (n valueNode) fstring(ind string) string {
   109  	return fmt.Sprintf("%x ", []byte(n))
   110  }
   111  
   112  // mustDecodeNode is a wrapper of decodeNode and panic if any error is encountered.
   113  func mustDecodeNode(hash, buf []byte) node {
   114  	n, err := decodeNode(hash, buf)
   115  	if err != nil {
   116  		panic(fmt.Sprintf("node %x: %v", hash, err))
   117  	}
   118  	return n
   119  }
   120  
   121  // mustDecodeNodeUnsafe is a wrapper of decodeNodeUnsafe and panic if any error is
   122  // encountered.
   123  func mustDecodeNodeUnsafe(hash, buf []byte) node {
   124  	n, err := decodeNodeUnsafe(hash, buf)
   125  	if err != nil {
   126  		panic(fmt.Sprintf("node %x: %v", hash, err))
   127  	}
   128  	return n
   129  }
   130  
   131  // decodeNode parses the RLP encoding of a trie node. It will deep-copy the passed
   132  // byte slice for decoding, so it's safe to modify the byte slice afterwards. The-
   133  // decode performance of this function is not optimal, but it is suitable for most
   134  // scenarios with low performance requirements and hard to determine whether the
   135  // byte slice be modified or not.
   136  func decodeNode(hash, buf []byte) (node, error) {
   137  	return decodeNodeUnsafe(hash, common.CopyBytes(buf))
   138  }
   139  
   140  // decodeNodeUnsafe parses the RLP encoding of a trie node. The passed byte slice
   141  // will be directly referenced by node without bytes deep copy, so the input MUST
   142  // not be changed after.
   143  func decodeNodeUnsafe(hash, buf []byte) (node, error) {
   144  	if len(buf) == 0 {
   145  		return nil, io.ErrUnexpectedEOF
   146  	}
   147  	elems, _, err := rlp.SplitList(buf)
   148  	if err != nil {
   149  		return nil, fmt.Errorf("decode error: %v", err)
   150  	}
   151  	switch c, _ := rlp.CountValues(elems); c {
   152  	case 2:
   153  		n, err := decodeShort(hash, elems)
   154  		return n, wrapError(err, "short")
   155  	case 17:
   156  		n, err := decodeFull(hash, elems)
   157  		return n, wrapError(err, "full")
   158  	default:
   159  		return nil, fmt.Errorf("invalid number of list elements: %v", c)
   160  	}
   161  }
   162  
   163  func decodeShort(hash, elems []byte) (node, error) {
   164  	kbuf, rest, err := rlp.SplitString(elems)
   165  	if err != nil {
   166  		return nil, err
   167  	}
   168  	flag := nodeFlag{hash: hash}
   169  	key := compactToHex(kbuf)
   170  	if hasTerm(key) {
   171  		// value node
   172  		val, _, err := rlp.SplitString(rest)
   173  		if err != nil {
   174  			return nil, fmt.Errorf("invalid value node: %v", err)
   175  		}
   176  		return &shortNode{key, valueNode(val), flag}, nil
   177  	}
   178  	r, _, err := decodeRef(rest)
   179  	if err != nil {
   180  		return nil, wrapError(err, "val")
   181  	}
   182  	return &shortNode{key, r, flag}, nil
   183  }
   184  
   185  func decodeFull(hash, elems []byte) (*fullNode, error) {
   186  	n := &fullNode{flags: nodeFlag{hash: hash}}
   187  	for i := 0; i < 16; i++ {
   188  		cld, rest, err := decodeRef(elems)
   189  		if err != nil {
   190  			return n, wrapError(err, fmt.Sprintf("[%d]", i))
   191  		}
   192  		n.Children[i], elems = cld, rest
   193  	}
   194  	val, _, err := rlp.SplitString(elems)
   195  	if err != nil {
   196  		return n, err
   197  	}
   198  	if len(val) > 0 {
   199  		n.Children[16] = valueNode(val)
   200  	}
   201  	return n, nil
   202  }
   203  
   204  const hashLen = len(common.Hash{})
   205  
   206  func decodeRef(buf []byte) (node, []byte, error) {
   207  	kind, val, rest, err := rlp.Split(buf)
   208  	if err != nil {
   209  		return nil, buf, err
   210  	}
   211  	switch {
   212  	case kind == rlp.List:
   213  		// 'embedded' node reference. The encoding must be smaller
   214  		// than a hash in order to be valid.
   215  		if size := len(buf) - len(rest); size > hashLen {
   216  			err := fmt.Errorf("oversized embedded node (size is %d bytes, want size < %d)", size, hashLen)
   217  			return nil, buf, err
   218  		}
   219  		n, err := decodeNode(nil, buf)
   220  		return n, rest, err
   221  	case kind == rlp.String && len(val) == 0:
   222  		// empty node
   223  		return nil, rest, nil
   224  	case kind == rlp.String && len(val) == 32:
   225  		return hashNode(val), rest, nil
   226  	default:
   227  		return nil, nil, fmt.Errorf("invalid RLP string size %d (want 0 or 32)", len(val))
   228  	}
   229  }
   230  
   231  // wraps a decoding error with information about the path to the
   232  // invalid child node (for debugging encoding issues).
   233  type decodeError struct {
   234  	what  error
   235  	stack []string
   236  }
   237  
   238  func wrapError(err error, ctx string) error {
   239  	if err == nil {
   240  		return nil
   241  	}
   242  	if decErr, ok := err.(*decodeError); ok {
   243  		decErr.stack = append(decErr.stack, ctx)
   244  		return decErr
   245  	}
   246  	return &decodeError{err, []string{ctx}}
   247  }
   248  
   249  func (err *decodeError) Error() string {
   250  	return fmt.Sprintf("%v (decode path: %s)", err.what, strings.Join(err.stack, "<-"))
   251  }