trie.go 7.2 KB

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