github.com/klaytn/klaytn@v1.12.1/storage/statedb/node.go (about)

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