-
Notifications
You must be signed in to change notification settings - Fork 675
/
genesis.go
580 lines (512 loc) · 17.7 KB
/
genesis.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package genesis
import (
"errors"
"fmt"
"time"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/formatting"
"github.com/ava-labs/avalanchego/utils/formatting/address"
"github.com/ava-labs/avalanchego/utils/json"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/vms/avm"
"github.com/ava-labs/avalanchego/vms/avm/fxs"
"github.com/ava-labs/avalanchego/vms/nftfx"
"github.com/ava-labs/avalanchego/vms/platformvm/api"
"github.com/ava-labs/avalanchego/vms/platformvm/genesis"
"github.com/ava-labs/avalanchego/vms/propertyfx"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
xchaintxs "github.com/ava-labs/avalanchego/vms/avm/txs"
pchaintxs "github.com/ava-labs/avalanchego/vms/platformvm/txs"
)
const (
defaultEncoding = formatting.Hex
configChainIDAlias = "X"
)
var (
errStakeDurationTooHigh = errors.New("initial stake duration larger than maximum configured")
errNoInitiallyStakedFunds = errors.New("initial staked funds cannot be empty")
errNoSupply = errors.New("initial supply must be > 0")
errNoStakeDuration = errors.New("initial stake duration must be > 0")
errNoStakers = errors.New("initial stakers must be > 0")
errNoCChainGenesis = errors.New("C-Chain genesis cannot be empty")
errNoTxs = errors.New("genesis creates no transactions")
errNoAllocationToStake = errors.New("no allocation to stake")
errDuplicateInitiallyStakedAddress = errors.New("duplicate initially staked address")
errConflictingNetworkIDs = errors.New("conflicting networkIDs")
errFutureStartTime = errors.New("startTime cannot be in the future")
errInitialStakeDurationTooLow = errors.New("initial stake duration is too low")
errOverridesStandardNetworkConfig = errors.New("overrides standard network genesis config")
)
// validateInitialStakedFunds ensures all staked
// funds have allocations and that all staked
// funds are unique.
//
// This function assumes that NetworkID in *Config has already
// been checked for correctness.
func validateInitialStakedFunds(config *Config) error {
if len(config.InitialStakedFunds) == 0 {
return errNoInitiallyStakedFunds
}
allocationSet := set.Set[ids.ShortID]{}
initialStakedFundsSet := set.Set[ids.ShortID]{}
for _, allocation := range config.Allocations {
// It is ok to have duplicates as different
// ethAddrs could claim to the same avaxAddr.
allocationSet.Add(allocation.AVAXAddr)
}
for _, staker := range config.InitialStakedFunds {
if initialStakedFundsSet.Contains(staker) {
avaxAddr, err := address.Format(
configChainIDAlias,
constants.GetHRP(config.NetworkID),
staker.Bytes(),
)
if err != nil {
return fmt.Errorf(
"unable to format address from %s",
staker.String(),
)
}
return fmt.Errorf(
"%w: %s",
errDuplicateInitiallyStakedAddress,
avaxAddr,
)
}
initialStakedFundsSet.Add(staker)
if !allocationSet.Contains(staker) {
avaxAddr, err := address.Format(
configChainIDAlias,
constants.GetHRP(config.NetworkID),
staker.Bytes(),
)
if err != nil {
return fmt.Errorf(
"unable to format address from %s",
staker.String(),
)
}
return fmt.Errorf(
"%w in address %s",
errNoAllocationToStake,
avaxAddr,
)
}
}
return nil
}
// validateConfig returns an error if the provided
// *Config is not considered valid.
func validateConfig(networkID uint32, config *Config, stakingCfg *StakingConfig) error {
if networkID != config.NetworkID {
return fmt.Errorf(
"%w: expected %d but config contains %d",
errConflictingNetworkIDs,
networkID,
config.NetworkID,
)
}
initialSupply, err := config.InitialSupply()
switch {
case err != nil:
return fmt.Errorf("unable to calculate initial supply: %w", err)
case initialSupply == 0:
return errNoSupply
}
startTime := time.Unix(int64(config.StartTime), 0)
if time.Since(startTime) < 0 {
return fmt.Errorf(
"%w: %s",
errFutureStartTime,
startTime,
)
}
// We don't impose any restrictions on the minimum
// stake duration to enable complex testing configurations
// but recommend setting a minimum duration of at least
// 15 minutes.
if config.InitialStakeDuration == 0 {
return errNoStakeDuration
}
// Initial stake duration of genesis validators must be
// not larger than maximal stake duration specified for any validator.
if config.InitialStakeDuration > uint64(stakingCfg.MaxStakeDuration.Seconds()) {
return errStakeDurationTooHigh
}
if len(config.InitialStakers) == 0 {
return errNoStakers
}
offsetTimeRequired := config.InitialStakeDurationOffset * uint64(len(config.InitialStakers)-1)
if offsetTimeRequired > config.InitialStakeDuration {
return fmt.Errorf(
"%w must be at least %d",
errInitialStakeDurationTooLow,
offsetTimeRequired,
)
}
if err := validateInitialStakedFunds(config); err != nil {
return fmt.Errorf("initial staked funds validation failed: %w", err)
}
if len(config.CChainGenesis) == 0 {
return errNoCChainGenesis
}
return nil
}
// FromFile returns the genesis data of the Platform Chain.
//
// Since an Avalanche network has exactly one Platform Chain, and the Platform
// Chain defines the genesis state of the network (who is staking, which chains
// exist, etc.), defining the genesis state of the Platform Chain is the same as
// defining the genesis state of the network.
//
// FromFile accepts:
// 1) The ID of the new network. [networkID]
// 2) The location of a custom genesis config to load. [filepath]
//
// If [filepath] is empty or the given network ID is Mainnet, Testnet, or Local, returns error.
// If [filepath] is non-empty and networkID isn't Mainnet, Testnet, or Local,
// loads the network genesis data from the config at [filepath].
//
// FromFile returns:
//
// 1. The byte representation of the genesis state of the platform chain
// (ie the genesis state of the network)
// 2. The asset ID of AVAX
func FromFile(networkID uint32, filepath string, stakingCfg *StakingConfig) ([]byte, ids.ID, error) {
switch networkID {
case constants.MainnetID, constants.TestnetID, constants.LocalID:
return nil, ids.Empty, fmt.Errorf(
"%w: %s",
errOverridesStandardNetworkConfig,
constants.NetworkName(networkID),
)
}
config, err := GetConfigFile(filepath)
if err != nil {
return nil, ids.Empty, fmt.Errorf("unable to load provided genesis config at %s: %w", filepath, err)
}
if err := validateConfig(networkID, config, stakingCfg); err != nil {
return nil, ids.Empty, fmt.Errorf("genesis config validation failed: %w", err)
}
return FromConfig(config)
}
// FromFlag returns the genesis data of the Platform Chain.
//
// Since an Avalanche network has exactly one Platform Chain, and the Platform
// Chain defines the genesis state of the network (who is staking, which chains
// exist, etc.), defining the genesis state of the Platform Chain is the same as
// defining the genesis state of the network.
//
// FromFlag accepts:
// 1) The ID of the new network. [networkID]
// 2) The content of a custom genesis config to load. [genesisContent]
//
// If [genesisContent] is empty or the given network ID is Mainnet, Testnet, or Local, returns error.
// If [genesisContent] is non-empty and networkID isn't Mainnet, Testnet, or Local,
// loads the network genesis data from [genesisContent].
//
// FromFlag returns:
//
// 1. The byte representation of the genesis state of the platform chain
// (ie the genesis state of the network)
// 2. The asset ID of AVAX
func FromFlag(networkID uint32, genesisContent string, stakingCfg *StakingConfig) ([]byte, ids.ID, error) {
switch networkID {
case constants.MainnetID, constants.TestnetID, constants.LocalID:
return nil, ids.Empty, fmt.Errorf(
"%w: %s",
errOverridesStandardNetworkConfig,
constants.NetworkName(networkID),
)
}
customConfig, err := GetConfigContent(genesisContent)
if err != nil {
return nil, ids.Empty, fmt.Errorf("unable to load genesis content from flag: %w", err)
}
if err := validateConfig(networkID, customConfig, stakingCfg); err != nil {
return nil, ids.Empty, fmt.Errorf("genesis config validation failed: %w", err)
}
return FromConfig(customConfig)
}
// FromConfig returns:
//
// 1. The byte representation of the genesis state of the platform chain
// (ie the genesis state of the network)
// 2. The asset ID of AVAX
func FromConfig(config *Config) ([]byte, ids.ID, error) {
hrp := constants.GetHRP(config.NetworkID)
amount := uint64(0)
// Specify the genesis state of the AVM
avmArgs := avm.BuildGenesisArgs{
NetworkID: json.Uint32(config.NetworkID),
Encoding: defaultEncoding,
}
{
avax := avm.AssetDefinition{
Name: "Avalanche",
Symbol: "AVAX",
Denomination: 9,
InitialState: map[string][]interface{}{},
}
memoBytes := []byte{}
xAllocations := []Allocation(nil)
for _, allocation := range config.Allocations {
if allocation.InitialAmount > 0 {
xAllocations = append(xAllocations, allocation)
}
}
utils.Sort(xAllocations)
for _, allocation := range xAllocations {
addr, err := address.FormatBech32(hrp, allocation.AVAXAddr.Bytes())
if err != nil {
return nil, ids.Empty, err
}
avax.InitialState["fixedCap"] = append(avax.InitialState["fixedCap"], avm.Holder{
Amount: json.Uint64(allocation.InitialAmount),
Address: addr,
})
memoBytes = append(memoBytes, allocation.ETHAddr.Bytes()...)
amount += allocation.InitialAmount
}
var err error
avax.Memo, err = formatting.Encode(defaultEncoding, memoBytes)
if err != nil {
return nil, ids.Empty, fmt.Errorf("couldn't parse memo bytes to string: %w", err)
}
avmArgs.GenesisData = map[string]avm.AssetDefinition{
"AVAX": avax, // The AVM starts out with one asset: AVAX
}
}
avmReply := avm.BuildGenesisReply{}
avmSS := avm.CreateStaticService()
err := avmSS.BuildGenesis(nil, &avmArgs, &avmReply)
if err != nil {
return nil, ids.Empty, err
}
bytes, err := formatting.Decode(defaultEncoding, avmReply.Bytes)
if err != nil {
return nil, ids.Empty, fmt.Errorf("couldn't parse avm genesis reply: %w", err)
}
avaxAssetID, err := AVAXAssetID(bytes)
if err != nil {
return nil, ids.Empty, fmt.Errorf("couldn't generate AVAX asset ID: %w", err)
}
genesisTime := time.Unix(int64(config.StartTime), 0)
initialSupply, err := config.InitialSupply()
if err != nil {
return nil, ids.Empty, fmt.Errorf("couldn't calculate the initial supply: %w", err)
}
initiallyStaked := set.Of(config.InitialStakedFunds...)
skippedAllocations := []Allocation(nil)
// Specify the initial state of the Platform Chain
platformvmArgs := api.BuildGenesisArgs{
AvaxAssetID: avaxAssetID,
NetworkID: json.Uint32(config.NetworkID),
Time: json.Uint64(config.StartTime),
InitialSupply: json.Uint64(initialSupply),
Message: config.Message,
Encoding: defaultEncoding,
}
for _, allocation := range config.Allocations {
if initiallyStaked.Contains(allocation.AVAXAddr) {
skippedAllocations = append(skippedAllocations, allocation)
continue
}
addr, err := address.FormatBech32(hrp, allocation.AVAXAddr.Bytes())
if err != nil {
return nil, ids.Empty, err
}
for _, unlock := range allocation.UnlockSchedule {
if unlock.Amount > 0 {
msgStr, err := formatting.Encode(defaultEncoding, allocation.ETHAddr.Bytes())
if err != nil {
return nil, ids.Empty, fmt.Errorf("couldn't encode message: %w", err)
}
platformvmArgs.UTXOs = append(platformvmArgs.UTXOs,
api.UTXO{
Locktime: json.Uint64(unlock.Locktime),
Amount: json.Uint64(unlock.Amount),
Address: addr,
Message: msgStr,
},
)
amount += unlock.Amount
}
}
}
allNodeAllocations := splitAllocations(skippedAllocations, len(config.InitialStakers))
endStakingTime := genesisTime.Add(time.Duration(config.InitialStakeDuration) * time.Second)
stakingOffset := time.Duration(0)
for i, staker := range config.InitialStakers {
nodeAllocations := allNodeAllocations[i]
endStakingTime := endStakingTime.Add(-stakingOffset)
stakingOffset += time.Duration(config.InitialStakeDurationOffset) * time.Second
destAddrStr, err := address.FormatBech32(hrp, staker.RewardAddress.Bytes())
if err != nil {
return nil, ids.Empty, err
}
utxos := []api.UTXO(nil)
for _, allocation := range nodeAllocations {
addr, err := address.FormatBech32(hrp, allocation.AVAXAddr.Bytes())
if err != nil {
return nil, ids.Empty, err
}
for _, unlock := range allocation.UnlockSchedule {
msgStr, err := formatting.Encode(defaultEncoding, allocation.ETHAddr.Bytes())
if err != nil {
return nil, ids.Empty, fmt.Errorf("couldn't encode message: %w", err)
}
utxos = append(utxos, api.UTXO{
Locktime: json.Uint64(unlock.Locktime),
Amount: json.Uint64(unlock.Amount),
Address: addr,
Message: msgStr,
})
amount += unlock.Amount
}
}
delegationFee := json.Uint32(staker.DelegationFee)
platformvmArgs.Validators = append(platformvmArgs.Validators,
api.GenesisPermissionlessValidator{
GenesisValidator: api.GenesisValidator{
StartTime: json.Uint64(genesisTime.Unix()),
EndTime: json.Uint64(endStakingTime.Unix()),
NodeID: staker.NodeID,
},
RewardOwner: &api.Owner{
Threshold: 1,
Addresses: []string{destAddrStr},
},
Staked: utxos,
ExactDelegationFee: &delegationFee,
Signer: staker.Signer,
},
)
}
// Specify the chains that exist upon this network's creation
genesisStr, err := formatting.Encode(defaultEncoding, []byte(config.CChainGenesis))
if err != nil {
return nil, ids.Empty, fmt.Errorf("couldn't encode message: %w", err)
}
platformvmArgs.Chains = []api.Chain{
{
GenesisData: avmReply.Bytes,
SubnetID: constants.PrimaryNetworkID,
VMID: constants.AVMID,
FxIDs: []ids.ID{
secp256k1fx.ID,
nftfx.ID,
propertyfx.ID,
},
Name: "X-Chain",
},
{
GenesisData: genesisStr,
SubnetID: constants.PrimaryNetworkID,
VMID: constants.EVMID,
Name: "C-Chain",
},
}
platformvmReply := api.BuildGenesisReply{}
platformvmSS := api.StaticService{}
if err := platformvmSS.BuildGenesis(nil, &platformvmArgs, &platformvmReply); err != nil {
return nil, ids.Empty, fmt.Errorf("problem while building platform chain's genesis state: %w", err)
}
genesisBytes, err := formatting.Decode(platformvmReply.Encoding, platformvmReply.Bytes)
if err != nil {
return nil, ids.Empty, fmt.Errorf("problem parsing platformvm genesis bytes: %w", err)
}
return genesisBytes, avaxAssetID, nil
}
func splitAllocations(allocations []Allocation, numSplits int) [][]Allocation {
totalAmount := uint64(0)
for _, allocation := range allocations {
for _, unlock := range allocation.UnlockSchedule {
totalAmount += unlock.Amount
}
}
nodeWeight := totalAmount / uint64(numSplits)
allNodeAllocations := make([][]Allocation, 0, numSplits)
currentNodeAllocation := []Allocation(nil)
currentNodeAmount := uint64(0)
for _, allocation := range allocations {
currentAllocation := allocation
// Already added to the X-chain
currentAllocation.InitialAmount = 0
// Going to be added until the correct amount is reached
currentAllocation.UnlockSchedule = nil
for _, unlock := range allocation.UnlockSchedule {
unlock := unlock
for currentNodeAmount+unlock.Amount > nodeWeight && len(allNodeAllocations) < numSplits-1 {
amountToAdd := nodeWeight - currentNodeAmount
currentAllocation.UnlockSchedule = append(currentAllocation.UnlockSchedule, LockedAmount{
Amount: amountToAdd,
Locktime: unlock.Locktime,
})
unlock.Amount -= amountToAdd
currentNodeAllocation = append(currentNodeAllocation, currentAllocation)
allNodeAllocations = append(allNodeAllocations, currentNodeAllocation)
currentNodeAllocation = nil
currentNodeAmount = 0
currentAllocation = allocation
// Already added to the X-chain
currentAllocation.InitialAmount = 0
// Going to be added until the correct amount is reached
currentAllocation.UnlockSchedule = nil
}
if unlock.Amount == 0 {
continue
}
currentAllocation.UnlockSchedule = append(currentAllocation.UnlockSchedule, LockedAmount{
Amount: unlock.Amount,
Locktime: unlock.Locktime,
})
currentNodeAmount += unlock.Amount
}
if len(currentAllocation.UnlockSchedule) > 0 {
currentNodeAllocation = append(currentNodeAllocation, currentAllocation)
}
}
return append(allNodeAllocations, currentNodeAllocation)
}
func VMGenesis(genesisBytes []byte, vmID ids.ID) (*pchaintxs.Tx, error) {
genesis, err := genesis.Parse(genesisBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse genesis: %w", err)
}
for _, chain := range genesis.Chains {
uChain := chain.Unsigned.(*pchaintxs.CreateChainTx)
if uChain.VMID == vmID {
return chain, nil
}
}
return nil, fmt.Errorf("couldn't find blockchain with VM ID %s", vmID)
}
func AVAXAssetID(avmGenesisBytes []byte) (ids.ID, error) {
parser, err := xchaintxs.NewParser(
[]fxs.Fx{
&secp256k1fx.Fx{},
},
)
if err != nil {
return ids.Empty, err
}
genesisCodec := parser.GenesisCodec()
genesis := avm.Genesis{}
if _, err := genesisCodec.Unmarshal(avmGenesisBytes, &genesis); err != nil {
return ids.Empty, err
}
if len(genesis.Txs) == 0 {
return ids.Empty, errNoTxs
}
genesisTx := genesis.Txs[0]
tx := xchaintxs.Tx{Unsigned: &genesisTx.CreateAssetTx}
if err := tx.Initialize(genesisCodec); err != nil {
return ids.Empty, err
}
return tx.ID(), nil
}