node.go 6.2 KB

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