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