node.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. package trie
  17. import (
  18. "fmt"
  19. "io"
  20. "strings"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/rlp"
  23. )
  24. var indices = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "[17]"}
  25. type node interface {
  26. fstring(string) string
  27. cache() (hashNode, bool)
  28. }
  29. type (
  30. fullNode struct {
  31. Children [17]node // Actual trie node data to encode/decode (needs custom encoder)
  32. hash hashNode // Cached hash of the node to prevent rehashing (may be nil)
  33. dirty bool // Cached flag whether the node's new or already stored
  34. }
  35. shortNode struct {
  36. Key []byte
  37. Val node
  38. hash hashNode // Cached hash of the node to prevent rehashing (may be nil)
  39. dirty bool // Cached flag whether the node's new or already stored
  40. }
  41. hashNode []byte
  42. valueNode []byte
  43. )
  44. // EncodeRLP encodes a full node into the consensus RLP format.
  45. func (n fullNode) EncodeRLP(w io.Writer) error {
  46. return rlp.Encode(w, n.Children)
  47. }
  48. // Cache accessors to retrieve precalculated values (avoid lengthy type switches).
  49. func (n fullNode) cache() (hashNode, bool) { return n.hash, n.dirty }
  50. func (n shortNode) cache() (hashNode, bool) { return n.hash, n.dirty }
  51. func (n hashNode) cache() (hashNode, bool) { return nil, true }
  52. func (n valueNode) cache() (hashNode, bool) { return nil, true }
  53. // Pretty printing.
  54. func (n fullNode) String() string { return n.fstring("") }
  55. func (n shortNode) String() string { return n.fstring("") }
  56. func (n hashNode) String() string { return n.fstring("") }
  57. func (n valueNode) String() string { return n.fstring("") }
  58. func (n fullNode) fstring(ind string) string {
  59. resp := fmt.Sprintf("[\n%s ", ind)
  60. for i, node := range n.Children {
  61. if node == nil {
  62. resp += fmt.Sprintf("%s: <nil> ", indices[i])
  63. } else {
  64. resp += fmt.Sprintf("%s: %v", indices[i], node.fstring(ind+" "))
  65. }
  66. }
  67. return resp + fmt.Sprintf("\n%s] ", ind)
  68. }
  69. func (n shortNode) fstring(ind string) string {
  70. return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+" "))
  71. }
  72. func (n hashNode) fstring(ind string) string {
  73. return fmt.Sprintf("<%x> ", []byte(n))
  74. }
  75. func (n valueNode) fstring(ind string) string {
  76. return fmt.Sprintf("%x ", []byte(n))
  77. }
  78. func mustDecodeNode(hash, buf []byte) node {
  79. n, err := decodeNode(hash, buf)
  80. if err != nil {
  81. panic(fmt.Sprintf("node %x: %v", hash, err))
  82. }
  83. return n
  84. }
  85. // decodeNode parses the RLP encoding of a trie node.
  86. func decodeNode(hash, buf []byte) (node, error) {
  87. if len(buf) == 0 {
  88. return nil, io.ErrUnexpectedEOF
  89. }
  90. elems, _, err := rlp.SplitList(buf)
  91. if err != nil {
  92. return nil, fmt.Errorf("decode error: %v", err)
  93. }
  94. switch c, _ := rlp.CountValues(elems); c {
  95. case 2:
  96. n, err := decodeShort(hash, buf, elems)
  97. return n, wrapError(err, "short")
  98. case 17:
  99. n, err := decodeFull(hash, buf, elems)
  100. return n, wrapError(err, "full")
  101. default:
  102. return nil, fmt.Errorf("invalid number of list elements: %v", c)
  103. }
  104. }
  105. func decodeShort(hash, buf, elems []byte) (node, error) {
  106. kbuf, rest, err := rlp.SplitString(elems)
  107. if err != nil {
  108. return nil, err
  109. }
  110. key := compactDecode(kbuf)
  111. if key[len(key)-1] == 16 {
  112. // value node
  113. val, _, err := rlp.SplitString(rest)
  114. if err != nil {
  115. return nil, fmt.Errorf("invalid value node: %v", err)
  116. }
  117. return shortNode{key, valueNode(val), hash, false}, nil
  118. }
  119. r, _, err := decodeRef(rest)
  120. if err != nil {
  121. return nil, wrapError(err, "val")
  122. }
  123. return shortNode{key, r, hash, false}, nil
  124. }
  125. func decodeFull(hash, buf, elems []byte) (fullNode, error) {
  126. n := fullNode{hash: hash}
  127. for i := 0; i < 16; i++ {
  128. cld, rest, err := decodeRef(elems)
  129. if err != nil {
  130. return n, wrapError(err, fmt.Sprintf("[%d]", i))
  131. }
  132. n.Children[i], elems = cld, rest
  133. }
  134. val, _, err := rlp.SplitString(elems)
  135. if err != nil {
  136. return n, err
  137. }
  138. if len(val) > 0 {
  139. n.Children[16] = valueNode(val)
  140. }
  141. return n, nil
  142. }
  143. const hashLen = len(common.Hash{})
  144. func decodeRef(buf []byte) (node, []byte, error) {
  145. kind, val, rest, err := rlp.Split(buf)
  146. if err != nil {
  147. return nil, buf, err
  148. }
  149. switch {
  150. case kind == rlp.List:
  151. // 'embedded' node reference. The encoding must be smaller
  152. // than a hash in order to be valid.
  153. if size := len(buf) - len(rest); size > hashLen {
  154. err := fmt.Errorf("oversized embedded node (size is %d bytes, want size < %d)", size, hashLen)
  155. return nil, buf, err
  156. }
  157. n, err := decodeNode(nil, buf)
  158. return n, rest, err
  159. case kind == rlp.String && len(val) == 0:
  160. // empty node
  161. return nil, rest, nil
  162. case kind == rlp.String && len(val) == 32:
  163. return hashNode(val), rest, nil
  164. default:
  165. return nil, nil, fmt.Errorf("invalid RLP string size %d (want 0 or 32)", len(val))
  166. }
  167. }
  168. // wraps a decoding error with information about the path to the
  169. // invalid child node (for debugging encoding issues).
  170. type decodeError struct {
  171. what error
  172. stack []string
  173. }
  174. func wrapError(err error, ctx string) error {
  175. if err == nil {
  176. return nil
  177. }
  178. if decErr, ok := err.(*decodeError); ok {
  179. decErr.stack = append(decErr.stack, ctx)
  180. return decErr
  181. }
  182. return &decodeError{err, []string{ctx}}
  183. }
  184. func (err *decodeError) Error() string {
  185. return fmt.Sprintf("%v (decode path: %s)", err.what, strings.Join(err.stack, "<-"))
  186. }