node.go 7.0 KB

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