github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/trie/node.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar 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-aigar 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-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package trie
    19  
    20  import (
    21  	"fmt"
    22  	"io"
    23  	"strings"
    24  
    25  	"github.com/AigarNetwork/aigar/common"
    26  	"github.com/AigarNetwork/aigar/rlp"
    27  )
    28  
    29  var indices = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "[17]"}
    30  
    31  type node interface {
    32  	fstring(string) string
    33  	cache() (hashNode, 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  	dirty bool     // whether the node has changes that must be written to the database
    75  }
    76  
    77  func (n *fullNode) cache() (hashNode, bool)  { return n.flags.hash, n.flags.dirty }
    78  func (n *shortNode) cache() (hashNode, bool) { return n.flags.hash, n.flags.dirty }
    79  func (n hashNode) cache() (hashNode, bool)   { return nil, true }
    80  func (n valueNode) cache() (hashNode, bool)  { return nil, true }
    81  
    82  // Pretty printing.
    83  func (n *fullNode) String() string  { return n.fstring("") }
    84  func (n *shortNode) String() string { return n.fstring("") }
    85  func (n hashNode) String() string   { return n.fstring("") }
    86  func (n valueNode) String() string  { return n.fstring("") }
    87  
    88  func (n *fullNode) fstring(ind string) string {
    89  	resp := fmt.Sprintf("[\n%s  ", ind)
    90  	for i, node := range &n.Children {
    91  		if node == nil {
    92  			resp += fmt.Sprintf("%s: <nil> ", indices[i])
    93  		} else {
    94  			resp += fmt.Sprintf("%s: %v", indices[i], node.fstring(ind+"  "))
    95  		}
    96  	}
    97  	return resp + fmt.Sprintf("\n%s] ", ind)
    98  }
    99  func (n *shortNode) fstring(ind string) string {
   100  	return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+"  "))
   101  }
   102  func (n hashNode) fstring(ind string) string {
   103  	return fmt.Sprintf("<%x> ", []byte(n))
   104  }
   105  func (n valueNode) fstring(ind string) string {
   106  	return fmt.Sprintf("%x ", []byte(n))
   107  }
   108  
   109  func mustDecodeNode(hash, buf []byte) node {
   110  	n, err := decodeNode(hash, buf)
   111  	if err != nil {
   112  		panic(fmt.Sprintf("node %x: %v", hash, err))
   113  	}
   114  	return n
   115  }
   116  
   117  // decodeNode parses the RLP encoding of a trie node.
   118  func decodeNode(hash, buf []byte) (node, error) {
   119  	if len(buf) == 0 {
   120  		return nil, io.ErrUnexpectedEOF
   121  	}
   122  	elems, _, err := rlp.SplitList(buf)
   123  	if err != nil {
   124  		return nil, fmt.Errorf("decode error: %v", err)
   125  	}
   126  	switch c, _ := rlp.CountValues(elems); c {
   127  	case 2:
   128  		n, err := decodeShort(hash, elems)
   129  		return n, wrapError(err, "short")
   130  	case 17:
   131  		n, err := decodeFull(hash, elems)
   132  		return n, wrapError(err, "full")
   133  	default:
   134  		return nil, fmt.Errorf("invalid number of list elements: %v", c)
   135  	}
   136  }
   137  
   138  func decodeShort(hash, elems []byte) (node, error) {
   139  	kbuf, rest, err := rlp.SplitString(elems)
   140  	if err != nil {
   141  		return nil, err
   142  	}
   143  	flag := nodeFlag{hash: hash}
   144  	key := compactToHex(kbuf)
   145  	if hasTerm(key) {
   146  		// value node
   147  		val, _, err := rlp.SplitString(rest)
   148  		if err != nil {
   149  			return nil, fmt.Errorf("invalid value node: %v", err)
   150  		}
   151  		return &shortNode{key, append(valueNode{}, val...), flag}, nil
   152  	}
   153  	r, _, err := decodeRef(rest)
   154  	if err != nil {
   155  		return nil, wrapError(err, "val")
   156  	}
   157  	return &shortNode{key, r, flag}, nil
   158  }
   159  
   160  func decodeFull(hash, elems []byte) (*fullNode, error) {
   161  	n := &fullNode{flags: nodeFlag{hash: hash}}
   162  	for i := 0; i < 16; i++ {
   163  		cld, rest, err := decodeRef(elems)
   164  		if err != nil {
   165  			return n, wrapError(err, fmt.Sprintf("[%d]", i))
   166  		}
   167  		n.Children[i], elems = cld, rest
   168  	}
   169  	val, _, err := rlp.SplitString(elems)
   170  	if err != nil {
   171  		return n, err
   172  	}
   173  	if len(val) > 0 {
   174  		n.Children[16] = append(valueNode{}, val...)
   175  	}
   176  	return n, nil
   177  }
   178  
   179  const hashLen = len(common.Hash{})
   180  
   181  func decodeRef(buf []byte) (node, []byte, error) {
   182  	kind, val, rest, err := rlp.Split(buf)
   183  	if err != nil {
   184  		return nil, buf, err
   185  	}
   186  	switch {
   187  	case kind == rlp.List:
   188  		// 'embedded' node reference. The encoding must be smaller
   189  		// than a hash in order to be valid.
   190  		if size := len(buf) - len(rest); size > hashLen {
   191  			err := fmt.Errorf("oversized embedded node (size is %d bytes, want size < %d)", size, hashLen)
   192  			return nil, buf, err
   193  		}
   194  		n, err := decodeNode(nil, buf)
   195  		return n, rest, err
   196  	case kind == rlp.String && len(val) == 0:
   197  		// empty node
   198  		return nil, rest, nil
   199  	case kind == rlp.String && len(val) == 32:
   200  		return append(hashNode{}, val...), rest, nil
   201  	default:
   202  		return nil, nil, fmt.Errorf("invalid RLP string size %d (want 0 or 32)", len(val))
   203  	}
   204  }
   205  
   206  // wraps a decoding error with information about the path to the
   207  // invalid child node (for debugging encoding issues).
   208  type decodeError struct {
   209  	what  error
   210  	stack []string
   211  }
   212  
   213  func wrapError(err error, ctx string) error {
   214  	if err == nil {
   215  		return nil
   216  	}
   217  	if decErr, ok := err.(*decodeError); ok {
   218  		decErr.stack = append(decErr.stack, ctx)
   219  		return decErr
   220  	}
   221  	return &decodeError{err, []string{ctx}}
   222  }
   223  
   224  func (err *decodeError) Error() string {
   225  	return fmt.Sprintf("%v (decode path: %s)", err.what, strings.Join(err.stack, "<-"))
   226  }