-
Notifications
You must be signed in to change notification settings - Fork 642
/
add_delegator_tx.go
605 lines (539 loc) · 18.4 KB
/
add_delegator_tx.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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package platformvm
import (
"errors"
"fmt"
"time"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto"
"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/fx"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
pChainValidator "github.com/ava-labs/avalanchego/vms/platformvm/validator"
)
var (
errDelegatorSubset = errors.New("delegator's time range must be a subset of the validator's time range")
errInvalidState = errors.New("generated output isn't valid state")
errOverDelegated = errors.New("validator would be over delegated")
_ UnsignedProposalTx = &UnsignedAddDelegatorTx{}
_ TimedTx = &UnsignedAddDelegatorTx{}
)
// UnsignedAddDelegatorTx is an unsigned addDelegatorTx
type UnsignedAddDelegatorTx struct {
// Metadata, inputs and outputs
BaseTx `serialize:"true"`
// Describes the delegatee
Validator pChainValidator.Validator `serialize:"true" json:"validator"`
// Where to send staked tokens when done validating
Stake []*avax.TransferableOutput `serialize:"true" json:"stake"`
// Where to send staking rewards when done validating
RewardsOwner fx.Owner `serialize:"true" json:"rewardsOwner"`
}
// InitCtx sets the FxID fields in the inputs and outputs of this
// [UnsignedAddDelegatorTx]. Also sets the [ctx] to the given [vm.ctx] so that
// the addresses can be json marshalled into human readable format
func (tx *UnsignedAddDelegatorTx) InitCtx(ctx *snow.Context) {
tx.BaseTx.InitCtx(ctx)
for _, out := range tx.Stake {
out.FxID = secp256k1fx.ID
out.InitCtx(ctx)
}
tx.RewardsOwner.InitCtx(ctx)
}
// StartTime of this validator
func (tx *UnsignedAddDelegatorTx) StartTime() time.Time {
return tx.Validator.StartTime()
}
// EndTime of this validator
func (tx *UnsignedAddDelegatorTx) EndTime() time.Time {
return tx.Validator.EndTime()
}
// Weight of this validator
func (tx *UnsignedAddDelegatorTx) Weight() uint64 {
return tx.Validator.Weight()
}
// SyntacticVerify returns nil iff [tx] is valid
func (tx *UnsignedAddDelegatorTx) SyntacticVerify(ctx *snow.Context) error {
switch {
case tx == nil:
return errNilTx
case tx.syntacticallyVerified: // already passed syntactic verification
return nil
}
if err := tx.BaseTx.SyntacticVerify(ctx); err != nil {
return err
}
if err := verify.All(&tx.Validator, tx.RewardsOwner); err != nil {
return fmt.Errorf("failed to verify validator or rewards owner: %w", err)
}
totalStakeWeight := uint64(0)
for _, out := range tx.Stake {
if err := out.Verify(); err != nil {
return fmt.Errorf("output verification failed: %w", err)
}
newWeight, err := math.Add64(totalStakeWeight, out.Output().Amount())
if err != nil {
return err
}
totalStakeWeight = newWeight
}
switch {
case !avax.IsSortedTransferableOutputs(tx.Stake, Codec):
return errOutputsNotSorted
case totalStakeWeight != tx.Validator.Wght:
return fmt.Errorf("delegator weight %d is not equal to total stake weight %d", tx.Validator.Wght, totalStakeWeight)
}
// cache that this is valid
tx.syntacticallyVerified = true
return nil
}
// Attempts to verify this transaction with the provided state.
func (tx *UnsignedAddDelegatorTx) SemanticVerify(vm *VM, parentState MutableState, stx *Tx) error {
startTime := tx.StartTime()
maxLocalStartTime := vm.clock.Time().Add(maxFutureStartTime)
if startTime.After(maxLocalStartTime) {
return errFutureStakeTime
}
_, _, err := tx.Execute(vm, parentState, stx)
// We ignore [errFutureStakeTime] here because an advanceTimeTx will be
// issued before this transaction is issued.
if errors.Is(err, errFutureStakeTime) {
return nil
}
return err
}
// Execute this transaction.
func (tx *UnsignedAddDelegatorTx) Execute(
vm *VM,
parentState MutableState,
stx *Tx,
) (
VersionedState,
VersionedState,
error,
) {
// Verify the tx is well-formed
if err := tx.SyntacticVerify(vm.ctx); err != nil {
return nil, nil, err
}
duration := tx.Validator.Duration()
switch {
case duration < vm.MinStakeDuration: // Ensure staking length is not too short
return nil, nil, errStakeTooShort
case duration > vm.MaxStakeDuration: // Ensure staking length is not too long
return nil, nil, errStakeTooLong
case tx.Validator.Wght < vm.MinDelegatorStake:
// Ensure validator is staking at least the minimum amount
return nil, nil, errWeightTooSmall
}
outs := make([]*avax.TransferableOutput, len(tx.Outs)+len(tx.Stake))
copy(outs, tx.Outs)
copy(outs[len(tx.Outs):], tx.Stake)
currentStakers := parentState.CurrentStakerChainState()
pendingStakers := parentState.PendingStakerChainState()
if vm.bootstrapped.GetValue() {
currentTimestamp := parentState.GetTimestamp()
// Ensure the proposed validator starts after the current timestamp
validatorStartTime := tx.StartTime()
if !currentTimestamp.Before(validatorStartTime) {
return nil, nil, fmt.Errorf(
"chain timestamp (%s) not before validator's start time (%s)",
currentTimestamp,
validatorStartTime,
)
}
currentValidator, err := currentStakers.GetValidator(tx.Validator.NodeID)
if err != nil && err != database.ErrNotFound {
return nil, nil, fmt.Errorf(
"failed to find whether %s is a validator: %w",
tx.Validator.NodeID,
err,
)
}
pendingValidator := pendingStakers.GetValidator(tx.Validator.NodeID)
pendingDelegators := pendingValidator.Delegators()
var (
vdrTx *UnsignedAddValidatorTx
currentDelegatorWeight uint64
currentDelegators []*UnsignedAddDelegatorTx
)
if err == nil {
// This delegator is attempting to delegate to a currently validing
// node.
vdrTx = currentValidator.AddValidatorTx()
currentDelegatorWeight = currentValidator.DelegatorWeight()
currentDelegators = currentValidator.Delegators()
} else {
// This delegator is attempting to delegate to a node that hasn't
// started validating yet.
vdrTx, err = pendingStakers.GetValidatorTx(tx.Validator.NodeID)
if err != nil {
if err == database.ErrNotFound {
return nil, nil, errDelegatorSubset
}
return nil, nil, fmt.Errorf(
"failed to find whether %s is a validator: %w",
tx.Validator.NodeID,
err,
)
}
}
// Ensure that the period this delegator delegates is a subset of the
// time the validator validates.
if !tx.Validator.BoundedBy(vdrTx.StartTime(), vdrTx.EndTime()) {
return nil, nil, errDelegatorSubset
}
// Ensure that the period this delegator delegates wouldn't become over
// delegated.
vdrWeight := vdrTx.Weight()
currentWeight, err := math.Add64(vdrWeight, currentDelegatorWeight)
if err != nil {
return nil, nil, err
}
maximumWeight, err := math.Mul64(MaxValidatorWeightFactor, vdrWeight)
if err != nil {
return nil, nil, errStakeOverflow
}
if !currentTimestamp.Before(vm.ApricotPhase3Time) {
maximumWeight = math.Min64(maximumWeight, vm.MaxValidatorStake)
}
canDelegate, err := CanDelegate(
currentDelegators,
pendingDelegators,
tx,
currentWeight,
maximumWeight,
)
if err != nil {
return nil, nil, err
}
if !canDelegate {
return nil, nil, errOverDelegated
}
// Verify the flowcheck
if err := vm.semanticVerifySpend(parentState, tx, tx.Ins, outs, stx.Creds, vm.AddStakerTxFee, vm.ctx.AVAXAssetID); err != nil {
return nil, nil, fmt.Errorf("failed semanticVerifySpend: %w", err)
}
// Make sure the tx doesn't start too far in the future. This is done
// last to allow SemanticVerification to explicitly check for this
// error.
maxStartTime := currentTimestamp.Add(maxFutureStartTime)
if validatorStartTime.After(maxStartTime) {
return nil, nil, errFutureStakeTime
}
}
// Set up the state if this tx is committed
newlyPendingStakers := pendingStakers.AddStaker(stx)
onCommitState := newVersionedState(parentState, currentStakers, newlyPendingStakers)
// Consume the UTXOS
consumeInputs(onCommitState, tx.Ins)
// Produce the UTXOS
txID := tx.ID()
produceOutputs(onCommitState, txID, vm.ctx.AVAXAssetID, tx.Outs)
// Set up the state if this tx is aborted
onAbortState := newVersionedState(parentState, currentStakers, pendingStakers)
// Consume the UTXOS
consumeInputs(onAbortState, tx.Ins)
// Produce the UTXOS
produceOutputs(onAbortState, txID, vm.ctx.AVAXAssetID, outs)
return onCommitState, onAbortState, nil
}
// InitiallyPrefersCommit returns true if the proposed validators start time is
// after the current wall clock time,
func (tx *UnsignedAddDelegatorTx) InitiallyPrefersCommit(vm *VM) bool {
return tx.StartTime().After(vm.clock.Time())
}
// Creates a new transaction
func (vm *VM) newAddDelegatorTx(
stakeAmt, // Amount the delegator stakes
startTime, // Unix time they start delegating
endTime uint64, // Unix time they stop delegating
nodeID ids.NodeID, // ID of the node we are delegating to
rewardAddress ids.ShortID, // Address to send reward to, if applicable
keys []*crypto.PrivateKeySECP256K1R, // Keys providing the staked tokens
changeAddr ids.ShortID, // Address to send change to, if there is any
) (*Tx, error) {
ins, unlockedOuts, lockedOuts, signers, err := vm.stake(keys, stakeAmt, vm.AddStakerTxFee, changeAddr)
if err != nil {
return nil, fmt.Errorf("couldn't generate tx inputs/outputs: %w", err)
}
// Create the tx
utx := &UnsignedAddDelegatorTx{
BaseTx: BaseTx{BaseTx: avax.BaseTx{
NetworkID: vm.ctx.NetworkID,
BlockchainID: vm.ctx.ChainID,
Ins: ins,
Outs: unlockedOuts,
}},
Validator: pChainValidator.Validator{
NodeID: nodeID,
Start: startTime,
End: endTime,
Wght: stakeAmt,
},
Stake: lockedOuts,
RewardsOwner: &secp256k1fx.OutputOwners{
Locktime: 0,
Threshold: 1,
Addrs: []ids.ShortID{rewardAddress},
},
}
tx := &Tx{UnsignedTx: utx}
if err := tx.Sign(Codec, signers); err != nil {
return nil, err
}
return tx, utx.SyntacticVerify(vm.ctx)
}
// CanDelegate returns if the [new] delegator can be added to a validator who
// has [current] and [pending] delegators. [currentStake] is the current amount
// of stake on the validator, include the [current] delegators. [maximumStake]
// is the maximum amount of stake that can be on the validator at any given
// time. It is assumed that the validator without adding [new] does not violate
// [maximumStake].
func CanDelegate(
current,
pending []*UnsignedAddDelegatorTx, // sorted by next start time first
new *UnsignedAddDelegatorTx,
currentStake,
maximumStake uint64,
) (bool, error) {
maxStake, err := maxStakeAmount(current, pending, new.StartTime(), new.EndTime(), currentStake)
if err != nil {
return false, err
}
newMaxStake, err := math.Add64(maxStake, new.Validator.Wght)
if err != nil {
return false, err
}
return newMaxStake <= maximumStake, nil
}
// Return the maximum amount of stake on a node (including delegations) at any
// given time between [startTime] and [endTime] given that:
// * The amount of stake on the node right now is [currentStake]
// * The delegations currently on this node are [current]
// * [current] is sorted in order of increasing delegation end time.
// * The stake delegated in [current] are already included in [currentStake]
// * [startTime] is in the future, and [endTime] > [startTime]
// * The delegations that will be on this node in the future are [pending]
// * The start time of all delegations in [pending] are in the future
// * [pending] is sorted in order of increasing delegation start time
func maxStakeAmount(
current,
pending []*UnsignedAddDelegatorTx, // sorted by next start time first
startTime time.Time,
endTime time.Time,
currentStake uint64,
) (uint64, error) {
// Keep track of which delegators should be removed next so that we can
// efficiently remove delegators and keep the current stake updated.
toRemoveHeap := pChainValidator.EndTimeHeap{}
for _, currentDelegator := range current {
toRemoveHeap.Add(¤tDelegator.Validator)
}
var (
err error
// [maxStake] is the max stake at any point between now [starTime] and [endTime]
maxStake uint64
)
// Calculate what the amount staked will be when each pending delegation
// starts.
for _, nextPending := range pending { // Iterates in order of increasing start time
// Calculate what the amount staked will be when this delegation starts.
nextPendingStartTime := nextPending.StartTime()
if nextPendingStartTime.After(endTime) {
// This delegation starts after [endTime].
// Since we're calculating the max amount staked in
// [startTime, endTime], we can stop. (Recall that [pending] is
// sorted in order of increasing end time.)
break
}
// Subtract from [currentStake] all of the current delegations that will
// have ended by the time that the delegation [nextPending] starts.
for toRemoveHeap.Len() > 0 {
// Get the next current delegation that will end.
toRemove := toRemoveHeap.Peek()
toRemoveEndTime := toRemove.EndTime()
if toRemoveEndTime.After(nextPendingStartTime) {
break
}
// This current delegation [toRemove] ends before [nextPending]
// starts, so its stake should be subtracted from [currentStake].
// Changed in AP3:
// If the new delegator has started, then this current delegator
// should have an end time that is > [startTime].
newDelegatorHasStartedBeforeFinish := toRemoveEndTime.After(startTime)
if newDelegatorHasStartedBeforeFinish && currentStake > maxStake {
// Only update [maxStake] if it's after [startTime]
maxStake = currentStake
}
currentStake, err = math.Sub64(currentStake, toRemove.Wght)
if err != nil {
return 0, err
}
// Changed in AP3:
// Remove the delegator from the heap and update the heap so that
// the top of the heap is the next delegator to remove.
toRemoveHeap.Remove()
}
// Add to [currentStake] the stake of this pending delegator to
// calculate what the stake will be when this pending delegation has
// started.
currentStake, err = math.Add64(currentStake, nextPending.Validator.Wght)
if err != nil {
return 0, err
}
// Changed in AP3:
// If the new delegator has started, then this pending delegator should
// have a start time that is >= [startTime]. Otherwise, the delegator
// hasn't started yet and the [currentStake] shouldn't count towards the
// [maximumStake] during the delegators delegation period.
newDelegatorHasStarted := !nextPendingStartTime.Before(startTime)
if newDelegatorHasStarted && currentStake > maxStake {
// Only update [maxStake] if it's after [startTime]
maxStake = currentStake
}
// This pending delegator is a current delegator relative
// when considering later pending delegators that start late
toRemoveHeap.Add(&nextPending.Validator)
}
// [currentStake] is now the amount staked before the next pending delegator
// whose start time is after [endTime].
// If there aren't any delegators that will be added before the end of our
// delegation period, we should advance through time until our delegation
// period starts.
for toRemoveHeap.Len() > 0 {
toRemove := toRemoveHeap.Peek()
toRemoveEndTime := toRemove.EndTime()
if toRemoveEndTime.After(startTime) {
break
}
currentStake, err = math.Sub64(currentStake, toRemove.Wght)
if err != nil {
return 0, err
}
// Changed in AP3:
// Remove the delegator from the heap and update the heap so that the
// top of the heap is the next delegator to remove.
toRemoveHeap.Remove()
}
// We have advanced time to be inside the delegation window.
// Make sure that the max stake is updated accordingly.
if currentStake > maxStake {
maxStake = currentStake
}
return maxStake, nil
}
func (vm *VM) maxStakeAmount(
subnetID ids.ID,
nodeID ids.NodeID,
startTime time.Time,
endTime time.Time,
) (uint64, error) {
if startTime.After(endTime) {
return 0, errStartAfterEndTime
}
if timestamp := vm.internalState.GetTimestamp(); startTime.Before(timestamp) {
return 0, errStartTimeTooEarly
}
if subnetID == constants.PrimaryNetworkID {
return vm.maxPrimarySubnetStakeAmount(nodeID, startTime, endTime)
}
return vm.maxSubnetStakeAmount(subnetID, nodeID, startTime, endTime)
}
func (vm *VM) maxSubnetStakeAmount(
subnetID ids.ID,
nodeID ids.NodeID,
startTime time.Time,
endTime time.Time,
) (uint64, error) {
var (
vdrTx *UnsignedAddSubnetValidatorTx
exists bool
)
pendingStakers := vm.internalState.PendingStakerChainState()
pendingValidator := pendingStakers.GetValidator(nodeID)
currentStakers := vm.internalState.CurrentStakerChainState()
currentValidator, err := currentStakers.GetValidator(nodeID)
switch err {
case nil:
vdrTx, exists = currentValidator.SubnetValidators()[subnetID]
if !exists {
vdrTx = pendingValidator.SubnetValidators()[subnetID]
}
case database.ErrNotFound:
vdrTx = pendingValidator.SubnetValidators()[subnetID]
default:
return 0, err
}
if vdrTx == nil {
return 0, nil
}
if vdrTx.StartTime().After(endTime) {
return 0, nil
}
if vdrTx.EndTime().Before(startTime) {
return 0, nil
}
return vdrTx.Weight(), nil
}
func (vm *VM) maxPrimarySubnetStakeAmount(
nodeID ids.NodeID,
startTime time.Time,
endTime time.Time,
) (uint64, error) {
currentStakers := vm.internalState.CurrentStakerChainState()
pendingStakers := vm.internalState.PendingStakerChainState()
pendingValidator := pendingStakers.GetValidator(nodeID)
currentValidator, err := currentStakers.GetValidator(nodeID)
switch err {
case nil:
vdrTx := currentValidator.AddValidatorTx()
if vdrTx.StartTime().After(endTime) {
return 0, nil
}
if vdrTx.EndTime().Before(startTime) {
return 0, nil
}
currentWeight := vdrTx.Weight()
currentWeight, err = math.Add64(currentWeight, currentValidator.DelegatorWeight())
if err != nil {
return 0, err
}
return maxStakeAmount(
currentValidator.Delegators(),
pendingValidator.Delegators(),
startTime,
endTime,
currentWeight,
)
case database.ErrNotFound:
futureValidator, err := pendingStakers.GetValidatorTx(nodeID)
if err == database.ErrNotFound {
return 0, nil
}
if err != nil {
return 0, err
}
if futureValidator.StartTime().After(endTime) {
return 0, nil
}
if futureValidator.EndTime().Before(startTime) {
return 0, nil
}
return maxStakeAmount(
nil,
pendingValidator.Delegators(),
startTime,
endTime,
futureValidator.Weight(),
)
default:
return 0, err
}
}