trie.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright 2015 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 light
  17. import (
  18. "context"
  19. "errors"
  20. "fmt"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/trie"
  27. )
  28. func NewState(ctx context.Context, head *types.Header, odr OdrBackend) *state.StateDB {
  29. state, _ := state.New(head.Root, NewStateDatabase(ctx, head, odr))
  30. return state
  31. }
  32. func NewStateDatabase(ctx context.Context, head *types.Header, odr OdrBackend) state.Database {
  33. return &odrDatabase{ctx, StateTrieID(head), odr}
  34. }
  35. type odrDatabase struct {
  36. ctx context.Context
  37. id *TrieID
  38. backend OdrBackend
  39. }
  40. func (db *odrDatabase) OpenTrie(root common.Hash) (state.Trie, error) {
  41. return &odrTrie{db: db, id: db.id}, nil
  42. }
  43. func (db *odrDatabase) OpenStorageTrie(addrHash, root common.Hash) (state.Trie, error) {
  44. return &odrTrie{db: db, id: StorageTrieID(db.id, addrHash, root)}, nil
  45. }
  46. func (db *odrDatabase) CopyTrie(t state.Trie) state.Trie {
  47. switch t := t.(type) {
  48. case *odrTrie:
  49. cpy := &odrTrie{db: t.db, id: t.id}
  50. if t.trie != nil {
  51. cpytrie := *t.trie
  52. cpy.trie = &cpytrie
  53. }
  54. return cpy
  55. default:
  56. panic(fmt.Errorf("unknown trie type %T", t))
  57. }
  58. }
  59. func (db *odrDatabase) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
  60. if codeHash == sha3_nil {
  61. return nil, nil
  62. }
  63. if code, err := db.backend.Database().Get(codeHash[:]); err == nil {
  64. return code, nil
  65. }
  66. id := *db.id
  67. id.AccKey = addrHash[:]
  68. req := &CodeRequest{Id: &id, Hash: codeHash}
  69. err := db.backend.Retrieve(db.ctx, req)
  70. return req.Data, err
  71. }
  72. func (db *odrDatabase) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
  73. code, err := db.ContractCode(addrHash, codeHash)
  74. return len(code), err
  75. }
  76. func (db *odrDatabase) TrieDB() *trie.Database {
  77. return nil
  78. }
  79. type odrTrie struct {
  80. db *odrDatabase
  81. id *TrieID
  82. trie *trie.Trie
  83. }
  84. func (t *odrTrie) TryGet(key []byte) ([]byte, error) {
  85. key = crypto.Keccak256(key)
  86. var res []byte
  87. err := t.do(key, func() (err error) {
  88. res, err = t.trie.TryGet(key)
  89. return err
  90. })
  91. return res, err
  92. }
  93. func (t *odrTrie) TryUpdate(key, value []byte) error {
  94. key = crypto.Keccak256(key)
  95. return t.do(key, func() error {
  96. return t.trie.TryDelete(key)
  97. })
  98. }
  99. func (t *odrTrie) TryDelete(key []byte) error {
  100. key = crypto.Keccak256(key)
  101. return t.do(key, func() error {
  102. return t.trie.TryDelete(key)
  103. })
  104. }
  105. func (t *odrTrie) Commit(onleaf trie.LeafCallback) (common.Hash, error) {
  106. if t.trie == nil {
  107. return t.id.Root, nil
  108. }
  109. return t.trie.Commit(onleaf)
  110. }
  111. func (t *odrTrie) Hash() common.Hash {
  112. if t.trie == nil {
  113. return t.id.Root
  114. }
  115. return t.trie.Hash()
  116. }
  117. func (t *odrTrie) NodeIterator(startkey []byte) trie.NodeIterator {
  118. return newNodeIterator(t, startkey)
  119. }
  120. func (t *odrTrie) GetKey(sha []byte) []byte {
  121. return nil
  122. }
  123. func (t *odrTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error {
  124. return errors.New("not implemented, needs client/server interface split")
  125. }
  126. // do tries and retries to execute a function until it returns with no error or
  127. // an error type other than MissingNodeError
  128. func (t *odrTrie) do(key []byte, fn func() error) error {
  129. for {
  130. var err error
  131. if t.trie == nil {
  132. t.trie, err = trie.New(t.id.Root, trie.NewDatabase(t.db.backend.Database()))
  133. }
  134. if err == nil {
  135. err = fn()
  136. }
  137. if _, ok := err.(*trie.MissingNodeError); !ok {
  138. return err
  139. }
  140. r := &TrieRequest{Id: t.id, Key: key}
  141. if err := t.db.backend.Retrieve(t.db.ctx, r); err != nil {
  142. return err
  143. }
  144. }
  145. }
  146. type nodeIterator struct {
  147. trie.NodeIterator
  148. t *odrTrie
  149. err error
  150. }
  151. func newNodeIterator(t *odrTrie, startkey []byte) trie.NodeIterator {
  152. it := &nodeIterator{t: t}
  153. // Open the actual non-ODR trie if that hasn't happened yet.
  154. if t.trie == nil {
  155. it.do(func() error {
  156. t, err := trie.New(t.id.Root, trie.NewDatabase(t.db.backend.Database()))
  157. if err == nil {
  158. it.t.trie = t
  159. }
  160. return err
  161. })
  162. }
  163. it.do(func() error {
  164. it.NodeIterator = it.t.trie.NodeIterator(startkey)
  165. return it.NodeIterator.Error()
  166. })
  167. return it
  168. }
  169. func (it *nodeIterator) Next(descend bool) bool {
  170. var ok bool
  171. it.do(func() error {
  172. ok = it.NodeIterator.Next(descend)
  173. return it.NodeIterator.Error()
  174. })
  175. return ok
  176. }
  177. // do runs fn and attempts to fill in missing nodes by retrieving.
  178. func (it *nodeIterator) do(fn func() error) {
  179. var lasthash common.Hash
  180. for {
  181. it.err = fn()
  182. missing, ok := it.err.(*trie.MissingNodeError)
  183. if !ok {
  184. return
  185. }
  186. if missing.NodeHash == lasthash {
  187. it.err = fmt.Errorf("retrieve loop for trie node %x", missing.NodeHash)
  188. return
  189. }
  190. lasthash = missing.NodeHash
  191. r := &TrieRequest{Id: it.t.id, Key: nibblesToKey(missing.Path)}
  192. if it.err = it.t.db.backend.Retrieve(it.t.db.ctx, r); it.err != nil {
  193. return
  194. }
  195. }
  196. }
  197. func (it *nodeIterator) Error() error {
  198. if it.err != nil {
  199. return it.err
  200. }
  201. return it.NodeIterator.Error()
  202. }
  203. func nibblesToKey(nib []byte) []byte {
  204. if len(nib) > 0 && nib[len(nib)-1] == 0x10 {
  205. nib = nib[:len(nib)-1] // drop terminator
  206. }
  207. if len(nib)&1 == 1 {
  208. nib = append(nib, 0) // make even
  209. }
  210. key := make([]byte, len(nib)/2)
  211. for bi, ni := 0, 0; ni < len(nib); bi, ni = bi+1, ni+2 {
  212. key[bi] = nib[ni]<<4 | nib[ni+1]
  213. }
  214. return key
  215. }