github.com/jimmyx0x/go-ethereum@v1.10.28/trie/node.go (about)

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