github.com/ethereum/go-ethereum@v1.16.1/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  	// fullnodeEncoder is a type used exclusively for encoding fullNode.
    50  	// Briefly instantiating a fullnodeEncoder and initializing with
    51  	// existing slices is less memory intense than using the fullNode type.
    52  	fullnodeEncoder struct {
    53  		Children [17][]byte
    54  	}
    55  
    56  	// extNodeEncoder is a type used exclusively for encoding extension node.
    57  	// Briefly instantiating a extNodeEncoder and initializing with existing
    58  	// slices is less memory intense than using the shortNode type.
    59  	extNodeEncoder struct {
    60  		Key []byte
    61  		Val []byte
    62  	}
    63  
    64  	// leafNodeEncoder is a type used exclusively for encoding leaf node.
    65  	leafNodeEncoder struct {
    66  		Key []byte
    67  		Val []byte
    68  	}
    69  )
    70  
    71  // nilValueNode is used when collapsing internal trie nodes for hashing, since
    72  // unset children need to serialize correctly.
    73  var nilValueNode = valueNode(nil)
    74  
    75  // EncodeRLP encodes a full node into the consensus RLP format.
    76  func (n *fullNode) EncodeRLP(w io.Writer) error {
    77  	eb := rlp.NewEncoderBuffer(w)
    78  	n.encode(eb)
    79  	return eb.Flush()
    80  }
    81  
    82  // nodeFlag contains caching-related metadata about a node.
    83  type nodeFlag struct {
    84  	hash  hashNode // cached hash of the node (may be nil)
    85  	dirty bool     // whether the node has changes that must be written to the database
    86  }
    87  
    88  func (n nodeFlag) copy() nodeFlag {
    89  	return nodeFlag{
    90  		hash:  common.CopyBytes(n.hash),
    91  		dirty: n.dirty,
    92  	}
    93  }
    94  
    95  func (n *fullNode) cache() (hashNode, bool)  { return n.flags.hash, n.flags.dirty }
    96  func (n *shortNode) cache() (hashNode, bool) { return n.flags.hash, n.flags.dirty }
    97  func (n hashNode) cache() (hashNode, bool)   { return nil, true }
    98  func (n valueNode) cache() (hashNode, bool)  { return nil, true }
    99  
   100  // Pretty printing.
   101  func (n *fullNode) String() string  { return n.fstring("") }
   102  func (n *shortNode) String() string { return n.fstring("") }
   103  func (n hashNode) String() string   { return n.fstring("") }
   104  func (n valueNode) String() string  { return n.fstring("") }
   105  
   106  func (n *fullNode) fstring(ind string) string {
   107  	resp := fmt.Sprintf("[\n%s  ", ind)
   108  	for i, node := range &n.Children {
   109  		if node == nil {
   110  			resp += fmt.Sprintf("%s: <nil> ", indices[i])
   111  		} else {
   112  			resp += fmt.Sprintf("%s: %v", indices[i], node.fstring(ind+"  "))
   113  		}
   114  	}
   115  	return resp + fmt.Sprintf("\n%s] ", ind)
   116  }
   117  
   118  func (n *shortNode) fstring(ind string) string {
   119  	return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+"  "))
   120  }
   121  func (n hashNode) fstring(ind string) string {
   122  	return fmt.Sprintf("<%x> ", []byte(n))
   123  }
   124  func (n valueNode) fstring(ind string) string {
   125  	return fmt.Sprintf("%x ", []byte(n))
   126  }
   127  
   128  // mustDecodeNode is a wrapper of decodeNode and panic if any error is encountered.
   129  func mustDecodeNode(hash, buf []byte) node {
   130  	n, err := decodeNode(hash, buf)
   131  	if err != nil {
   132  		panic(fmt.Sprintf("node %x: %v", hash, err))
   133  	}
   134  	return n
   135  }
   136  
   137  // mustDecodeNodeUnsafe is a wrapper of decodeNodeUnsafe and panic if any error is
   138  // encountered.
   139  func mustDecodeNodeUnsafe(hash, buf []byte) node {
   140  	n, err := decodeNodeUnsafe(hash, buf)
   141  	if err != nil {
   142  		panic(fmt.Sprintf("node %x: %v", hash, err))
   143  	}
   144  	return n
   145  }
   146  
   147  // decodeNode parses the RLP encoding of a trie node. It will deep-copy the passed
   148  // byte slice for decoding, so it's safe to modify the byte slice afterwards. The-
   149  // decode performance of this function is not optimal, but it is suitable for most
   150  // scenarios with low performance requirements and hard to determine whether the
   151  // byte slice be modified or not.
   152  func decodeNode(hash, buf []byte) (node, error) {
   153  	return decodeNodeUnsafe(hash, common.CopyBytes(buf))
   154  }
   155  
   156  // decodeNodeUnsafe parses the RLP encoding of a trie node. The passed byte slice
   157  // will be directly referenced by node without bytes deep copy, so the input MUST
   158  // not be changed after.
   159  func decodeNodeUnsafe(hash, buf []byte) (node, error) {
   160  	if len(buf) == 0 {
   161  		return nil, io.ErrUnexpectedEOF
   162  	}
   163  	elems, _, err := rlp.SplitList(buf)
   164  	if err != nil {
   165  		return nil, fmt.Errorf("decode error: %v", err)
   166  	}
   167  	switch c, _ := rlp.CountValues(elems); c {
   168  	case 2:
   169  		n, err := decodeShort(hash, elems)
   170  		return n, wrapError(err, "short")
   171  	case 17:
   172  		n, err := decodeFull(hash, elems)
   173  		return n, wrapError(err, "full")
   174  	default:
   175  		return nil, fmt.Errorf("invalid number of list elements: %v", c)
   176  	}
   177  }
   178  
   179  func decodeShort(hash, elems []byte) (node, error) {
   180  	kbuf, rest, err := rlp.SplitString(elems)
   181  	if err != nil {
   182  		return nil, err
   183  	}
   184  	flag := nodeFlag{hash: hash}
   185  	key := compactToHex(kbuf)
   186  	if hasTerm(key) {
   187  		// value node
   188  		val, _, err := rlp.SplitString(rest)
   189  		if err != nil {
   190  			return nil, fmt.Errorf("invalid value node: %v", err)
   191  		}
   192  		return &shortNode{key, valueNode(val), flag}, nil
   193  	}
   194  	r, _, err := decodeRef(rest)
   195  	if err != nil {
   196  		return nil, wrapError(err, "val")
   197  	}
   198  	return &shortNode{key, r, flag}, nil
   199  }
   200  
   201  func decodeFull(hash, elems []byte) (*fullNode, error) {
   202  	n := &fullNode{flags: nodeFlag{hash: hash}}
   203  	for i := 0; i < 16; i++ {
   204  		cld, rest, err := decodeRef(elems)
   205  		if err != nil {
   206  			return n, wrapError(err, fmt.Sprintf("[%d]", i))
   207  		}
   208  		n.Children[i], elems = cld, rest
   209  	}
   210  	val, _, err := rlp.SplitString(elems)
   211  	if err != nil {
   212  		return n, err
   213  	}
   214  	if len(val) > 0 {
   215  		n.Children[16] = valueNode(val)
   216  	}
   217  	return n, nil
   218  }
   219  
   220  const hashLen = len(common.Hash{})
   221  
   222  func decodeRef(buf []byte) (node, []byte, error) {
   223  	kind, val, rest, err := rlp.Split(buf)
   224  	if err != nil {
   225  		return nil, buf, err
   226  	}
   227  	switch {
   228  	case kind == rlp.List:
   229  		// 'embedded' node reference. The encoding must be smaller
   230  		// than a hash in order to be valid.
   231  		if size := len(buf) - len(rest); size > hashLen {
   232  			err := fmt.Errorf("oversized embedded node (size is %d bytes, want size < %d)", size, hashLen)
   233  			return nil, buf, err
   234  		}
   235  		// The buffer content has already been copied or is safe to use;
   236  		// no additional copy is required.
   237  		n, err := decodeNodeUnsafe(nil, buf)
   238  		return n, rest, err
   239  	case kind == rlp.String && len(val) == 0:
   240  		// empty node
   241  		return nil, rest, nil
   242  	case kind == rlp.String && len(val) == 32:
   243  		return hashNode(val), rest, nil
   244  	default:
   245  		return nil, nil, fmt.Errorf("invalid RLP string size %d (want 0 or 32)", len(val))
   246  	}
   247  }
   248  
   249  // wraps a decoding error with information about the path to the
   250  // invalid child node (for debugging encoding issues).
   251  type decodeError struct {
   252  	what  error
   253  	stack []string
   254  }
   255  
   256  func wrapError(err error, ctx string) error {
   257  	if err == nil {
   258  		return nil
   259  	}
   260  	if decErr, ok := err.(*decodeError); ok {
   261  		decErr.stack = append(decErr.stack, ctx)
   262  		return decErr
   263  	}
   264  	return &decodeError{err, []string{ctx}}
   265  }
   266  
   267  func (err *decodeError) Error() string {
   268  	return fmt.Sprintf("%v (decode path: %s)", err.what, strings.Join(err.stack, "<-"))
   269  }