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