-
Notifications
You must be signed in to change notification settings - Fork 175
/
account_reporter.go
407 lines (350 loc) · 9.64 KB
/
account_reporter.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
package reporters
import (
"fmt"
goRuntime "runtime"
"sync"
"github.com/rs/zerolog"
"github.com/schollz/progressbar/v3"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/flow-go/engine/execution/state/delta"
"github.com/onflow/flow-go/fvm"
"github.com/onflow/flow-go/fvm/environment"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/ledger"
"github.com/onflow/flow-go/model/flow"
)
// AccountReporter iterates through registers keeping a map of register sizes
// reports on storage metrics
type AccountReporter struct {
Log zerolog.Logger
RWF ReportWriterFactory
Chain flow.Chain
}
var _ ledger.Reporter = &AccountReporter{}
func (r *AccountReporter) Name() string {
return "Account Reporter"
}
type accountRecord struct {
Address string `json:"address"`
StorageUsed uint64 `json:"storageUsed"`
AccountBalance uint64 `json:"accountBalance"`
FUSDBalance uint64 `json:"fusdBalance"`
HasVault bool `json:"hasVault"`
HasReceiver bool `json:"hasReceiver"`
IsDapper bool `json:"isDapper"`
}
type contractRecord struct {
Address string `json:"address"`
Contract string `json:"contract"`
}
type momentsRecord struct {
Address string `json:"address"`
Moments int `json:"moments"`
}
func (r *AccountReporter) Report(payload []ledger.Payload, commit ledger.State) error {
rwa := r.RWF.ReportWriter("account_report")
rwc := r.RWF.ReportWriter("contract_report")
rwm := r.RWF.ReportWriter("moments_report")
defer rwa.Close()
defer rwc.Close()
defer rwm.Close()
snapshot := NewStorageSnapshotFromPayload(payload)
workerCount := goRuntime.NumCPU() / 2
if workerCount == 0 {
workerCount = 1
}
addressIndexes := make(chan uint64, workerCount)
defer close(addressIndexes)
// create multiple workers to generate account data report concurrently
wg := &sync.WaitGroup{}
for i := 0; i < workerCount; i++ {
go func() {
adp := newAccountDataProcessor(
r.Log,
rwa,
rwc,
rwm,
r.Chain,
snapshot)
for indx := range addressIndexes {
adp.reportAccountData(indx)
wg.Done()
}
}()
}
txnState := state.NewTransactionState(
delta.NewDeltaView(snapshot),
state.DefaultParameters())
gen := environment.NewAddressGenerator(txnState, r.Chain)
addressCount := gen.AddressCount()
progress := progressbar.Default(int64(addressCount), "Processing:")
// produce jobs for workers to process
for i := uint64(1); i <= addressCount; i++ {
addressIndexes <- i
wg.Add(1)
err := progress.Add(1)
if err != nil {
panic(fmt.Errorf("progress.Add(1): %w", err))
}
}
// wait until all jobs are done
wg.Wait()
err := progress.Finish()
if err != nil {
panic(fmt.Errorf("progress.Finish(): %w", err))
}
return nil
}
type balanceProcessor struct {
vm fvm.VM
ctx fvm.Context
storageSnapshot state.StorageSnapshot
env environment.Environment
balanceScript []byte
momentsScript []byte
rwa ReportWriter
rwc ReportWriter
logger zerolog.Logger
rwm ReportWriter
fusdScript []byte
}
func NewBalanceReporter(
chain flow.Chain,
snapshot state.StorageSnapshot,
) *balanceProcessor {
vm := fvm.NewVirtualMachine()
ctx := fvm.NewContext(
fvm.WithChain(chain),
fvm.WithMemoryAndInteractionLimitsDisabled())
env := environment.NewScriptEnvironmentFromStorageSnapshot(
ctx.EnvironmentParams,
snapshot)
return &balanceProcessor{
vm: vm,
ctx: ctx,
storageSnapshot: snapshot,
env: env,
}
}
func newAccountDataProcessor(
logger zerolog.Logger,
rwa ReportWriter,
rwc ReportWriter,
rwm ReportWriter,
chain flow.Chain,
snapshot state.StorageSnapshot,
) *balanceProcessor {
bp := NewBalanceReporter(chain, snapshot)
bp.logger = logger
bp.rwa = rwa
bp.rwc = rwc
bp.rwm = rwm
bp.balanceScript = []byte(fmt.Sprintf(`
import FungibleToken from 0x%s
import FlowToken from 0x%s
pub fun main(account: Address): UFix64 {
let acct = getAccount(account)
let vaultRef = acct.getCapability(/public/flowTokenBalance)
.borrow<&FlowToken.Vault{FungibleToken.Balance}>()
?? panic("Could not borrow Balance reference to the Vault")
return vaultRef.balance
}
`, fvm.FungibleTokenAddress(bp.ctx.Chain), fvm.FlowTokenAddress(bp.ctx.Chain)))
bp.fusdScript = []byte(fmt.Sprintf(`
import FungibleToken from 0x%s
import FUSD from 0x%s
pub fun main(address: Address): UFix64 {
let account = getAccount(address)
let vaultRef = account.getCapability(/public/fusdBalance)!
.borrow<&FUSD.Vault{FungibleToken.Balance}>()
?? panic("Could not borrow Balance reference to the Vault")
return vaultRef.balance
}
`, fvm.FungibleTokenAddress(bp.ctx.Chain), "3c5959b568896393"))
bp.momentsScript = []byte(`
import TopShot from 0x0b2a3299cc857e29
pub fun main(account: Address): Int {
let acct = getAccount(account)
let collectionRef = acct.getCapability(/public/MomentCollection)
.borrow<&{TopShot.MomentCollectionPublic}>()!
return collectionRef.getIDs().length
}
`)
return bp
}
func (c *balanceProcessor) reportAccountData(indx uint64) {
address, err := c.ctx.Chain.AddressAtIndex(indx)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Msgf("Error getting address")
return
}
runtimeAddress := common.MustBytesToAddress(address.Bytes())
u, err := c.env.GetStorageUsed(runtimeAddress)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Str("address", address.String()).
Msgf("Error getting storage used for account")
return
}
balance, hasVault, err := c.balance(address)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Str("address", address.String()).
Msgf("Error getting balance for account")
return
}
fusdBalance, err := c.fusdBalance(address)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Str("address", address.String()).
Msgf("Error getting FUSD balance for account")
return
}
dapper, err := c.isDapper(address)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Str("address", address.String()).
Msgf("Error determining if account is dapper account")
return
}
if dapper {
m, err := c.moments(address)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Str("address", address.String()).
Msgf("Error getting moments for account")
return
}
c.rwm.Write(momentsRecord{
Address: address.Hex(),
Moments: m,
})
}
hasReceiver, err := c.hasReceiver(address)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Str("address", address.String()).
Msgf("Error checking if account has a receiver")
return
}
c.rwa.Write(accountRecord{
Address: address.Hex(),
StorageUsed: u,
AccountBalance: balance,
FUSDBalance: fusdBalance,
HasVault: hasVault,
HasReceiver: hasReceiver,
IsDapper: dapper,
})
contracts, err := c.env.GetAccountContractNames(runtimeAddress)
if err != nil {
c.logger.
Err(err).
Uint64("index", indx).
Str("address", address.String()).
Msgf("Error getting account contract names")
return
}
if len(contracts) == 0 {
return
}
for _, contract := range contracts {
c.rwc.Write(contractRecord{
Address: address.Hex(),
Contract: contract,
})
}
}
func (c *balanceProcessor) balance(address flow.Address) (uint64, bool, error) {
script := fvm.Script(c.balanceScript).WithArguments(
jsoncdc.MustEncode(cadence.NewAddress(address)),
)
_, output, err := c.vm.RunV2(c.ctx, script, c.storageSnapshot)
if err != nil {
return 0, false, err
}
var balance uint64
var hasVault bool
if output.Err == nil && output.Value != nil {
balance = output.Value.ToGoValue().(uint64)
hasVault = true
} else {
hasVault = false
}
return balance, hasVault, nil
}
func (c *balanceProcessor) fusdBalance(address flow.Address) (uint64, error) {
script := fvm.Script(c.fusdScript).WithArguments(
jsoncdc.MustEncode(cadence.NewAddress(address)),
)
_, output, err := c.vm.RunV2(c.ctx, script, c.storageSnapshot)
if err != nil {
return 0, err
}
var balance uint64
if output.Err == nil && output.Value != nil {
balance = output.Value.ToGoValue().(uint64)
}
return balance, nil
}
func (c *balanceProcessor) moments(address flow.Address) (int, error) {
script := fvm.Script(c.momentsScript).WithArguments(
jsoncdc.MustEncode(cadence.NewAddress(address)),
)
_, output, err := c.vm.RunV2(c.ctx, script, c.storageSnapshot)
if err != nil {
return 0, err
}
var m int
if output.Err == nil && output.Value != nil {
m = output.Value.(cadence.Int).Int()
}
return m, nil
}
func (c *balanceProcessor) isDapper(address flow.Address) (bool, error) {
receiver, err := c.ReadStored(address, common.PathDomainPublic, "dapperUtilityCoinReceiver")
if err != nil {
return false, fmt.Errorf("could not load dapper receiver at %s: %w", address, err)
}
return receiver != nil, nil
}
func (c *balanceProcessor) hasReceiver(address flow.Address) (bool, error) {
receiver, err := c.ReadStored(address, common.PathDomainPublic, "flowTokenReceiver")
if err != nil {
return false, fmt.Errorf("could not load receiver at %s: %w", address, err)
}
return receiver != nil, nil
}
func (c *balanceProcessor) ReadStored(address flow.Address, domain common.PathDomain, id string) (cadence.Value, error) {
addr, err := common.BytesToAddress(address.Bytes())
if err != nil {
return nil, err
}
rt := c.env.BorrowCadenceRuntime()
defer c.env.ReturnCadenceRuntime(rt)
receiver, err := rt.ReadStored(
addr,
cadence.Path{
Domain: domain.Identifier(),
Identifier: id,
},
)
return receiver, err
}