-
Notifications
You must be signed in to change notification settings - Fork 0
/
storeview.go
674 lines (578 loc) · 18 KB
/
storeview.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
package state
import (
"bytes"
"fmt"
"math/big"
log "github.com/sirupsen/logrus"
"github.com/dnerochain/dnero/common"
"github.com/dnerochain/dnero/core"
"github.com/dnerochain/dnero/crypto"
"github.com/dnerochain/dnero/ledger/types"
"github.com/dnerochain/dnero/rlp"
"github.com/dnerochain/dnero/store/database"
"github.com/dnerochain/dnero/store/treestore"
)
var logger *log.Entry = log.WithFields(log.Fields{"prefix": "ledger"})
//
// ------------------------- StoreView -------------------------
//
type StoreView struct {
height uint64 // block height
store *treestore.TreeStore
coinbaseTransactinProcessed bool
slashIntents []types.SlashIntent
refund uint64 // Gas refund during smart contract execution
logs []*types.Log // Temporary store of events during smart contract execution
}
// NewStoreView creates an instance of the StoreView
func NewStoreView(height uint64, root common.Hash, db database.Database) *StoreView {
store := treestore.NewTreeStore(root, db)
if store == nil {
return nil
}
sv := &StoreView{
height: height,
store: store,
slashIntents: []types.SlashIntent{},
refund: 0,
}
return sv
}
// Copy returns a copy of the StoreView
func (sv *StoreView) Copy() (*StoreView, error) {
copiedStore, err := sv.store.Copy()
if err != nil {
return nil, err
}
copiedStoreView := &StoreView{
height: sv.height,
store: copiedStore,
slashIntents: []types.SlashIntent{},
refund: 0,
}
return copiedStoreView, nil
}
// GetDB returns the underlying database.
func (sv *StoreView) GetDB() database.Database {
return sv.store.GetDB()
}
// Hash returns the root hash of the tree store
func (sv *StoreView) Hash() common.Hash {
return sv.store.Hash()
}
// Height returns the block height corresponding to the stored state
func (sv *StoreView) Height() uint64 {
return sv.height
}
// IncrementHeight increments the block height by 1
func (sv *StoreView) IncrementHeight() {
sv.height++
}
// Save saves the StoreView to the persistent storage, and return the root hash
func (sv *StoreView) Save() common.Hash {
rootHash, err := sv.store.Commit()
logger.Debugf("Commit to data store, height: %v, rootHash: %v", sv.height+1, rootHash.Hex())
if err != nil {
log.Panicf("Failed to save the StoreView: %v", err)
}
return rootHash
}
// Get returns the value corresponding to the key
func (sv *StoreView) Get(key common.Bytes) common.Bytes {
value := sv.store.Get(key)
return value
}
func (sv *StoreView) ProveVCP(vcpKey []byte, vp *core.VCPProof) error {
return sv.store.ProveVCP(vcpKey, vp)
}
// Delete removes the value corresponding to the key
func (sv *StoreView) Delete(key common.Bytes) {
sv.store.Delete(key)
}
// Set returns the value corresponding to the key
func (sv *StoreView) Set(key common.Bytes, value common.Bytes) {
sv.store.Set(key, value)
}
// AddSlashIntent adds slashIntent
func (sv *StoreView) AddSlashIntent(slashIntent types.SlashIntent) {
sv.slashIntents = append(sv.slashIntents, slashIntent)
}
// GetSlashIntents retrieves all the slashIntents
func (sv *StoreView) GetSlashIntents() []types.SlashIntent {
return sv.slashIntents
}
// ClearSlashIntents clears all the slashIntents
func (sv *StoreView) ClearSlashIntents() {
sv.slashIntents = []types.SlashIntent{}
}
// CoinbaseTransactinProcessed returns whether the coinbase transaction for the current block has been processed
func (sv *StoreView) CoinbaseTransactinProcessed() bool {
return sv.coinbaseTransactinProcessed
}
// SetCoinbaseTransactionProcessed sets whether the coinbase transaction for the current block has been processed
func (sv *StoreView) SetCoinbaseTransactionProcessed(processed bool) {
sv.coinbaseTransactinProcessed = processed
}
// GetAccount returns an account.
func (sv *StoreView) GetAccount(addr common.Address) *types.Account {
data := sv.Get(AccountKey(addr))
if data == nil || len(data) == 0 {
return nil
}
acc := &types.Account{}
err := types.FromBytes(data, acc)
if err != nil {
log.Panicf("Error reading account %X error: %v",
data, err.Error())
}
return acc
}
// // SetAccount sets an account.
// func (sv *StoreView) SetAccount(addr common.Address, acc *types.Account) {
// accBytes, err := types.ToBytes(acc)
// if err != nil {
// log.Panicf("Error writing account %v error: %v",
// acc, err.Error())
// }
// sv.Set(AccountKey(addr), accBytes)
// }
// SetAccount sets an account.
func (sv *StoreView) SetAccount(addr common.Address, acc *types.Account) {
sv.setAccount(addr, acc, true)
}
func (sv *StoreView) setAccountWithoutStateTreeRefCountUpdate(addr common.Address, acc *types.Account) {
sv.setAccount(addr, acc, false)
}
func (sv *StoreView) setAccount(addr common.Address, acc *types.Account, updateRefCountForAccountStateTree bool) {
accBytes, err := types.ToBytes(acc)
if err != nil {
log.Panicf("Error writing account %v error: %v",
acc, err.Error())
}
sv.Set(AccountKey(addr), accBytes)
if !updateRefCountForAccountStateTree {
return
}
if (acc == nil || acc.Root == common.Hash{}) || (acc.Root == core.EmptyRootHash) {
return
}
tree := sv.getAccountStorage(acc)
_, err = tree.Commit() // update the reference count of the account state trie root
if err != nil {
log.Panic(err)
}
}
// DeleteAccount deletes an account.
func (sv *StoreView) DeleteAccount(addr common.Address) {
sv.Delete(AccountKey(addr))
}
// SplitRuleExists checks if a split rule associated with the given resourceID already exists
func (sv *StoreView) SplitRuleExists(resourceID string) bool {
return sv.GetSplitRule(resourceID) != nil
}
// AddSplitRule adds a split rule
func (sv *StoreView) AddSplitRule(splitRule *types.SplitRule) bool {
if sv.SplitRuleExists(splitRule.ResourceID) {
return false // Each resourceID can have at most one corresponding split rule
}
sv.SetSplitRule(splitRule.ResourceID, splitRule)
return true
}
// UpdateSplitRule updates a split rule
func (sv *StoreView) UpdateSplitRule(splitRule *types.SplitRule) bool {
if !sv.SplitRuleExists(splitRule.ResourceID) {
return false
}
sv.SetSplitRule(splitRule.ResourceID, splitRule)
return true
}
// GetSplitRule gets split rule.
func (sv *StoreView) GetSplitRule(resourceID string) *types.SplitRule {
data := sv.Get(SplitRuleKey(resourceID))
if data == nil || len(data) == 0 {
return nil
}
splitRule := &types.SplitRule{}
err := types.FromBytes(data, splitRule)
if err != nil {
log.Panicf("Error reading splitRule %X error: %v",
data, err.Error())
}
return splitRule
}
// SetSplitRule sets split rule.
func (sv *StoreView) SetSplitRule(resourceID string, splitRule *types.SplitRule) {
splitRuleBytes, err := types.ToBytes(splitRule)
if err != nil {
log.Panicf("Error writing splitRule %v error: %v",
splitRule, err.Error())
}
sv.Set(SplitRuleKey(resourceID), splitRuleBytes)
}
// DeleteSplitRule deletes a split rule.
func (sv *StoreView) DeleteSplitRule(resourceID string) bool {
key := SplitRuleKey(resourceID)
deleted := sv.store.Delete(key)
return deleted
}
// DeleteExpiredSplitRules deletes a split rule.
func (sv *StoreView) DeleteExpiredSplitRules(currentBlockHeight uint64) bool {
prefix := SplitRuleKeyPrefix()
expiredKeys := []common.Bytes{}
sv.store.Traverse(prefix, func(key, value common.Bytes) bool {
var splitRule types.SplitRule
err := types.FromBytes(value, &splitRule)
if err != nil {
log.Panicf("Error reading splitRule %X error: %v", value, err.Error())
}
expired := (splitRule.EndBlockHeight < currentBlockHeight)
if expired {
expiredKeys = append(expiredKeys, key)
}
return true
})
for _, key := range expiredKeys {
deleted := sv.store.Delete(key)
if !deleted {
logger.Errorf("Failed to delete expired split rules")
return false
}
}
return true
}
// GetValidatorCandidatePool gets the validator candidate pool.
func (sv *StoreView) GetValidatorCandidatePool() *core.ValidatorCandidatePool {
data := sv.Get(ValidatorCandidatePoolKey())
if data == nil || len(data) == 0 {
return nil
}
vcp := &core.ValidatorCandidatePool{}
err := types.FromBytes(data, vcp)
if err != nil {
log.Panicf("Error reading validator candidate pool %X, error: %v",
data, err.Error())
}
return vcp
}
// UpdateValidatorCandidatePool updates the validator candidate pool.
func (sv *StoreView) UpdateValidatorCandidatePool(vcp *core.ValidatorCandidatePool) {
vcpBytes, err := types.ToBytes(vcp)
if err != nil {
log.Panicf("Error writing validator candidate pool %v, error: %v",
vcp, err.Error())
}
sv.Set(ValidatorCandidatePoolKey(), vcpBytes)
}
// GetGuradianCandidatePool gets the sentry candidate pool.
func (sv *StoreView) GetSentryCandidatePool() *core.SentryCandidatePool {
data := sv.Get(SentryCandidatePoolKey())
if data == nil || len(data) == 0 {
return core.NewSentryCandidatePool()
}
gcp := &core.SentryCandidatePool{}
err := types.FromBytes(data, gcp)
if err != nil {
log.Panicf("Error reading validator candidate pool %X, error: %v",
data, err.Error())
}
return gcp
}
// UpdateSentryCandidatePool updates the sentry candidate pool.
func (sv *StoreView) UpdateSentryCandidatePool(gcp *core.SentryCandidatePool) {
gcpBytes, err := types.ToBytes(gcp)
if err != nil {
log.Panicf("Error writing sentry candidate pool %v, error: %v",
gcp, err.Error())
}
sv.Set(SentryCandidatePoolKey(), gcpBytes)
}
// GetStakeTransactionHeightList gets the heights of blocks that contain stake related transactions
func (sv *StoreView) GetStakeTransactionHeightList() *types.HeightList {
data := sv.Get(StakeTransactionHeightListKey())
if data == nil || len(data) == 0 {
return nil
}
hl := &types.HeightList{}
err := types.FromBytes(data, hl)
if err != nil {
log.Panicf("Error reading height list %X, error: %v",
data, err.Error())
}
return hl
}
// UpdateStakeTransactionHeightList updates the heights of blocks that contain stake related transactions
func (sv *StoreView) UpdateStakeTransactionHeightList(hl *types.HeightList) {
hlBytes, err := types.ToBytes(hl)
if err != nil {
log.Panicf("Error writing height list %v, error: %v",
hl, err.Error())
}
sv.Set(StakeTransactionHeightListKey(), hlBytes)
}
func (sv *StoreView) GetStore() *treestore.TreeStore {
return sv.store
}
func (sv *StoreView) ResetLogs() {
sv.logs = []*types.Log{}
}
func (sv *StoreView) PopLogs() []*types.Log {
ret := sv.logs
sv.ResetLogs()
return ret
}
//
// ---------- Implement vm.StateDB interface -----------
//
func (sv *StoreView) CreateAccount(addr common.Address) {
account := types.NewAccount(addr)
sv.SetAccount(addr, account)
}
func (sv *StoreView) GetOrCreateAccount(addr common.Address) *types.Account {
account := sv.GetAccount(addr)
if account != nil {
return account
}
return types.NewAccount(addr)
}
func (sv *StoreView) SubBalance(addr common.Address, amount *big.Int) {
if amount.Sign() == 0 {
return
}
account := sv.GetAccount(addr)
if account == nil {
panic(fmt.Sprintf("Account for %v does not exist!", addr))
}
account.Balance = account.Balance.NoNil()
account.Balance.DTokenWei.Sub(account.Balance.DTokenWei, amount)
sv.SetAccount(addr, account)
}
func (sv *StoreView) AddBalance(addr common.Address, amount *big.Int) {
if amount.Sign() == 0 {
return
}
account := sv.GetOrCreateAccount(addr)
account.Balance = account.Balance.NoNil()
account.Balance.DTokenWei.Add(account.Balance.DTokenWei, amount)
sv.SetAccount(addr, account)
}
func (sv *StoreView) GetBalance(addr common.Address) *big.Int {
return sv.GetOrCreateAccount(addr).Balance.DTokenWei
}
// GetDneroBalance returns the DneroWei balance of the given address
func (sv *StoreView) GetDneroBalance(addr common.Address) *big.Int {
return sv.GetOrCreateAccount(addr).Balance.DneroWei
}
// GetDneroStake returns the total amount of DneroWei the address staked to validators and/or sentrys
func (sv *StoreView) GetDneroStake(addr common.Address) *big.Int {
totalStake := big.NewInt(0)
vcp := sv.GetValidatorCandidatePool()
for _, v := range vcp.SortedCandidates {
for _, stake := range v.Stakes {
if stake.Source == addr {
if stake.Withdrawn {
continue // withdrawn stake does not count
}
totalStake = new(big.Int).Add(stake.Amount, totalStake)
}
}
}
gcp := sv.GetSentryCandidatePool()
for _, g := range gcp.SortedSentrys {
for _, stake := range g.Stakes {
if stake.Source == addr {
if stake.Withdrawn {
continue // withdrawn stake does not count
}
totalStake = new(big.Int).Add(stake.Amount, totalStake)
}
}
}
return totalStake
}
func (sv *StoreView) GetNonce(addr common.Address) uint64 {
return sv.GetOrCreateAccount(addr).Sequence
}
func (sv *StoreView) SetNonce(addr common.Address, nonce uint64) {
account := sv.GetOrCreateAccount(addr)
account.Sequence = nonce
sv.SetAccount(addr, account)
}
func (sv *StoreView) GetCodeHash(addr common.Address) common.Hash {
account := sv.GetAccount(addr)
if account == nil {
return common.Hash{}
}
return account.CodeHash
}
func (sv *StoreView) GetCode(addr common.Address) []byte {
account := sv.GetAccount(addr)
if account == nil {
return nil
}
if (account.CodeHash == types.EmptyCodeHash) || (account.CodeHash == core.SuicidedCodeHash) {
return nil
}
return sv.GetCodeByHash(account.CodeHash)
}
func (sv *StoreView) GetCodeByHash(codeHash common.Hash) []byte {
if codeHash == core.SuicidedCodeHash {
return nil
}
codeKey := CodeKey(codeHash[:])
return sv.Get(codeKey)
}
func (sv *StoreView) SetCode(addr common.Address, code []byte) {
account := sv.GetOrCreateAccount(addr)
codeHash := crypto.Keccak256Hash(code)
account.CodeHash = codeHash
sv.Set(CodeKey(account.CodeHash[:]), code)
sv.SetAccount(addr, account)
}
func (sv *StoreView) GetCodeSize(addr common.Address) int {
return len(sv.GetCode(addr))
}
func (sv *StoreView) AddRefund(gas uint64) {
sv.refund += gas
}
func (sv *StoreView) SubRefund(gas uint64) {
if gas > sv.refund {
log.Panic("Refund counter below zero")
}
sv.refund -= gas
}
func (sv *StoreView) GetRefund() uint64 {
return sv.refund
}
func (sv *StoreView) ResetRefund() {
sv.refund = 0
}
func (sv *StoreView) GetBlockHeight() uint64 {
blockHeight := sv.height + 1
return blockHeight
}
func (sv *StoreView) GetCommittedState(addr common.Address, key common.Hash) common.Hash {
return sv.GetState(addr, key)
}
func (sv *StoreView) getAccountStorage(account *types.Account) *treestore.TreeStore {
return treestore.NewTreeStore(account.Root, sv.store.GetDB())
}
func (sv *StoreView) GetState(addr common.Address, key common.Hash) common.Hash {
account := sv.GetAccount(addr)
if account == nil {
return common.Hash{}
}
logger.Debugf("StoreView.GetState, address: %v, account.root: %v, key: %v", addr, account.Root.Hex(), key.Hex())
enc, err := sv.getAccountStorage(account).TryGet(key[:])
if err != nil {
log.Panic(err)
}
if len(enc) > 0 {
_, content, _, err := rlp.Split(enc)
if err != nil {
log.Panic(err)
}
return common.BytesToHash(content)
}
return common.Hash{}
}
func (sv *StoreView) SetState(addr common.Address, key, val common.Hash) {
account := sv.GetAccount(addr)
if account == nil {
account = types.NewAccount(addr)
}
tree := sv.getAccountStorage(account)
if (val == common.Hash{}) {
tree.TryDelete(key[:])
root, err := tree.Commit()
if err != nil {
log.Panic(err)
}
account.Root = root
sv.setAccountWithoutStateTreeRefCountUpdate(addr, account) // The ref counts of the state tree already got updated above
logger.Debugf("StoreView.SetState, address: %v, account.root: %v, key: %v, val: %v", addr.Hex(), root.Hex(), key.Hex(), val.Hex())
return
}
// Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(bytes.TrimLeft(val[:], "\x00"))
tree.TryUpdate(key[:], v)
root, err := tree.Commit()
if err != nil {
log.Panic(err)
}
account.Root = root
sv.setAccountWithoutStateTreeRefCountUpdate(addr, account) // The ref counts of the state tree already got updated above
logger.Debugf("StoreView.SetState, address: %v, account.root: %v, key: %v, val: %v", addr.Hex(), root.Hex(), key.Hex(), val.Hex())
}
func (sv *StoreView) Suicide(addr common.Address) bool {
account := sv.GetAccount(addr)
if account == nil {
return false
}
account.CodeHash = core.SuicidedCodeHash
account.Balance.DTokenWei = big.NewInt(0)
sv.SetAccount(addr, account)
return true
}
func (sv *StoreView) HasSuicided(addr common.Address) bool {
account := sv.GetAccount(addr)
if account == nil {
return true
}
hasSuicided := (account.CodeHash == core.SuicidedCodeHash)
return hasSuicided
}
// Exist reports whether the given account exists in state.
// Notably this should also return true for suicided accounts.
func (sv *StoreView) Exist(addr common.Address) bool {
account := sv.GetAccount(addr)
return account != nil
}
// Empty returns whether the given account is empty. Empty
// is defined according to EIP161 (balance = nonce = code = 0).
func (sv *StoreView) Empty(addr common.Address) bool {
account := sv.GetAccount(addr)
if account == nil {
return true
}
return account.Sequence == 0 &&
account.CodeHash == types.EmptyCodeHash &&
account.Balance.IsZero()
}
func (sv *StoreView) RevertToSnapshot(root common.Hash) {
var err error
sv.store, err = sv.store.Revert(root) // revert to one of the previous roots
if err != nil {
log.Panic(err)
}
}
func (sv *StoreView) Snapshot() common.Hash {
sv.store.Trie.Commit(nil) // Needs to commit to the in-memory trie DB
return sv.store.Hash()
}
func (sv *StoreView) Prune() error {
err := sv.store.Prune(func(node []byte) bool {
account := &types.Account{}
err := types.FromBytes(node, account)
if err != nil {
return false
}
if (account.Root == (common.Hash{})) || (account.Root == core.EmptyRootHash) {
return false
}
storage := sv.getAccountStorage(account)
logger.Debugf("StoreView.Prune, address: %v, account.root: %v", account.Address, account.Root.Hex())
err = storage.Prune(nil)
if err != nil {
logger.Errorf("Failed to prune storage for account %v", account)
return false
}
return true
})
if err != nil {
return fmt.Errorf("Failed to prune store view, %v", err)
}
return nil
}
func (sv *StoreView) AddLog(l *types.Log) {
sv.logs = append(sv.logs, l)
}