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