-
Notifications
You must be signed in to change notification settings - Fork 660
/
proposal_tx_executor.go
670 lines (577 loc) · 18.3 KB
/
proposal_tx_executor.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
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package executor
import (
"errors"
"fmt"
"time"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/math"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/components/verify"
"github.com/ava-labs/avalanchego/vms/platformvm/reward"
"github.com/ava-labs/avalanchego/vms/platformvm/state"
"github.com/ava-labs/avalanchego/vms/platformvm/txs"
)
const (
// Maximum future start time for staking/delegating
MaxFutureStartTime = 24 * 7 * 2 * time.Hour
// SyncBound is the synchrony bound used for safe decision making
SyncBound = 10 * time.Second
MaxValidatorWeightFactor = 5
)
var (
_ txs.Visitor = (*ProposalTxExecutor)(nil)
ErrRemoveStakerTooEarly = errors.New("attempting to remove staker before their end time")
ErrRemoveWrongStaker = errors.New("attempting to remove wrong staker")
ErrChildBlockNotAfterParent = errors.New("proposed timestamp not after current chain time")
ErrInvalidState = errors.New("generated output isn't valid state")
ErrShouldBePermissionlessStaker = errors.New("expected permissionless staker")
ErrWrongTxType = errors.New("wrong transaction type")
ErrInvalidID = errors.New("invalid ID")
ErrProposedAddStakerTxAfterBanff = errors.New("staker transaction proposed after Banff")
ErrAdvanceTimeTxIssuedAfterBanff = errors.New("AdvanceTimeTx issued after Banff")
)
type ProposalTxExecutor struct {
// inputs, to be filled before visitor methods are called
*Backend
Tx *txs.Tx
// [OnCommitState] is the state used for validation.
// [OnCommitState] is modified by this struct's methods to
// reflect changes made to the state if the proposal is committed.
//
// Invariant: Both [OnCommitState] and [OnAbortState] represent the same
// state when provided to this struct.
OnCommitState state.Diff
// [OnAbortState] is modified by this struct's methods to
// reflect changes made to the state if the proposal is aborted.
OnAbortState state.Diff
// outputs populated by this struct's methods:
//
// [PrefersCommit] is true iff this node initially prefers to
// commit this block transaction.
PrefersCommit bool
}
func (*ProposalTxExecutor) CreateChainTx(*txs.CreateChainTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) CreateSubnetTx(*txs.CreateSubnetTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) ImportTx(*txs.ImportTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) ExportTx(*txs.ExportTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) RemoveSubnetValidatorTx(*txs.RemoveSubnetValidatorTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) TransformSubnetTx(*txs.TransformSubnetTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) AddPermissionlessValidatorTx(*txs.AddPermissionlessValidatorTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) AddPermissionlessDelegatorTx(*txs.AddPermissionlessDelegatorTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) TransferSubnetOwnershipTx(*txs.TransferSubnetOwnershipTx) error {
return ErrWrongTxType
}
func (*ProposalTxExecutor) BaseTx(*txs.BaseTx) error {
return ErrWrongTxType
}
func (e *ProposalTxExecutor) AddValidatorTx(tx *txs.AddValidatorTx) error {
// AddValidatorTx is a proposal transaction until the Banff fork
// activation. Following the activation, AddValidatorTxs must be issued into
// StandardBlocks.
currentTimestamp := e.OnCommitState.GetTimestamp()
if e.Config.IsBanffActivated(currentTimestamp) {
return fmt.Errorf(
"%w: timestamp (%s) >= Banff fork time (%s)",
ErrProposedAddStakerTxAfterBanff,
currentTimestamp,
e.Config.BanffTime,
)
}
onAbortOuts, err := verifyAddValidatorTx(
e.Backend,
e.OnCommitState,
e.Tx,
tx,
)
if err != nil {
return err
}
txID := e.Tx.ID()
// Set up the state if this tx is committed
// Consume the UTXOs
avax.Consume(e.OnCommitState, tx.Ins)
// Produce the UTXOs
avax.Produce(e.OnCommitState, txID, tx.Outs)
newStaker, err := state.NewPendingStaker(txID, tx)
if err != nil {
return err
}
e.OnCommitState.PutPendingValidator(newStaker)
// Set up the state if this tx is aborted
// Consume the UTXOs
avax.Consume(e.OnAbortState, tx.Ins)
// Produce the UTXOs
avax.Produce(e.OnAbortState, txID, onAbortOuts)
e.PrefersCommit = tx.StartTime().After(e.Clk.Time())
return nil
}
func (e *ProposalTxExecutor) AddSubnetValidatorTx(tx *txs.AddSubnetValidatorTx) error {
// AddSubnetValidatorTx is a proposal transaction until the Banff fork
// activation. Following the activation, AddSubnetValidatorTxs must be
// issued into StandardBlocks.
currentTimestamp := e.OnCommitState.GetTimestamp()
if e.Config.IsBanffActivated(currentTimestamp) {
return fmt.Errorf(
"%w: timestamp (%s) >= Banff fork time (%s)",
ErrProposedAddStakerTxAfterBanff,
currentTimestamp,
e.Config.BanffTime,
)
}
if err := verifyAddSubnetValidatorTx(
e.Backend,
e.OnCommitState,
e.Tx,
tx,
); err != nil {
return err
}
txID := e.Tx.ID()
// Set up the state if this tx is committed
// Consume the UTXOs
avax.Consume(e.OnCommitState, tx.Ins)
// Produce the UTXOs
avax.Produce(e.OnCommitState, txID, tx.Outs)
newStaker, err := state.NewPendingStaker(txID, tx)
if err != nil {
return err
}
e.OnCommitState.PutPendingValidator(newStaker)
// Set up the state if this tx is aborted
// Consume the UTXOs
avax.Consume(e.OnAbortState, tx.Ins)
// Produce the UTXOs
avax.Produce(e.OnAbortState, txID, tx.Outs)
e.PrefersCommit = tx.StartTime().After(e.Clk.Time())
return nil
}
func (e *ProposalTxExecutor) AddDelegatorTx(tx *txs.AddDelegatorTx) error {
// AddDelegatorTx is a proposal transaction until the Banff fork
// activation. Following the activation, AddDelegatorTxs must be issued into
// StandardBlocks.
currentTimestamp := e.OnCommitState.GetTimestamp()
if e.Config.IsBanffActivated(currentTimestamp) {
return fmt.Errorf(
"%w: timestamp (%s) >= Banff fork time (%s)",
ErrProposedAddStakerTxAfterBanff,
currentTimestamp,
e.Config.BanffTime,
)
}
onAbortOuts, err := verifyAddDelegatorTx(
e.Backend,
e.OnCommitState,
e.Tx,
tx,
)
if err != nil {
return err
}
txID := e.Tx.ID()
// Set up the state if this tx is committed
// Consume the UTXOs
avax.Consume(e.OnCommitState, tx.Ins)
// Produce the UTXOs
avax.Produce(e.OnCommitState, txID, tx.Outs)
newStaker, err := state.NewPendingStaker(txID, tx)
if err != nil {
return err
}
e.OnCommitState.PutPendingDelegator(newStaker)
// Set up the state if this tx is aborted
// Consume the UTXOs
avax.Consume(e.OnAbortState, tx.Ins)
// Produce the UTXOs
avax.Produce(e.OnAbortState, txID, onAbortOuts)
e.PrefersCommit = tx.StartTime().After(e.Clk.Time())
return nil
}
func (e *ProposalTxExecutor) AdvanceTimeTx(tx *txs.AdvanceTimeTx) error {
switch {
case tx == nil:
return txs.ErrNilTx
case len(e.Tx.Creds) != 0:
return errWrongNumberOfCredentials
}
// Validate [newChainTime]
newChainTime := tx.Timestamp()
if e.Config.IsBanffActivated(newChainTime) {
return fmt.Errorf(
"%w: proposed timestamp (%s) >= Banff fork time (%s)",
ErrAdvanceTimeTxIssuedAfterBanff,
newChainTime,
e.Config.BanffTime,
)
}
parentChainTime := e.OnCommitState.GetTimestamp()
if !newChainTime.After(parentChainTime) {
return fmt.Errorf(
"%w, proposed timestamp (%s), chain time (%s)",
ErrChildBlockNotAfterParent,
parentChainTime,
parentChainTime,
)
}
// Only allow timestamp to move forward as far as the time of next staker
// set change time
nextStakerChangeTime, err := GetNextStakerChangeTime(e.OnCommitState)
if err != nil {
return err
}
now := e.Clk.Time()
if err := VerifyNewChainTime(
newChainTime,
nextStakerChangeTime,
now,
); err != nil {
return err
}
changes, err := AdvanceTimeTo(e.Backend, e.OnCommitState, newChainTime)
if err != nil {
return err
}
// Update the state if this tx is committed
e.OnCommitState.SetTimestamp(newChainTime)
changes.Apply(e.OnCommitState)
e.PrefersCommit = !newChainTime.After(now.Add(SyncBound))
// Note that state doesn't change if this proposal is aborted
return nil
}
func (e *ProposalTxExecutor) RewardValidatorTx(tx *txs.RewardValidatorTx) error {
switch {
case tx == nil:
return txs.ErrNilTx
case tx.TxID == ids.Empty:
return ErrInvalidID
case len(e.Tx.Creds) != 0:
return errWrongNumberOfCredentials
}
currentStakerIterator, err := e.OnCommitState.GetCurrentStakerIterator()
if err != nil {
return err
}
if !currentStakerIterator.Next() {
return fmt.Errorf("failed to get next staker to remove: %w", database.ErrNotFound)
}
stakerToReward := currentStakerIterator.Value()
currentStakerIterator.Release()
if stakerToReward.TxID != tx.TxID {
return fmt.Errorf(
"%w: %s != %s",
ErrRemoveWrongStaker,
stakerToReward.TxID,
tx.TxID,
)
}
// Verify that the chain's timestamp is the validator's end time
currentChainTime := e.OnCommitState.GetTimestamp()
if !stakerToReward.EndTime.Equal(currentChainTime) {
return fmt.Errorf(
"%w: TxID = %s with %s < %s",
ErrRemoveStakerTooEarly,
tx.TxID,
currentChainTime,
stakerToReward.EndTime,
)
}
// retrieve primaryNetworkValidator before possibly removing it.
primaryNetworkValidator, err := e.OnCommitState.GetCurrentValidator(
constants.PrimaryNetworkID,
stakerToReward.NodeID,
)
if err != nil {
// This should never error because the staker set is in memory and
// primary network validators are removed last.
return err
}
stakerTx, _, err := e.OnCommitState.GetTx(stakerToReward.TxID)
if err != nil {
return fmt.Errorf("failed to get next removed staker tx: %w", err)
}
// Invariant: A [txs.DelegatorTx] does not also implement the
// [txs.ValidatorTx] interface.
switch uStakerTx := stakerTx.Unsigned.(type) {
case txs.ValidatorTx:
if err := e.rewardValidatorTx(uStakerTx, stakerToReward); err != nil {
return err
}
// Handle staker lifecycle.
e.OnCommitState.DeleteCurrentValidator(stakerToReward)
e.OnAbortState.DeleteCurrentValidator(stakerToReward)
case txs.DelegatorTx:
if err := e.rewardDelegatorTx(uStakerTx, stakerToReward); err != nil {
return err
}
// Handle staker lifecycle.
e.OnCommitState.DeleteCurrentDelegator(stakerToReward)
e.OnAbortState.DeleteCurrentDelegator(stakerToReward)
default:
// Invariant: Permissioned stakers are removed by the advancement of
// time and the current chain timestamp is == this staker's
// EndTime. This means only permissionless stakers should be
// left in the staker set.
return ErrShouldBePermissionlessStaker
}
// If the reward is aborted, then the current supply should be decreased.
currentSupply, err := e.OnAbortState.GetCurrentSupply(stakerToReward.SubnetID)
if err != nil {
return err
}
newSupply, err := math.Sub(currentSupply, stakerToReward.PotentialReward)
if err != nil {
return err
}
e.OnAbortState.SetCurrentSupply(stakerToReward.SubnetID, newSupply)
// handle option preference
e.PrefersCommit, err = e.shouldBeRewarded(stakerToReward, primaryNetworkValidator)
return err
}
func (e *ProposalTxExecutor) rewardValidatorTx(uValidatorTx txs.ValidatorTx, validator *state.Staker) error {
var (
txID = validator.TxID
stake = uValidatorTx.Stake()
outputs = uValidatorTx.Outputs()
// Invariant: The staked asset must be equal to the reward asset.
stakeAsset = stake[0].Asset
)
// Refund the stake only when validator is about to leave
// the staking set
for i, out := range stake {
utxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(len(outputs) + i),
},
Asset: out.Asset,
Out: out.Output(),
}
e.OnCommitState.AddUTXO(utxo)
e.OnAbortState.AddUTXO(utxo)
}
utxosOffset := 0
// Provide the reward here
reward := validator.PotentialReward
if reward > 0 {
validationRewardsOwner := uValidatorTx.ValidationRewardsOwner()
outIntf, err := e.Fx.CreateOutput(reward, validationRewardsOwner)
if err != nil {
return fmt.Errorf("failed to create output: %w", err)
}
out, ok := outIntf.(verify.State)
if !ok {
return ErrInvalidState
}
utxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(len(outputs) + len(stake)),
},
Asset: stakeAsset,
Out: out,
}
e.OnCommitState.AddUTXO(utxo)
e.OnCommitState.AddRewardUTXO(txID, utxo)
utxosOffset++
}
// Provide the accrued delegatee rewards from successful delegations here.
delegateeReward, err := e.OnCommitState.GetDelegateeReward(
validator.SubnetID,
validator.NodeID,
)
if err != nil {
return fmt.Errorf("failed to fetch accrued delegatee rewards: %w", err)
}
if delegateeReward == 0 {
return nil
}
delegationRewardsOwner := uValidatorTx.DelegationRewardsOwner()
outIntf, err := e.Fx.CreateOutput(delegateeReward, delegationRewardsOwner)
if err != nil {
return fmt.Errorf("failed to create output: %w", err)
}
out, ok := outIntf.(verify.State)
if !ok {
return ErrInvalidState
}
onCommitUtxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(len(outputs) + len(stake) + utxosOffset),
},
Asset: stakeAsset,
Out: out,
}
e.OnCommitState.AddUTXO(onCommitUtxo)
e.OnCommitState.AddRewardUTXO(txID, onCommitUtxo)
// Note: There is no [offset] if the RewardValidatorTx is
// aborted, because the validator reward is not awarded.
onAbortUtxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(len(outputs) + len(stake)),
},
Asset: stakeAsset,
Out: out,
}
e.OnAbortState.AddUTXO(onAbortUtxo)
e.OnAbortState.AddRewardUTXO(txID, onAbortUtxo)
return nil
}
func (e *ProposalTxExecutor) rewardDelegatorTx(uDelegatorTx txs.DelegatorTx, delegator *state.Staker) error {
var (
txID = delegator.TxID
stake = uDelegatorTx.Stake()
outputs = uDelegatorTx.Outputs()
// Invariant: The staked asset must be equal to the reward asset.
stakeAsset = stake[0].Asset
)
// Refund the stake only when delegator is about to leave
// the staking set
for i, out := range stake {
utxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(len(outputs) + i),
},
Asset: out.Asset,
Out: out.Output(),
}
e.OnCommitState.AddUTXO(utxo)
e.OnAbortState.AddUTXO(utxo)
}
// We're (possibly) rewarding a delegator, so we need to fetch
// the validator they are delegated to.
validator, err := e.OnCommitState.GetCurrentValidator(delegator.SubnetID, delegator.NodeID)
if err != nil {
return fmt.Errorf("failed to get whether %s is a validator: %w", delegator.NodeID, err)
}
vdrTxIntf, _, err := e.OnCommitState.GetTx(validator.TxID)
if err != nil {
return fmt.Errorf("failed to get whether %s is a validator: %w", delegator.NodeID, err)
}
// Invariant: Delegators must only be able to reference validator
// transactions that implement [txs.ValidatorTx]. All
// validator transactions implement this interface except the
// AddSubnetValidatorTx.
vdrTx, ok := vdrTxIntf.Unsigned.(txs.ValidatorTx)
if !ok {
return ErrWrongTxType
}
// Calculate split of reward between delegator/delegatee
delegateeReward, delegatorReward := reward.Split(delegator.PotentialReward, vdrTx.Shares())
utxosOffset := 0
// Reward the delegator here
reward := delegatorReward
if reward > 0 {
rewardsOwner := uDelegatorTx.RewardsOwner()
outIntf, err := e.Fx.CreateOutput(reward, rewardsOwner)
if err != nil {
return fmt.Errorf("failed to create output: %w", err)
}
out, ok := outIntf.(verify.State)
if !ok {
return ErrInvalidState
}
utxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(len(outputs) + len(stake)),
},
Asset: stakeAsset,
Out: out,
}
e.OnCommitState.AddUTXO(utxo)
e.OnCommitState.AddRewardUTXO(txID, utxo)
utxosOffset++
}
if delegateeReward == 0 {
return nil
}
// Reward the delegatee here
if e.Config.IsCortinaActivated(validator.StartTime) {
previousDelegateeReward, err := e.OnCommitState.GetDelegateeReward(
validator.SubnetID,
validator.NodeID,
)
if err != nil {
return fmt.Errorf("failed to get delegatee reward: %w", err)
}
// Invariant: The rewards calculator can never return a
// [potentialReward] that would overflow the
// accumulated rewards.
newDelegateeReward := previousDelegateeReward + delegateeReward
// For any validators starting after [CortinaTime], we defer rewarding the
// [reward] until their staking period is over.
err = e.OnCommitState.SetDelegateeReward(
validator.SubnetID,
validator.NodeID,
newDelegateeReward,
)
if err != nil {
return fmt.Errorf("failed to update delegatee reward: %w", err)
}
} else {
// For any validators who started prior to [CortinaTime], we issue the
// [delegateeReward] immediately.
delegationRewardsOwner := vdrTx.DelegationRewardsOwner()
outIntf, err := e.Fx.CreateOutput(delegateeReward, delegationRewardsOwner)
if err != nil {
return fmt.Errorf("failed to create output: %w", err)
}
out, ok := outIntf.(verify.State)
if !ok {
return ErrInvalidState
}
utxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(len(outputs) + len(stake) + utxosOffset),
},
Asset: stakeAsset,
Out: out,
}
e.OnCommitState.AddUTXO(utxo)
e.OnCommitState.AddRewardUTXO(txID, utxo)
}
return nil
}
func (e *ProposalTxExecutor) shouldBeRewarded(stakerToReward, primaryNetworkValidator *state.Staker) (bool, error) {
expectedUptimePercentage := e.Config.UptimePercentage
if stakerToReward.SubnetID != constants.PrimaryNetworkID {
transformSubnet, err := GetTransformSubnetTx(e.OnCommitState, stakerToReward.SubnetID)
if err != nil {
return false, fmt.Errorf("failed to calculate uptime: %w", err)
}
expectedUptimePercentage = float64(transformSubnet.UptimeRequirement) / reward.PercentDenominator
}
// TODO: calculate subnet uptimes
uptime, err := e.Uptimes.CalculateUptimePercentFrom(
primaryNetworkValidator.NodeID,
constants.PrimaryNetworkID,
primaryNetworkValidator.StartTime,
)
if err != nil {
return false, fmt.Errorf("failed to calculate uptime: %w", err)
}
return uptime >= expectedUptimePercentage, nil
}