-
Notifications
You must be signed in to change notification settings - Fork 178
/
transactionStorageLimiter.go
90 lines (74 loc) · 2.21 KB
/
transactionStorageLimiter.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
package fvm
import (
"fmt"
"github.com/onflow/cadence/runtime/common"
errors "github.com/onflow/flow-go/fvm/errors"
"github.com/onflow/flow-go/fvm/programs"
"github.com/onflow/flow-go/fvm/state"
)
type TransactionStorageLimiter struct {
// A function to create a function to get storage capacity from an address. This is to make this easily testable.
GetStorageCapacityFuncFactory func(
vm *VirtualMachine,
ctx Context,
tp *TransactionProcedure,
sth *state.StateHolder,
programs *programs.Programs,
) (func(address common.Address) (value uint64, err error), error)
}
func getStorageCapacityFuncFactory(
vm *VirtualMachine,
ctx Context,
_ *TransactionProcedure,
sth *state.StateHolder,
programs *programs.Programs,
) (func(address common.Address) (value uint64, err error), error) {
env := newEnvironment(ctx, vm, sth, programs)
return func(address common.Address) (value uint64, err error) {
return env.GetStorageCapacity(common.BytesToAddress(address.Bytes()))
}, nil
}
func NewTransactionStorageLimiter() *TransactionStorageLimiter {
return &TransactionStorageLimiter{
GetStorageCapacityFuncFactory: getStorageCapacityFuncFactory,
}
}
func (d *TransactionStorageLimiter) Process(
vm *VirtualMachine,
ctx *Context,
tp *TransactionProcedure,
sth *state.StateHolder,
programs *programs.Programs,
) error {
if !ctx.LimitAccountStorage {
return nil
}
getCapacity, err := d.GetStorageCapacityFuncFactory(vm, *ctx, tp, sth, programs)
if err != nil {
return fmt.Errorf("storage limit check failed: %w", err)
}
accounts := state.NewAccounts(sth)
addresses := sth.State().UpdatedAddresses()
for _, address := range addresses {
// does it exist?
exists, err := accounts.Exists(address)
if err != nil {
return fmt.Errorf("storage limit check failed: %w", err)
}
if !exists {
continue
}
capacity, err := getCapacity(common.BytesToAddress(address.Bytes()))
if err != nil {
return fmt.Errorf("storage limit check failed: %w", err)
}
usage, err := accounts.GetStorageUsed(address)
if err != nil {
return fmt.Errorf("storage limit check failed: %w", err)
}
if usage > capacity {
return errors.NewStorageCapacityExceededError(address, usage, capacity)
}
}
return nil
}