node.go 7.1 KB

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