github.com/aitimate-0/go-ethereum@v1.9.7/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  	fstring(string) string
    32  	cache() (hashNode, bool)
    33  }
    34  
    35  type (
    36  	fullNode struct {
    37  		Children [17]node // Actual trie node data to encode/decode (needs custom encoder)
    38  		flags    nodeFlag
    39  	}
    40  	shortNode struct {
    41  		Key   []byte
    42  		Val   node
    43  		flags nodeFlag
    44  	}
    45  	hashNode  []byte
    46  	valueNode []byte
    47  )
    48  
    49  // nilValueNode is used when collapsing internal trie nodes for hashing, since
    50  // unset children need to serialize correctly.
    51  var nilValueNode = valueNode(nil)
    52  
    53  // EncodeRLP encodes a full node into the consensus RLP format.
    54  func (n *fullNode) EncodeRLP(w io.Writer) error {
    55  	var nodes [17]node
    56  
    57  	for i, child := range &n.Children {
    58  		if child != nil {
    59  			nodes[i] = child
    60  		} else {
    61  			nodes[i] = nilValueNode
    62  		}
    63  	}
    64  	return rlp.Encode(w, nodes)
    65  }
    66  
    67  func (n *fullNode) copy() *fullNode   { copy := *n; return &copy }
    68  func (n *shortNode) copy() *shortNode { copy := *n; return &copy }
    69  
    70  // nodeFlag contains caching-related metadata about a node.
    71  type nodeFlag struct {
    72  	hash  hashNode // cached hash of the node (may be nil)
    73  	dirty bool     // whether the node has changes that must be written to the database
    74  }
    75  
    76  func (n *fullNode) cache() (hashNode, bool)  { return n.flags.hash, n.flags.dirty }
    77  func (n *shortNode) cache() (hashNode, bool) { return n.flags.hash, n.flags.dirty }
    78  func (n hashNode) cache() (hashNode, bool)   { return nil, true }
    79  func (n valueNode) cache() (hashNode, bool)  { return nil, true }
    80  
    81  // Pretty printing.
    82  func (n *fullNode) String() string  { return n.fstring("") }
    83  func (n *shortNode) String() string { return n.fstring("") }
    84  func (n hashNode) String() string   { return n.fstring("") }
    85  func (n valueNode) String() string  { return n.fstring("") }
    86  
    87  func (n *fullNode) fstring(ind string) string {
    88  	resp := fmt.Sprintf("[\n%s  ", ind)
    89  	for i, node := range &n.Children {
    90  		if node == nil {
    91  			resp += fmt.Sprintf("%s: <nil> ", indices[i])
    92  		} else {
    93  			resp += fmt.Sprintf("%s: %v", indices[i], node.fstring(ind+"  "))
    94  		}
    95  	}
    96  	return resp + fmt.Sprintf("\n%s] ", ind)
    97  }
    98  func (n *shortNode) fstring(ind string) string {
    99  	return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+"  "))
   100  }
   101  func (n hashNode) fstring(ind string) string {
   102  	return fmt.Sprintf("<%x> ", []byte(n))
   103  }
   104  func (n valueNode) fstring(ind string) string {
   105  	return fmt.Sprintf("%x ", []byte(n))
   106  }
   107  
   108  func mustDecodeNode(hash, buf []byte) node {
   109  	n, err := decodeNode(hash, buf)
   110  	if err != nil {
   111  		panic(fmt.Sprintf("node %x: %v", hash, err))
   112  	}
   113  	return n
   114  }
   115  
   116  // decodeNode parses the RLP encoding of a trie node.
   117  func decodeNode(hash, buf []byte) (node, error) {
   118  	if len(buf) == 0 {
   119  		return nil, io.ErrUnexpectedEOF
   120  	}
   121  	elems, _, err := rlp.SplitList(buf)
   122  	if err != nil {
   123  		return nil, fmt.Errorf("decode error: %v", err)
   124  	}
   125  	switch c, _ := rlp.CountValues(elems); c {
   126  	case 2:
   127  		n, err := decodeShort(hash, elems)
   128  		return n, wrapError(err, "short")
   129  	case 17:
   130  		n, err := decodeFull(hash, elems)
   131  		return n, wrapError(err, "full")
   132  	default:
   133  		return nil, fmt.Errorf("invalid number of list elements: %v", c)
   134  	}
   135  }
   136  
   137  func decodeShort(hash, elems []byte) (node, error) {
   138  	kbuf, rest, err := rlp.SplitString(elems)
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  	flag := nodeFlag{hash: hash}
   143  	key := compactToHex(kbuf)
   144  	if hasTerm(key) {
   145  		// value node
   146  		val, _, err := rlp.SplitString(rest)
   147  		if err != nil {
   148  			return nil, fmt.Errorf("invalid value node: %v", err)
   149  		}
   150  		return &shortNode{key, append(valueNode{}, val...), flag}, nil
   151  	}
   152  	r, _, err := decodeRef(rest)
   153  	if err != nil {
   154  		return nil, wrapError(err, "val")
   155  	}
   156  	return &shortNode{key, r, flag}, nil
   157  }
   158  
   159  func decodeFull(hash, elems []byte) (*fullNode, error) {
   160  	n := &fullNode{flags: nodeFlag{hash: hash}}
   161  	for i := 0; i < 16; i++ {
   162  		cld, rest, err := decodeRef(elems)
   163  		if err != nil {
   164  			return n, wrapError(err, fmt.Sprintf("[%d]", i))
   165  		}
   166  		n.Children[i], elems = cld, rest
   167  	}
   168  	val, _, err := rlp.SplitString(elems)
   169  	if err != nil {
   170  		return n, err
   171  	}
   172  	if len(val) > 0 {
   173  		n.Children[16] = append(valueNode{}, val...)
   174  	}
   175  	return n, nil
   176  }
   177  
   178  const hashLen = len(common.Hash{})
   179  
   180  func decodeRef(buf []byte) (node, []byte, error) {
   181  	kind, val, rest, err := rlp.Split(buf)
   182  	if err != nil {
   183  		return nil, buf, err
   184  	}
   185  	switch {
   186  	case kind == rlp.List:
   187  		// 'embedded' node reference. The encoding must be smaller
   188  		// than a hash in order to be valid.
   189  		if size := len(buf) - len(rest); size > hashLen {
   190  			err := fmt.Errorf("oversized embedded node (size is %d bytes, want size < %d)", size, hashLen)
   191  			return nil, buf, err
   192  		}
   193  		n, err := decodeNode(nil, buf)
   194  		return n, rest, err
   195  	case kind == rlp.String && len(val) == 0:
   196  		// empty node
   197  		return nil, rest, nil
   198  	case kind == rlp.String && len(val) == 32:
   199  		return append(hashNode{}, val...), rest, nil
   200  	default:
   201  		return nil, nil, fmt.Errorf("invalid RLP string size %d (want 0 or 32)", len(val))
   202  	}
   203  }
   204  
   205  // wraps a decoding error with information about the path to the
   206  // invalid child node (for debugging encoding issues).
   207  type decodeError struct {
   208  	what  error
   209  	stack []string
   210  }
   211  
   212  func wrapError(err error, ctx string) error {
   213  	if err == nil {
   214  		return nil
   215  	}
   216  	if decErr, ok := err.(*decodeError); ok {
   217  		decErr.stack = append(decErr.stack, ctx)
   218  		return decErr
   219  	}
   220  	return &decodeError{err, []string{ctx}}
   221  }
   222  
   223  func (err *decodeError) Error() string {
   224  	return fmt.Sprintf("%v (decode path: %s)", err.what, strings.Join(err.stack, "<-"))
   225  }