-
Notifications
You must be signed in to change notification settings - Fork 177
/
base.go
501 lines (441 loc) · 12.7 KB
/
base.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
package state
import (
"fmt"
"math/big"
gethCommon "github.com/ethereum/go-ethereum/common"
gethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/onflow/atree"
"github.com/onflow/flow-go/fvm/evm/types"
"github.com/onflow/flow-go/model/flow"
)
const (
// AccountsStorageIDKey is the path where we store the collection ID for accounts
AccountsStorageIDKey = "AccountsStorageIDKey"
// CodesStorageIDKey is the path where we store the collection ID for codes
CodesStorageIDKey = "CodesStorageIDKey"
)
// BaseView implements a types.BaseView
// it acts as the base layer of state queries for the stateDB
// it stores accounts, codes and storage slots.
//
// under the hood it uses a set of collections,
// one for account's meta data, one for codes
// and one for each of account storage space.
type BaseView struct {
rootAddress flow.Address
ledger atree.Ledger
collectionProvider *CollectionProvider
// collections
accounts *Collection
codes *Collection
slots map[gethCommon.Address]*Collection
// cached values
cachedAccounts map[gethCommon.Address]*Account
cachedCodes map[gethCommon.Address][]byte
cachedSlots map[types.SlotAddress]gethCommon.Hash
// flags
accountSetupOnCommit bool
codeSetupOnCommit bool
}
var _ types.BaseView = &BaseView{}
// NewBaseView constructs a new base view
func NewBaseView(ledger atree.Ledger, rootAddress flow.Address) (*BaseView, error) {
cp, err := NewCollectionProvider(atree.Address(rootAddress), ledger)
if err != nil {
return nil, err
}
view := &BaseView{
ledger: ledger,
rootAddress: rootAddress,
collectionProvider: cp,
slots: make(map[gethCommon.Address]*Collection),
cachedAccounts: make(map[gethCommon.Address]*Account),
cachedCodes: make(map[gethCommon.Address][]byte),
cachedSlots: make(map[types.SlotAddress]gethCommon.Hash),
}
// fetch the account collection, if not exist, create one
view.accounts, view.accountSetupOnCommit, err = view.fetchOrCreateCollection(AccountsStorageIDKey)
if err != nil {
return nil, err
}
// fetch the code collection, if not exist, create one
view.codes, view.codeSetupOnCommit, err = view.fetchOrCreateCollection(CodesStorageIDKey)
if err != nil {
return nil, err
}
return view, nil
}
// Exist returns true if the address exist in the state
func (v *BaseView) Exist(addr gethCommon.Address) (bool, error) {
acc, err := v.getAccount(addr)
return acc != nil, err
}
// IsCreated returns true if the address has been created in the context of this transaction
func (v *BaseView) IsCreated(gethCommon.Address) bool {
return false
}
// HasSelfDestructed returns true if an address is flagged for destruction at the end of transaction
func (v *BaseView) HasSelfDestructed(gethCommon.Address) (bool, *big.Int) {
return false, new(big.Int)
}
// GetBalance returns the balance of an address
//
// for non-existent accounts it returns a balance of zero
func (v *BaseView) GetBalance(addr gethCommon.Address) (*big.Int, error) {
acc, err := v.getAccount(addr)
bal := big.NewInt(0)
if acc != nil {
bal = acc.Balance
}
return bal, err
}
// GetNonce returns the nonce of an address
//
// for non-existent accounts it returns zero
func (v *BaseView) GetNonce(addr gethCommon.Address) (uint64, error) {
acc, err := v.getAccount(addr)
nonce := uint64(0)
if acc != nil {
nonce = acc.Nonce
}
return nonce, err
}
// GetCode returns the code of an address
//
// for non-existent accounts or accounts without a code (e.g. EOAs) it returns nil
func (v *BaseView) GetCode(addr gethCommon.Address) ([]byte, error) {
return v.getCode(addr)
}
// GetCodeHash returns the code hash of an address
//
// for non-existent accounts or accounts without a code (e.g. EOAs) it returns default empty
// hash value (gethTypes.EmptyCodeHash)
func (v *BaseView) GetCodeHash(addr gethCommon.Address) (gethCommon.Hash, error) {
acc, err := v.getAccount(addr)
codeHash := gethTypes.EmptyCodeHash
if acc != nil {
codeHash = acc.CodeHash
}
return codeHash, err
}
// GetCodeSize returns the code size of an address
//
// for non-existent accounts or accounts without a code (e.g. EOAs) it returns zero
func (v *BaseView) GetCodeSize(addr gethCommon.Address) (int, error) {
code, err := v.GetCode(addr)
return len(code), err
}
// GetState returns values for a slot in the main storage
//
// for non-existent slots it returns the default empty hash value (gethTypes.EmptyCodeHash)
func (v *BaseView) GetState(sk types.SlotAddress) (gethCommon.Hash, error) {
return v.getSlot(sk)
}
// UpdateSlot updates the value for a slot
func (v *BaseView) UpdateSlot(sk types.SlotAddress, value gethCommon.Hash) error {
return v.storeSlot(sk, value)
}
// GetRefund returns the total amount of (gas) refund
//
// this method returns the value of zero
func (v *BaseView) GetRefund() uint64 {
return 0
}
// GetTransientState returns values for an slot transient storage
//
// transient storage is not a functionality for the base view so it always
// returns the default value for non-existent slots
func (v *BaseView) GetTransientState(types.SlotAddress) gethCommon.Hash {
return gethCommon.Hash{}
}
// AddressInAccessList checks if an address is in the access list
//
// access list control is not a functionality of the base view
// it always returns false
func (v *BaseView) AddressInAccessList(gethCommon.Address) bool {
return false
}
// SlotInAccessList checks if a slot is in the access list
//
// access list control is not a functionality of the base view
// it always returns false
func (v *BaseView) SlotInAccessList(types.SlotAddress) (addressOk bool, slotOk bool) {
return false, false
}
// CreateAccount creates a new account
func (v *BaseView) CreateAccount(
addr gethCommon.Address,
balance *big.Int,
nonce uint64,
code []byte,
codeHash gethCommon.Hash,
) error {
var colID []byte
// if is an smart contract account
if len(code) > 0 {
err := v.storeCode(addr, code)
if err != nil {
return err
}
}
// create a new account and store it
acc := NewAccount(addr, balance, nonce, codeHash, colID)
// no need to update the cache , storeAccount would update the cache
return v.storeAccount(acc)
}
// UpdateAccount updates an account's meta data
func (v *BaseView) UpdateAccount(
addr gethCommon.Address,
balance *big.Int,
nonce uint64,
code []byte,
codeHash gethCommon.Hash,
) error {
acc, err := v.getAccount(addr)
if err != nil {
return err
}
// if update is called on a non existing account
// we gracefully call the create account
// TODO: but we might need to revisit this action in the future
if acc == nil {
return v.CreateAccount(addr, balance, nonce, code, codeHash)
}
// if it has a code change
if codeHash != acc.CodeHash {
err := v.storeCode(addr, code)
if err != nil {
return err
}
// TODO: maybe purge the state in the future as well
// currently the behaviour of stateDB doesn't purge the data
// We don't need to check if the code is empty and we purge the state
// this is not possible right now.
}
newAcc := NewAccount(addr, balance, nonce, codeHash, acc.CollectionID)
// no need to update the cache , storeAccount would update the cache
return v.storeAccount(newAcc)
}
// DeleteAccount deletes an account's meta data, code, and
// storage slots associated with that address
func (v *BaseView) DeleteAccount(addr gethCommon.Address) error {
// 1. check account exists
acc, err := v.getAccount(addr)
if err != nil {
return err
}
if acc == nil {
return fmt.Errorf("account doesn't exist to be deleted")
}
// 2. update the cache
delete(v.cachedAccounts, addr)
// 3. collections
err = v.accounts.Remove(addr.Bytes())
if err != nil {
return err
}
// 4. remove the code
if acc.HasCode() {
err = v.storeCode(addr, nil)
if err != nil {
return err
}
}
// 5. remove storage slots
if len(acc.CollectionID) > 0 {
col, found := v.slots[addr]
if !found {
col, err = v.collectionProvider.CollectionByID(acc.CollectionID)
if err != nil {
return err
}
}
// delete all slots related to this account (eip-6780)
keys, err := col.Destroy()
if err != nil {
return err
}
delete(v.slots, addr)
for _, key := range keys {
delete(v.cachedSlots, types.SlotAddress{
Address: addr,
Key: gethCommon.BytesToHash(key),
})
}
}
return nil
}
// Commit commits the changes to the underlying storage layers
func (v *BaseView) Commit() error {
// commit collection changes
err := v.collectionProvider.Commit()
if err != nil {
return err
}
// if this is the first time we are setting up an
// account collection, store its collection id.
if v.accountSetupOnCommit {
err = v.ledger.SetValue(v.rootAddress[:], []byte(AccountsStorageIDKey), v.accounts.CollectionID())
if err != nil {
return err
}
v.accountSetupOnCommit = false
}
// if this is the first time we are setting up an
// code collection, store its collection id.
if v.codeSetupOnCommit {
err = v.ledger.SetValue(v.rootAddress[:], []byte(CodesStorageIDKey), v.codes.CollectionID())
if err != nil {
return err
}
v.codeSetupOnCommit = false
}
return nil
}
func (v *BaseView) fetchOrCreateCollection(path string) (collection *Collection, created bool, error error) {
collectionID, err := v.ledger.GetValue(v.rootAddress[:], []byte(path))
if err != nil {
return nil, false, err
}
if len(collectionID) == 0 {
collection, err = v.collectionProvider.NewCollection()
return collection, true, err
}
collection, err = v.collectionProvider.CollectionByID(collectionID)
return collection, false, err
}
func (v *BaseView) getAccount(addr gethCommon.Address) (*Account, error) {
// check cached accounts first
acc, found := v.cachedAccounts[addr]
if found {
return acc, nil
}
// then collect it from the account collection
data, err := v.accounts.Get(addr.Bytes())
if err != nil {
return nil, err
}
// decode it
acc, err = DecodeAccount(data)
if err != nil {
return nil, err
}
// cache it
if acc != nil {
v.cachedAccounts[addr] = acc
}
return acc, nil
}
func (v *BaseView) storeAccount(acc *Account) error {
data, err := acc.Encode()
if err != nil {
return err
}
// update the cache
v.cachedAccounts[acc.Address] = acc
return v.accounts.Set(acc.Address.Bytes(), data)
}
func (v *BaseView) getCode(addr gethCommon.Address) ([]byte, error) {
// check the cache first
code, found := v.cachedCodes[addr]
if found {
return code, nil
}
// check if account exist in cache and has codeHash
acc, found := v.cachedAccounts[addr]
if found && !acc.HasCode() {
return nil, nil
}
// then collect it from the code collection
code, err := v.codes.Get(addr.Bytes())
if err != nil {
return nil, err
}
if code != nil {
v.cachedCodes[addr] = code
}
return code, nil
}
func (v *BaseView) storeCode(addr gethCommon.Address, code []byte) error {
if len(code) == 0 {
delete(v.cachedCodes, addr)
return v.codes.Remove(addr.Bytes())
}
v.cachedCodes[addr] = code
return v.codes.Set(addr.Bytes(), code)
}
func (v *BaseView) getSlot(sk types.SlotAddress) (gethCommon.Hash, error) {
value, found := v.cachedSlots[sk]
if found {
return value, nil
}
acc, err := v.getAccount(sk.Address)
if err != nil {
return gethCommon.Hash{}, err
}
if acc == nil || len(acc.CollectionID) == 0 {
return gethCommon.Hash{}, nil
}
col, err := v.getSlotCollection(acc)
if err != nil {
return gethCommon.Hash{}, err
}
val, err := col.Get(sk.Key.Bytes())
if err != nil {
return gethCommon.Hash{}, err
}
value = gethCommon.BytesToHash(val)
v.cachedSlots[sk] = value
return value, nil
}
func (v *BaseView) storeSlot(sk types.SlotAddress, data gethCommon.Hash) error {
acc, err := v.getAccount(sk.Address)
if err != nil {
return err
}
if acc == nil {
return fmt.Errorf("slot belongs to a non-existing account")
}
if !acc.HasCode() {
return fmt.Errorf("slot belongs to a non-smart contract account")
}
col, err := v.getSlotCollection(acc)
if err != nil {
return err
}
emptyValue := gethCommon.Hash{}
if data == emptyValue {
delete(v.cachedSlots, sk)
return col.Remove(sk.Key.Bytes())
}
v.cachedSlots[sk] = data
return col.Set(sk.Key.Bytes(), data.Bytes())
}
func (v *BaseView) getSlotCollection(acc *Account) (*Collection, error) {
var err error
if len(acc.CollectionID) == 0 {
// create a new collection for slots
col, err := v.collectionProvider.NewCollection()
if err != nil {
return nil, err
}
// cache collection
v.slots[acc.Address] = col
// update account's collection ID
acc.CollectionID = col.CollectionID()
err = v.storeAccount(acc)
if err != nil {
return nil, err
}
return col, nil
}
col, found := v.slots[acc.Address]
if !found {
col, err = v.collectionProvider.CollectionByID(acc.CollectionID)
if err != nil {
return nil, err
}
v.slots[acc.Address] = col
}
return col, nil
}