-
Notifications
You must be signed in to change notification settings - Fork 175
/
account_migration.go
99 lines (80 loc) · 2.52 KB
/
account_migration.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
package migrations
import (
"fmt"
"github.com/rs/zerolog/log"
"github.com/onflow/flow-go/fvm/environment"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/ledger"
)
func MigrateAccountUsage(payloads []ledger.Payload, nWorker int) ([]ledger.Payload, error) {
return MigrateByAccount(AccountUsageMigrator{}, payloads, nWorker)
}
func payloadSize(key ledger.Key, payload ledger.Payload) (uint64, error) {
id, err := KeyToRegisterID(key)
if err != nil {
return 0, err
}
return uint64(registerSize(id, payload)), nil
}
func isAccountKey(key ledger.Key) bool {
return string(key.KeyParts[1].Value) == state.AccountStatusKey
}
type AccountUsageMigrator struct{}
// AccountUsageMigrator iterate through each payload, and calculate the storage usage
// and update the accoutns status with the updated storage usage
func (m AccountUsageMigrator) MigratePayloads(account string, payloads []ledger.Payload) ([]ledger.Payload, error) {
var status *environment.AccountStatus
var statusIndex int
totalSize := uint64(0)
for i, payload := range payloads {
key, err := payload.Key()
if err != nil {
return nil, err
}
if isAccountKey(key) {
statusIndex = i
status, err = environment.AccountStatusFromBytes(payload.Value())
if err != nil {
return nil, fmt.Errorf("could not parse account status: %w", err)
}
}
size, err := payloadSize(key, payload)
if err != nil {
return nil, err
}
totalSize += size
}
err := compareUsage(status, totalSize)
if err != nil {
log.Error().Msgf("%v", err)
}
if status == nil {
return nil, fmt.Errorf("could not find account status for account %v", account)
}
// update storage used
status.SetStorageUsed(totalSize)
newValue := status.ToBytes()
newPayload, err := newPayloadWithValue(payloads[statusIndex], newValue)
if err != nil {
return nil, fmt.Errorf("cannot create new payload with value: %w", err)
}
payloads[statusIndex] = newPayload
return payloads, nil
}
func compareUsage(status *environment.AccountStatus, totalSize uint64) error {
oldSize := status.StorageUsed()
if oldSize != totalSize {
return fmt.Errorf("old size: %v, new size: %v", oldSize, totalSize)
}
return nil
}
// newPayloadWithValue returns a new payload with the key from the given payload, and
// the value from the argument
func newPayloadWithValue(payload ledger.Payload, value ledger.Value) (ledger.Payload, error) {
key, err := payload.Key()
if err != nil {
return ledger.Payload{}, err
}
newPayload := ledger.NewPayload(key, payload.Value())
return *newPayload, nil
}