-
Notifications
You must be signed in to change notification settings - Fork 649
/
add_validator_tx.go
297 lines (264 loc) · 9.8 KB
/
add_validator_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
// 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/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/components/verify"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
safemath "github.com/ava-labs/avalanchego/utils/math"
)
var (
errNilTx = errors.New("tx is nil")
errWeightTooSmall = errors.New("weight of this validator is too low")
errWeightTooLarge = errors.New("weight of this validator is too large")
errStakeTooShort = errors.New("staking period is too short")
errStakeTooLong = errors.New("staking period is too long")
errInsufficientDelegationFee = errors.New("staker charges an insufficient delegation fee")
errFutureStakeTime = fmt.Errorf("staker is attempting to start staking more than %s ahead of the current chain time", maxFutureStartTime)
errTooManyShares = fmt.Errorf("a staker can only require at most %d shares from delegators", PercentDenominator)
_ UnsignedProposalTx = &UnsignedAddValidatorTx{}
_ TimedTx = &UnsignedAddValidatorTx{}
)
// UnsignedAddValidatorTx is an unsigned addValidatorTx
type UnsignedAddValidatorTx struct {
// Metadata, inputs and outputs
BaseTx `serialize:"true"`
// Describes the delegatee
Validator 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 Owner `serialize:"true" json:"rewardsOwner"`
// Fee this validator charges delegators as a percentage, times 10,000
// For example, if this validator has Shares=300,000 then they take 30% of rewards from delegators
Shares uint32 `serialize:"true" json:"shares"`
}
// InitCtx sets the FxID fields in the inputs and outputs of this
// [UnsignedAddValidatorTx]. Also sets the [ctx] to the given [vm.ctx] so that
// the addresses can be json marshalled into human readable format
func (tx *UnsignedAddValidatorTx) 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 *UnsignedAddValidatorTx) StartTime() time.Time {
return tx.Validator.StartTime()
}
// EndTime of this validator
func (tx *UnsignedAddValidatorTx) EndTime() time.Time {
return tx.Validator.EndTime()
}
// Weight of this validator
func (tx *UnsignedAddValidatorTx) Weight() uint64 {
return tx.Validator.Weight()
}
// SyntacticVerify returns nil iff [tx] is valid
func (tx *UnsignedAddValidatorTx) SyntacticVerify(ctx *snow.Context) error {
switch {
case tx == nil:
return errNilTx
case tx.syntacticallyVerified: // already passed syntactic verification
return nil
case tx.Shares > PercentDenominator: // Ensure delegators shares are in the allowed amount
return errTooManyShares
}
if err := tx.BaseTx.SyntacticVerify(ctx); err != nil {
return fmt.Errorf("failed to verify BaseTx: %w", 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("failed to verify output: %w", err)
}
newWeight, err := safemath.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("validator 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 *UnsignedAddValidatorTx) SemanticVerify(vm *VM, parentState MutableState, stx *Tx) error {
_, _, 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 *UnsignedAddValidatorTx) 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
}
switch {
case tx.Validator.Wght < vm.MinValidatorStake: // Ensure validator is staking at least the minimum amount
return nil, nil, errWeightTooSmall
case tx.Validator.Wght > vm.MaxValidatorStake: // Ensure validator isn't staking too much
return nil, nil, errWeightTooLarge
case tx.Shares < vm.MinDelegationFee:
return nil, nil, errInsufficientDelegationFee
}
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
}
currentStakers := parentState.CurrentStakerChainState()
pendingStakers := parentState.PendingStakerChainState()
outs := make([]*avax.TransferableOutput, len(tx.Outs)+len(tx.Stake))
copy(outs, tx.Outs)
copy(outs[len(tx.Outs):], tx.Stake)
if vm.bootstrapped.GetValue() {
currentTimestamp := parentState.GetTimestamp()
// Ensure the proposed validator starts after the current time
startTime := tx.StartTime()
if !currentTimestamp.Before(startTime) {
return nil, nil, fmt.Errorf(
"validator's start time (%s) at or before current timestamp (%s)",
startTime,
currentTimestamp,
)
}
// Ensure this validator isn't currently a validator.
_, err := currentStakers.GetValidator(tx.Validator.NodeID)
if err == nil {
return nil, nil, fmt.Errorf(
"%s is already a primary network validator",
tx.Validator.NodeID.PrefixedString(constants.NodeIDPrefix),
)
}
if err != database.ErrNotFound {
return nil, nil, fmt.Errorf(
"failed to find whether %s is a validator: %w",
tx.Validator.NodeID.PrefixedString(constants.NodeIDPrefix),
err,
)
}
// Ensure this validator isn't about to become a validator.
_, err = pendingStakers.GetValidatorTx(tx.Validator.NodeID)
if err == nil {
return nil, nil, fmt.Errorf(
"%s is about to become a primary network validator",
tx.Validator.NodeID.PrefixedString(constants.NodeIDPrefix),
)
}
if err != database.ErrNotFound {
return nil, nil, fmt.Errorf(
"failed to find whether %s is about to become a validator: %w",
tx.Validator.NodeID.PrefixedString(constants.NodeIDPrefix),
err,
)
}
// 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 startTime.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 *UnsignedAddValidatorTx) InitiallyPrefersCommit(vm *VM) bool {
return tx.StartTime().After(vm.clock.Time())
}
// NewAddValidatorTx returns a new NewAddValidatorTx
func (vm *VM) newAddValidatorTx(
stakeAmt, // Amount the delegator stakes
startTime, // Unix time they start delegating
endTime uint64, // Unix time they stop delegating
nodeID ids.ShortID, // ID of the node we are delegating to
rewardAddress ids.ShortID, // Address to send reward to, if applicable
shares uint32, // 10,000 times percentage of reward taken from delegators
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 := &UnsignedAddValidatorTx{
BaseTx: BaseTx{BaseTx: avax.BaseTx{
NetworkID: vm.ctx.NetworkID,
BlockchainID: vm.ctx.ChainID,
Ins: ins,
Outs: unlockedOuts,
}},
Validator: Validator{
NodeID: nodeID,
Start: startTime,
End: endTime,
Wght: stakeAmt,
},
Stake: lockedOuts,
RewardsOwner: &secp256k1fx.OutputOwners{
Locktime: 0,
Threshold: 1,
Addrs: []ids.ShortID{rewardAddress},
},
Shares: shares,
}
tx := &Tx{UnsignedTx: utx}
if err := tx.Sign(Codec, signers); err != nil {
return nil, err
}
return tx, utx.SyntacticVerify(vm.ctx)
}