-
Notifications
You must be signed in to change notification settings - Fork 4
/
local_simulation.go
703 lines (623 loc) · 18.8 KB
/
local_simulation.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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
package transaction_v2
import (
"context"
"errors"
transactionpb "github.com/code-payments/code-protobuf-api/generated/go/transaction/v2"
"github.com/code-payments/code-server/pkg/code/balance"
"github.com/code-payments/code-server/pkg/code/common"
code_data "github.com/code-payments/code-server/pkg/code/data"
"github.com/code-payments/code-server/pkg/code/data/timelock"
timelock_token_v1 "github.com/code-payments/code-server/pkg/solana/timelock/v1"
)
type LocalSimulationResult struct {
SimulationsByAccount map[string]TokenAccountSimulation
}
type TokenAccountSimulation struct {
TokenAccount *common.Account
Transfers []TransferSimulation
Opened bool
OpenAction *transactionpb.Action
// todo: We need to handle CloseDormantAccount actions better. They're closed later,
// but there's no indication here in simulation that we could close it at our
// discretion.
Closed bool
CloseAction *transactionpb.Action
}
// todo: Make it easier to extract accounts from a TransferSimulation (see some fee payment validation logic)
type TransferSimulation struct {
Action *transactionpb.Action
IsPrivate bool
IsWithdraw bool
IsFee bool
DeltaQuarks int64
}
// LocalSimulation simulates actions as if they were executed on the blockchain
// taking into account cached Code DB state.
//
// Note: This doesn't currently incoporate accounts being closed by us. This is
// fine because we only close temporary accounts during rotation. We already have
// good validation for this, so it's fine for now.
func LocalSimulation(ctx context.Context, data code_data.Provider, actions []*transactionpb.Action) (*LocalSimulationResult, error) {
result := &LocalSimulationResult{
SimulationsByAccount: make(map[string]TokenAccountSimulation),
}
for _, action := range actions {
var authority, derivedTimelockVault *common.Account
var simulations []TokenAccountSimulation
var err error
// Simulate the action
switch typedAction := action.Type.(type) {
case *transactionpb.Action_OpenAccount:
opened, err := common.NewAccountFromProto(typedAction.OpenAccount.Token)
if err != nil {
return nil, err
}
derivedTimelockVault = opened
authority, err = common.NewAccountFromProto(typedAction.OpenAccount.Authority)
if err != nil {
return nil, err
}
timelockRecord, err := data.GetTimelockByVault(ctx, opened.PublicKey().ToBase58())
if err == nil {
// Generally, real clients will have stale state, but it's entirely possible
// that a malicious client is attempting to invoke a failed fufillment.
//
// todo: We don't support reopening accounts yet
if timelockRecord.IsClosed() {
return nil, newActionWithStaleStateError(action, "account is already closed and won't be reused")
}
return nil, newActionWithStaleStateError(action, "account is already opened")
} else if err != nil && err != timelock.ErrTimelockNotFound {
return nil, err
}
simulations = append(
simulations,
TokenAccountSimulation{
TokenAccount: opened,
Opened: true,
OpenAction: action,
},
)
case *transactionpb.Action_CloseEmptyAccount:
closed, err := common.NewAccountFromProto(typedAction.CloseEmptyAccount.Token)
if err != nil {
return nil, err
}
derivedTimelockVault = closed
authority, err = common.NewAccountFromProto(typedAction.CloseEmptyAccount.Authority)
if err != nil {
return nil, err
}
simulations = append(
simulations,
TokenAccountSimulation{
TokenAccount: closed,
Closed: true,
CloseAction: action,
},
)
case *transactionpb.Action_CloseDormantAccount:
derivedTimelockVault, err = common.NewAccountFromProto(typedAction.CloseDormantAccount.Token)
if err != nil {
return nil, err
}
authority, err = common.NewAccountFromProto(typedAction.CloseDormantAccount.Authority)
if err != nil {
return nil, err
}
case *transactionpb.Action_NoPrivacyTransfer:
source, err := common.NewAccountFromProto(typedAction.NoPrivacyTransfer.Source)
if err != nil {
return nil, err
}
derivedTimelockVault = source
authority, err = common.NewAccountFromProto(typedAction.NoPrivacyTransfer.Authority)
if err != nil {
return nil, err
}
destination, err := common.NewAccountFromProto(typedAction.NoPrivacyTransfer.Destination)
if err != nil {
return nil, err
}
amount := typedAction.NoPrivacyTransfer.Amount
simulations = append(
simulations,
TokenAccountSimulation{
TokenAccount: source,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: false,
IsWithdraw: false,
IsFee: false,
DeltaQuarks: -int64(amount),
},
},
},
TokenAccountSimulation{
TokenAccount: destination,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: false,
IsWithdraw: false,
IsFee: false,
DeltaQuarks: int64(amount),
},
},
},
)
case *transactionpb.Action_FeePayment:
source, err := common.NewAccountFromProto(typedAction.FeePayment.Source)
if err != nil {
return nil, err
}
derivedTimelockVault = source
authority, err = common.NewAccountFromProto(typedAction.FeePayment.Authority)
if err != nil {
return nil, err
}
amount := typedAction.FeePayment.Amount
simulations = append(
simulations,
TokenAccountSimulation{
TokenAccount: source,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: false,
IsWithdraw: false,
IsFee: true,
DeltaQuarks: -int64(amount),
},
},
},
// todo: Doesn't specify destination, but that's not required yet,
// and makes other validation more complex since it's based
// on the simulation.
)
case *transactionpb.Action_NoPrivacyWithdraw:
source, err := common.NewAccountFromProto(typedAction.NoPrivacyWithdraw.Source)
if err != nil {
return nil, err
}
derivedTimelockVault = source
authority, err = common.NewAccountFromProto(typedAction.NoPrivacyWithdraw.Authority)
if err != nil {
return nil, err
}
destination, err := common.NewAccountFromProto(typedAction.NoPrivacyWithdraw.Destination)
if err != nil {
return nil, err
}
amount := typedAction.NoPrivacyWithdraw.Amount
if source.PublicKey().ToBase58() == destination.PublicKey().ToBase58() {
return nil, newActionValidationError(action, "source and destination accounts must be different")
}
simulations = append(
simulations,
TokenAccountSimulation{
TokenAccount: source,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: false,
IsWithdraw: true,
IsFee: false,
DeltaQuarks: -int64(amount),
},
},
Closed: true,
CloseAction: action,
},
TokenAccountSimulation{
TokenAccount: destination,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: false,
IsWithdraw: true,
IsFee: false,
DeltaQuarks: int64(amount),
},
},
},
)
case *transactionpb.Action_TemporaryPrivacyTransfer:
source, err := common.NewAccountFromProto(typedAction.TemporaryPrivacyTransfer.Source)
if err != nil {
return nil, err
}
derivedTimelockVault = source
authority, err = common.NewAccountFromProto(typedAction.TemporaryPrivacyTransfer.Authority)
if err != nil {
return nil, err
}
destination, err := common.NewAccountFromProto(typedAction.TemporaryPrivacyTransfer.Destination)
if err != nil {
return nil, err
}
amount := typedAction.TemporaryPrivacyTransfer.Amount
simulations = append(
simulations,
TokenAccountSimulation{
TokenAccount: source,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: true,
IsWithdraw: false,
IsFee: false,
DeltaQuarks: -int64(amount),
},
},
},
TokenAccountSimulation{
TokenAccount: destination,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: true,
IsWithdraw: false,
IsFee: false,
DeltaQuarks: int64(amount),
},
},
},
)
case *transactionpb.Action_TemporaryPrivacyExchange:
source, err := common.NewAccountFromProto(typedAction.TemporaryPrivacyExchange.Source)
if err != nil {
return nil, err
}
derivedTimelockVault = source
authority, err = common.NewAccountFromProto(typedAction.TemporaryPrivacyExchange.Authority)
if err != nil {
return nil, err
}
destination, err := common.NewAccountFromProto(typedAction.TemporaryPrivacyExchange.Destination)
if err != nil {
return nil, err
}
amount := typedAction.TemporaryPrivacyExchange.Amount
simulations = append(
simulations,
TokenAccountSimulation{
TokenAccount: source,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: true,
IsWithdraw: false,
IsFee: false,
DeltaQuarks: -int64(amount),
},
},
},
TokenAccountSimulation{
TokenAccount: destination,
Transfers: []TransferSimulation{
{
Action: action,
IsPrivate: true,
IsWithdraw: false,
IsFee: false,
DeltaQuarks: int64(amount),
},
},
},
)
case *transactionpb.Action_PermanentPrivacyUpgrade:
continue
default:
return nil, errors.New("unhandled action for local simulation")
}
// Validate authorities and respective derived timelock vault accounts match.
timelockAccounts, err := authority.GetTimelockAccounts(timelock_token_v1.DataVersion1, common.KinMintAccount)
if err != nil {
return nil, err
}
if timelockAccounts.Vault.PublicKey().ToBase58() != derivedTimelockVault.PublicKey().ToBase58() {
return nil, newActionValidationErrorf(action, "token must be %s", timelockAccounts.Vault.PublicKey().ToBase58())
}
// Combine the simulated action to all previously simulated actions with
// some basic level of validation.
for _, simulation := range simulations {
for _, txn := range simulation.Transfers {
// Attempt to transfer 0 Kin
if txn.DeltaQuarks == 0 {
return nil, newActionValidationError(action, "transaction with 0 quarks")
}
}
combined, ok := result.SimulationsByAccount[simulation.TokenAccount.PublicKey().ToBase58()]
if ok {
// Attempt to open an already closed account, which isn't supported
if combined.Closed && simulation.Opened {
return nil, newActionValidationError(action, "account cannot be reopened")
}
// Attempt to open an already opened account
if combined.Opened && simulation.Opened {
return nil, newActionValidationError(action, "account is already opened in another action")
}
// Funds transferred to an account before it was opened
if len(combined.Transfers) > 0 && simulation.Opened {
return nil, newActionValidationError(action, "opened an account after transferring funds to it")
}
// Attempt to close an already closed account
if combined.Closed && simulation.Closed {
return nil, newActionValidationError(action, "account is already closed in another action")
}
// Attempt to send/receive Kin to a closed account
if combined.Closed && len(simulation.Transfers) > 0 {
return nil, newActionValidationError(action, "account is closed and cannot send/receive kin")
}
combined.Transfers = append(combined.Transfers, simulation.Transfers...)
combined.Opened = combined.Opened || simulation.Opened
if simulation.Opened {
combined.OpenAction = simulation.OpenAction
}
combined.Closed = combined.Closed || simulation.Closed
if simulation.Closed {
combined.CloseAction = simulation.CloseAction
}
} else {
combined = simulation
}
result.SimulationsByAccount[simulation.TokenAccount.PublicKey().ToBase58()] = combined
}
}
// Optimally prefetch all required balances in a single batch
var err error
var tokenAccountsToFetchBalance []*common.Account
for _, sim := range result.SimulationsByAccount {
if sim.RequiresBalanceFetch() {
tokenAccountsToFetchBalance = append(tokenAccountsToFetchBalance, sim.TokenAccount)
}
}
prefetchedBalances := make(map[string]uint64)
if len(tokenAccountsToFetchBalance) > 0 {
prefetchedBalances, err = balance.BatchCalculateFromCacheWithTokenAccounts(ctx, data, tokenAccountsToFetchBalance...)
if err == balance.ErrNotManagedByCode {
return nil, ErrNotManagedByCode
} else if err != nil {
return nil, err
}
}
// Do more complex simulation validation on each involved account using all combined actions
for _, sim := range result.SimulationsByAccount {
if !sim.RequiresBalanceCheck() {
continue
}
var ok bool
var balance uint64
if sim.RequiresBalanceFetch() {
balance, ok = prefetchedBalances[sim.TokenAccount.PublicKey().ToBase58()]
if !ok {
return nil, errors.New("prefetched balance is unavailable")
}
}
err := sim.EnforceBalances(ctx, data, balance)
if err != nil {
return nil, err
}
}
return result, nil
}
func (s TokenAccountSimulation) EnforceBalances(ctx context.Context, data code_data.Provider, currentBalance uint64) error {
// There's no value to doing a balance check if there's no operation that
// requires a specific balance value
if !s.RequiresBalanceCheck() {
return nil
}
// Ensure all transfers have sufficient balance
newBalance := int64(currentBalance)
for _, transfer := range s.Transfers {
newBalance = newBalance + transfer.DeltaQuarks
if newBalance < 0 {
return newActionValidationError(transfer.Action, "insufficient balance to perform action")
}
// If it's withdrawn out of this account, remove any remaining balance.
// Do this only after applying the expected DeltaQuarks and validating
// sufficient funds as a safety precaution.
if transfer.IsWithdraw && transfer.DeltaQuarks < 0 {
newBalance = 0
}
}
if s.Closed && newBalance != 0 {
return newActionValidationError(s.CloseAction, "attempt to close an account with a non-zero balance")
}
return nil
}
func (s TokenAccountSimulation) RequiresBalanceCheck() bool {
return s.HasOutgoingTransfer() || s.Closed
}
func (s TokenAccountSimulation) RequiresBalanceFetch() bool {
return s.RequiresBalanceCheck() && !s.Opened
}
func (s LocalSimulationResult) GetOpenedAccounts() []TokenAccountSimulation {
var simulations []TokenAccountSimulation
for _, simulation := range s.SimulationsByAccount {
if simulation.Opened {
simulations = append(simulations, simulation)
}
}
return simulations
}
func (s LocalSimulationResult) GetClosedAccounts() []TokenAccountSimulation {
var simulations []TokenAccountSimulation
for _, simulation := range s.SimulationsByAccount {
if simulation.Closed {
simulations = append(simulations, simulation)
}
}
return simulations
}
func (s TokenAccountSimulation) GetDeltaQuarks() int64 {
var res int64
for _, txn := range s.Transfers {
res += txn.DeltaQuarks
}
return res
}
func (s TokenAccountSimulation) GetIncomingTransfers() []TransferSimulation {
var transfers []TransferSimulation
for _, transfer := range s.Transfers {
if transfer.DeltaQuarks > 0 {
transfers = append(transfers, transfer)
}
}
return transfers
}
func (s TokenAccountSimulation) GetOutgoingTransfers() []TransferSimulation {
var transfers []TransferSimulation
for _, transfer := range s.Transfers {
if transfer.DeltaQuarks < 0 {
transfers = append(transfers, transfer)
}
}
return transfers
}
func (s TokenAccountSimulation) GetPublicTransfers() []TransferSimulation {
var transfers []TransferSimulation
for _, transfer := range s.Transfers {
if !transfer.IsPrivate {
transfers = append(transfers, transfer)
}
}
return transfers
}
func (s TokenAccountSimulation) GetPrivateTransfers() []TransferSimulation {
var transfers []TransferSimulation
for _, transfer := range s.Transfers {
if transfer.IsPrivate {
transfers = append(transfers, transfer)
}
}
return transfers
}
func (s TokenAccountSimulation) GetWithdraws() []TransferSimulation {
var transfers []TransferSimulation
for _, transfer := range s.Transfers {
if transfer.IsWithdraw {
transfers = append(transfers, transfer)
}
}
return transfers
}
func (s LocalSimulationResult) GetFeePayments() []TransferSimulation {
var transfers []TransferSimulation
for _, tokenAccountSimulation := range s.SimulationsByAccount {
for _, transfer := range tokenAccountSimulation.Transfers {
if transfer.IsFee {
transfers = append(transfers, transfer)
}
}
}
return transfers
}
func (s TokenAccountSimulation) HasAnyPrivateTransfers() bool {
for _, transfer := range s.Transfers {
if transfer.IsPrivate {
return true
}
}
return false
}
func (s TokenAccountSimulation) HasAnyPublicTransfers() bool {
for _, transfer := range s.Transfers {
if !transfer.IsPrivate {
return true
}
}
return false
}
func (s TokenAccountSimulation) HasAnyWithdraws() bool {
for _, transfer := range s.Transfers {
if transfer.IsWithdraw {
return true
}
}
return false
}
func (s TokenAccountSimulation) HasIncomingTransfer() bool {
for _, transfer := range s.Transfers {
if transfer.DeltaQuarks > 0 {
return true
}
}
return false
}
func (s TokenAccountSimulation) HasOutgoingTransfer() bool {
for _, transfer := range s.Transfers {
if transfer.DeltaQuarks < 0 {
return true
}
}
return false
}
func (s LocalSimulationResult) HasAnyFeePayments() bool {
for _, tokenAccountSimulation := range s.SimulationsByAccount {
for _, transfer := range tokenAccountSimulation.Transfers {
if transfer.IsFee {
return true
}
}
}
return false
}
func (s TokenAccountSimulation) CountPrivateTransfers() int {
var count int
for _, transfer := range s.Transfers {
if !transfer.IsPrivate {
count++
}
}
return count
}
func (s TokenAccountSimulation) CountPublicTransfers() int {
var count int
for _, transfer := range s.Transfers {
if !transfer.IsPrivate {
count++
}
}
return count
}
func (s TokenAccountSimulation) CountIncomingTransfers() int {
var count int
for _, transfer := range s.Transfers {
if transfer.DeltaQuarks > 0 {
count++
}
}
return count
}
func (s TokenAccountSimulation) CountOutgoingTransfers() int {
var count int
for _, transfer := range s.Transfers {
if transfer.DeltaQuarks < 0 {
count++
}
}
return count
}
func (s TokenAccountSimulation) CountWithdrawals() int {
var count int
for _, transfer := range s.Transfers {
if transfer.IsWithdraw {
count++
}
}
return count
}
func (s LocalSimulationResult) CountFeePayments() int {
var count int
for _, tokenAccountSimulation := range s.SimulationsByAccount {
for _, transfer := range tokenAccountSimulation.Transfers {
if transfer.IsFee {
count++
}
}
}
return count
}