trie.go 6.1 KB

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