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