-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathconvert.go
More file actions
671 lines (628 loc) · 23.2 KB
/
convert.go
File metadata and controls
671 lines (628 loc) · 23.2 KB
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
// / Copyright (C) 2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package blockchaincmd
import (
"encoding/hex"
"fmt"
"math/big"
"os"
"strings"
"time"
"github.com/ava-labs/avalanche-cli/pkg/blockchain"
"github.com/ava-labs/avalanche-cli/pkg/cobrautils"
"github.com/ava-labs/avalanche-cli/pkg/constants"
"github.com/ava-labs/avalanche-cli/pkg/contract"
"github.com/ava-labs/avalanche-cli/pkg/evm"
"github.com/ava-labs/avalanche-cli/pkg/keychain"
"github.com/ava-labs/avalanche-cli/pkg/localnet"
"github.com/ava-labs/avalanche-cli/pkg/models"
"github.com/ava-labs/avalanche-cli/pkg/networkoptions"
"github.com/ava-labs/avalanche-cli/pkg/node"
"github.com/ava-labs/avalanche-cli/pkg/prompts"
"github.com/ava-labs/avalanche-cli/pkg/subnet"
"github.com/ava-labs/avalanche-cli/pkg/txutils"
"github.com/ava-labs/avalanche-cli/pkg/utils"
"github.com/ava-labs/avalanche-cli/pkg/ux"
"github.com/ava-labs/avalanche-cli/pkg/vm"
blockchainSDK "github.com/ava-labs/avalanche-cli/sdk/blockchain"
validatorManagerSDK "github.com/ava-labs/avalanche-cli/sdk/validatormanager"
"github.com/ava-labs/avalanchego/api/info"
"github.com/ava-labs/avalanchego/config"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/units"
"github.com/ava-labs/avalanchego/vms/platformvm/txs"
"github.com/ethereum/go-ethereum/common"
"github.com/spf13/cobra"
)
// avalanche blockchain convert
func newConvertCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "convert [blockchainName]",
Short: "Converts a Subnet into a sovereign L1",
Long: `The blockchain convert command converts a Subnet into sovereign L1.
Sovereign L1s require bootstrap validators. avalanche blockchain convert command gives the option of:
- either using local machine as bootstrap validators (set the number of bootstrap validators using
--num-local-nodes flag, default is set to 1)
- or using remote nodes (we require the node's Node-ID and BLS info)`,
RunE: convertBlockchain,
PersistentPostRun: handlePostRun,
Args: cobrautils.ExactArgs(1),
}
networkoptions.AddNetworkFlagsToCmd(cmd, &globalNetworkFlags, true, networkoptions.DefaultSupportedNetworkOptions)
privateKeyFlags.SetFlagNames("blockchain-private-key", "blockchain-key", "blockchain-genesis-key")
privateKeyFlags.AddToCmd(cmd, "to fund validator manager initialization")
cmd.Flags().StringVarP(&keyName, "key", "k", "", "select the key to use [fuji/devnet convert to l1 tx only]")
cmd.Flags().StringSliceVar(&subnetAuthKeys, "auth-keys", nil, "control keys that will be used to authenticate convert to L1 tx")
cmd.Flags().StringVar(&outputTxPath, "output-tx-path", "", "file path of the convert to L1 tx (for multi-sig)")
cmd.Flags().BoolVarP(&useLedger, "ledger", "g", false, "use ledger instead of key (always true on mainnet, defaults to false on fuji/devnet)")
cmd.Flags().StringSliceVar(&ledgerAddresses, "ledger-addrs", []string{}, "use the given ledger addresses")
cmd.Flags().StringVar(&bootstrapValidatorsJSONFilePath, "bootstrap-filepath", "", "JSON file path that provides details about bootstrap validators, leave Node-ID and BLS values empty if using --generate-node-id=true")
cmd.Flags().BoolVar(&generateNodeID, "generate-node-id", false, "whether to create new node id for bootstrap validators (Node-ID and BLS values in bootstrap JSON file will be overridden if --bootstrap-filepath flag is used)")
cmd.Flags().StringSliceVar(&bootstrapEndpoints, "bootstrap-endpoints", nil, "take validator node info from the given endpoints")
cmd.Flags().BoolVar(&convertOnly, "convert-only", false, "avoid node track, restart and poa manager setup")
cmd.Flags().StringVar(&aggregatorLogLevel, "aggregator-log-level", constants.DefaultAggregatorLogLevel, "log level to use with signature aggregator")
cmd.Flags().BoolVar(&aggregatorLogToStdout, "aggregator-log-to-stdout", false, "use stdout for signature aggregator logs")
cmd.Flags().StringSliceVar(&aggregatorExtraEndpoints, "aggregator-extra-endpoints", nil, "endpoints for extra nodes that are needed in signature aggregation")
cmd.Flags().BoolVar(&aggregatorAllowPrivatePeers, "aggregator-allow-private-peers", true, "allow the signature aggregator to connect to peers with private IP")
cmd.Flags().BoolVar(&useLocalMachine, "use-local-machine", false, "use local machine as a blockchain validator")
cmd.Flags().IntVar(&numBootstrapValidators, "num-bootstrap-validators", 0, "(only if --generate-node-id is true) number of bootstrap validators to set up in sovereign L1 validator)")
cmd.Flags().Float64Var(
&deployBalanceAVAX,
"balance",
float64(constants.BootstrapValidatorBalanceNanoAVAX)/float64(units.Avax),
"set the AVAX balance of each bootstrap validator that will be used for continuous fee on P-Chain",
)
cmd.Flags().IntVar(&numLocalNodes, "num-local-nodes", 0, "number of nodes to be created on local machine")
cmd.Flags().StringVar(&changeOwnerAddress, "change-owner-address", "", "address that will receive change if node is no longer L1 validator")
cmd.Flags().Uint64Var(&poSMinimumStakeAmount, "pos-minimum-stake-amount", 1, "minimum stake amount")
cmd.Flags().Uint64Var(&poSMaximumStakeAmount, "pos-maximum-stake-amount", 1000, "maximum stake amount")
cmd.Flags().Uint64Var(&poSMinimumStakeDuration, "pos-minimum-stake-duration", constants.PoSL1MinimumStakeDurationSeconds, "minimum stake duration (in seconds)")
cmd.Flags().Uint16Var(&poSMinimumDelegationFee, "pos-minimum-delegation-fee", 1, "minimum delegation fee")
cmd.Flags().Uint8Var(&poSMaximumStakeMultiplier, "pos-maximum-stake-multiplier", 1, "maximum stake multiplier")
cmd.Flags().Uint64Var(&poSWeightToValueFactor, "pos-weight-to-value-factor", 1, "weight to value factor")
cmd.Flags().BoolVar(&partialSync, "partial-sync", true, "set primary network partial sync for new validators")
cmd.Flags().BoolVar(&createFlags.proofOfAuthority, "proof-of-authority", false, "use proof of authority(PoA) for validator management")
cmd.Flags().BoolVar(&createFlags.proofOfStake, "proof-of-stake", false, "use proof of stake(PoS) for validator management")
cmd.Flags().StringVar(&createFlags.validatorManagerOwner, "validator-manager-owner", "", "EVM address that controls Validator Manager Owner")
cmd.Flags().StringVar(&createFlags.proxyContractOwner, "proxy-contract-owner", "", "EVM address that controls ProxyAdmin for TransparentProxy of ValidatorManager contract")
cmd.Flags().Uint64Var(&createFlags.rewardBasisPoints, "reward-basis-points", 100, "(PoS only) reward basis points for PoS Reward Calculator")
cmd.Flags().StringVar(&validatorManagerAddress, "validator-manager-address", "", "validator manager address")
return cmd
}
func StartLocalMachine(
network models.Network,
sidecar models.Sidecar,
blockchainName string,
deployBalance,
availableBalance uint64,
) error {
var err error
if network.Kind == models.Local {
useLocalMachine = true
}
networkNameComponent := strings.ReplaceAll(strings.ToLower(network.Name()), " ", "-")
clusterName := fmt.Sprintf("%s-local-node-%s", blockchainName, networkNameComponent)
if clusterNameFlagValue != "" {
clusterName = clusterNameFlagValue
clusterConfig, err := app.GetClusterConfig(clusterName)
if err != nil {
return err
}
// check if cluster is local
if clusterConfig.Local {
useLocalMachine = true
if len(bootstrapEndpoints) == 0 {
bootstrapEndpoints, err = getLocalBootstrapEndpoints()
if err != nil {
return fmt.Errorf("error getting local host bootstrap endpoints: %w, "+
"please create your local node again and call blockchain deploy command again", err)
}
}
network = models.ConvertClusterToNetwork(network)
}
}
if numLocalNodes > 0 {
useLocalMachine = true
}
// ask user if we want to use local machine if cluster is not provided
if !useLocalMachine && clusterNameFlagValue == "" {
ux.Logger.PrintToUser("You can use your local machine as a bootstrap validator on the blockchain")
ux.Logger.PrintToUser("This means that you don't have to to set up a remote server on a cloud service (e.g. AWS / GCP) to be a validator on the blockchain.")
useLocalMachine, err = app.Prompt.CaptureYesNo("Do you want to use your local machine as a bootstrap validator?")
if err != nil {
return err
}
}
// default number of local machine nodes to be 1
// we set it here instead of at flag level so that we don't prompt if user wants to use local machine when they set numLocalNodes flag value
if useLocalMachine && numLocalNodes == 0 {
numLocalNodes = constants.DefaultNumberOfLocalMachineNodes
}
// if no cluster provided - we create one with fmt.Sprintf("%s-local-node-%s", blockchainName, networkNameComponent) name
if useLocalMachine && clusterNameFlagValue == "" {
if clusterExists, err := node.CheckClusterIsLocal(app, clusterName); err != nil {
return err
} else if clusterExists {
ux.Logger.PrintToUser("")
ux.Logger.PrintToUser(
logging.Red.Wrap("A local machine L1 deploy already exists for %s L1 and network %s"),
blockchainName,
network.Name(),
)
yes, err := app.Prompt.CaptureNoYes(
fmt.Sprintf("Do you want to overwrite the current local L1 deploy for %s?", blockchainName),
)
if err != nil {
return err
}
if !yes {
return nil
}
_ = node.DestroyLocalNode(app, clusterName)
}
requiredBalance := deployBalance * uint64(numLocalNodes)
if availableBalance < requiredBalance {
return fmt.Errorf(
"required balance for %d validators dynamic fee on PChain is %d but the given key has %d",
numLocalNodes,
requiredBalance,
availableBalance,
)
}
// stop local avalanchego process so that we can generate new local cluster
_ = node.StopLocalNode(app)
anrSettings := node.ANRSettings{}
avagoVersionSettings := node.AvalancheGoVersionSettings{}
// setup (install if needed) avalanchego binary
avagoVersion := userProvidedAvagoVersion
if userProvidedAvagoVersion == constants.DefaultAvalancheGoVersion && avagoBinaryPath == "" {
// nothing given: get avago version from RPC compat
avagoVersion, err = vm.GetLatestAvalancheGoByProtocolVersion(
app,
sidecar.RPCVersion,
constants.AvalancheGoCompatibilityURL,
)
if err != nil {
if err != vm.ErrNoAvagoVersion {
return err
}
avagoVersion = constants.LatestPreReleaseVersionTag
}
}
avagoBinaryPath, err := localnet.SetupAvalancheGoBinary(app, avagoVersion, avagoBinaryPath)
if err != nil {
return err
}
nodeConfig := map[string]interface{}{}
if app.AvagoNodeConfigExists(blockchainName) {
nodeConfig, err = utils.ReadJSON(app.GetAvagoNodeConfigPath(blockchainName))
if err != nil {
return err
}
}
if partialSync {
nodeConfig[config.PartialSyncPrimaryNetworkKey] = true
}
if network.Kind == models.Fuji {
globalNetworkFlags.UseFuji = true
}
if network.Kind == models.Mainnet {
globalNetworkFlags.UseMainnet = true
}
// anrSettings, avagoVersionSettings, globalNetworkFlags are empty
if err = node.StartLocalNode(
app,
clusterName,
avagoBinaryPath,
uint32(numLocalNodes),
nodeConfig,
anrSettings,
avagoVersionSettings,
network,
networkoptions.NetworkFlags{},
nil,
); err != nil {
return err
}
clusterNameFlagValue = clusterName
if len(bootstrapEndpoints) == 0 {
bootstrapEndpoints, err = getLocalBootstrapEndpoints()
if err != nil {
return fmt.Errorf("error getting local host bootstrap endpoints: %w, "+
"please create your local node again and call blockchain deploy command again", err)
}
}
}
return nil
}
func InitializeValidatorManager(blockchainName,
validatorManagerOwner string,
subnetID, blockchainID ids.ID,
network models.Network,
avaGoBootstrapValidators []*txs.ConvertSubnetToL1Validator,
pos bool,
validatorManagerAddrStr string,
) (bool, error) {
var err error
clusterName := clusterNameFlagValue
switch {
case useLocalMachine:
if err := node.TrackSubnetWithLocalMachine(
app,
clusterName,
blockchainName,
avagoBinaryPath,
); err != nil {
return false, err
}
default:
if clusterName != "" {
if err = node.SyncSubnet(app, clusterName, blockchainName, true, nil); err != nil {
return false, err
}
if err := node.WaitForHealthyCluster(app, clusterName, node.HealthCheckTimeout, node.HealthCheckPoolTime); err != nil {
return false, err
}
}
}
tracked := true
chainSpec := contract.ChainSpec{
BlockchainName: blockchainName,
}
_, genesisPrivateKey, err := contract.GetEVMSubnetPrefundedKey(
app,
network,
chainSpec,
)
if err != nil {
return tracked, err
}
rpcURL, _, err := contract.GetBlockchainEndpoints(
app,
network,
chainSpec,
true,
false,
)
if err != nil {
return tracked, err
}
client, err := evm.GetClient(rpcURL)
if err != nil {
return tracked, err
}
evm.WaitForChainID(client)
extraAggregatorPeers, err := blockchain.GetAggregatorExtraPeers(app, clusterName, aggregatorExtraEndpoints)
if err != nil {
return tracked, err
}
ownerAddress := common.HexToAddress(validatorManagerOwner)
subnetSDK := blockchainSDK.Subnet{
SubnetID: subnetID,
BlockchainID: blockchainID,
OwnerAddress: &ownerAddress,
RPC: rpcURL,
BootstrapValidators: avaGoBootstrapValidators,
}
aggregatorLogger, err := utils.NewLogger(
constants.SignatureAggregatorLogName,
aggregatorLogLevel,
constants.DefaultAggregatorLogLevel,
app.GetAggregatorLogDir(clusterName),
aggregatorLogToStdout,
ux.Logger.PrintToUser,
)
if err != nil {
return tracked, err
}
if pos {
ux.Logger.PrintToUser("Initializing Native Token Proof of Stake Validator Manager contract on blockchain %s ...", blockchainName)
if err := subnetSDK.InitializeProofOfStake(
network,
genesisPrivateKey,
extraAggregatorPeers,
aggregatorAllowPrivatePeers,
aggregatorLogger,
validatorManagerSDK.PoSParams{
MinimumStakeAmount: big.NewInt(int64(poSMinimumStakeAmount)),
MaximumStakeAmount: big.NewInt(int64(poSMaximumStakeAmount)),
MinimumStakeDuration: poSMinimumStakeDuration,
MinimumDelegationFee: poSMinimumDelegationFee,
MaximumStakeMultiplier: poSMaximumStakeMultiplier,
WeightToValueFactor: big.NewInt(int64(poSWeightToValueFactor)),
RewardCalculatorAddress: validatorManagerSDK.RewardCalculatorAddress,
},
validatorManagerAddrStr,
); err != nil {
return tracked, err
}
ux.Logger.GreenCheckmarkToUser("Proof of Stake Validator Manager contract successfully initialized on blockchain %s", blockchainName)
} else {
ux.Logger.PrintToUser("Initializing Proof of Authority Validator Manager contract on blockchain %s ...", blockchainName)
if err := subnetSDK.InitializeProofOfAuthority(
network,
genesisPrivateKey,
extraAggregatorPeers,
aggregatorAllowPrivatePeers,
aggregatorLogger,
validatorManagerAddrStr,
); err != nil {
return tracked, err
}
ux.Logger.GreenCheckmarkToUser("Proof of Authority Validator Manager contract successfully initialized on blockchain %s", blockchainName)
}
return tracked, nil
}
func convertSubnetToL1(
bootstrapValidators []models.SubnetValidator,
deployer *subnet.PublicDeployer,
subnetID, blockchainID ids.ID,
network models.Network,
chain string,
sidecar models.Sidecar,
controlKeysList,
subnetAuthKeysList []string,
validatorManagerAddressStr string,
) ([]*txs.ConvertSubnetToL1Validator, bool, error) {
avaGoBootstrapValidators, err := ConvertToAvalancheGoSubnetValidator(bootstrapValidators)
if err != nil {
return avaGoBootstrapValidators, false, err
}
deployer.CleanCacheWallet()
managerAddress := common.HexToAddress(validatorManagerAddressStr)
isFullySigned, convertL1TxID, tx, remainingSubnetAuthKeys, err := deployer.ConvertL1(
controlKeysList,
subnetAuthKeysList,
subnetID,
blockchainID,
managerAddress,
avaGoBootstrapValidators,
)
if err != nil {
ux.Logger.RedXToUser("error converting blockchain: %s. fix the issue and try again with a new convert cmd", err)
return avaGoBootstrapValidators, false, err
}
savePartialTx := !isFullySigned && err == nil
if savePartialTx {
if err := SaveNotFullySignedTx(
"ConvertSubnetToL1Tx",
tx,
chain,
subnetAuthKeys,
remainingSubnetAuthKeys,
outputTxPath,
false,
); err != nil {
return avaGoBootstrapValidators, savePartialTx, err
}
} else {
ux.Logger.PrintToUser("ConvertSubnetToL1Tx ID: %s", convertL1TxID)
_, err = ux.TimedProgressBar(
30*time.Second,
"Waiting for the Subnet to be converted into a sovereign L1 ...",
0,
)
if err != nil {
return avaGoBootstrapValidators, savePartialTx, err
}
}
ux.Logger.PrintToUser("")
setBootstrapValidatorValidationID(avaGoBootstrapValidators, bootstrapValidators, subnetID)
return avaGoBootstrapValidators, savePartialTx, app.UpdateSidecarNetworks(
&sidecar,
network,
subnetID,
blockchainID,
"",
"",
bootstrapValidators,
clusterNameFlagValue,
validatorManagerAddressStr,
)
}
// convertBlockchain is the cobra command run for converting subnets into sovereign L1
func convertBlockchain(_ *cobra.Command, args []string) error {
blockchainName := args[0]
chains, err := ValidateSubnetNameAndGetChains(args)
if err != nil {
return err
}
var bootstrapValidators []models.SubnetValidator
if bootstrapValidatorsJSONFilePath != "" {
bootstrapValidators, err = LoadBootstrapValidator(bootstrapValidatorsJSONFilePath)
if err != nil {
return err
}
}
chain := chains[0]
sidecar, err := app.LoadSidecar(chain)
if err != nil {
return fmt.Errorf("failed to load sidecar for later update: %w", err)
}
if outputTxPath != "" {
if _, err := os.Stat(outputTxPath); err == nil {
return fmt.Errorf("outputTxPath %q already exists", outputTxPath)
}
}
network, err := networkoptions.GetNetworkFromCmdLineFlags(
app,
"",
globalNetworkFlags,
true,
false,
networkoptions.DefaultSupportedNetworkOptions,
"",
)
if err != nil {
return err
}
clusterNameFlagValue = globalNetworkFlags.ClusterName
subnetID := sidecar.Networks[network.Name()].SubnetID
blockchainID := sidecar.Networks[network.Name()].BlockchainID
if validatorManagerAddress == "" {
validatorManagerAddressAddrFmt, err := app.Prompt.CaptureAddress("What is the address of the Validator Manager?")
if err != nil {
return err
}
validatorManagerAddress = validatorManagerAddressAddrFmt.String()
}
if err = promptValidatorManagementType(app, &sidecar); err != nil {
return err
}
if err := setSidecarValidatorManageOwner(&sidecar, createFlags); err != nil {
return err
}
sidecar.UpdateValidatorManagerAddress(network.Name(), validatorManagerAddress)
sidecar.Sovereign = true
fee := uint64(0)
kc, err := keychain.GetKeychainFromCmdLineFlags(
app,
constants.PayTxsFeesMsg,
network,
keyName,
useEwoq,
useLedger,
ledgerAddresses,
fee,
)
if err != nil {
return err
}
availableBalance, err := utils.GetNetworkBalance(kc.Addresses().List(), network.Endpoint)
if err != nil {
return err
}
deployBalance := uint64(deployBalanceAVAX * float64(units.Avax))
if changeOwnerAddress == "" {
// use provided key as change owner unless already set
if pAddr, err := kc.PChainFormattedStrAddresses(); err == nil && len(pAddr) > 0 {
changeOwnerAddress = pAddr[0]
ux.Logger.PrintToUser("Using [%s] to be set as a change owner for leftover AVAX", changeOwnerAddress)
}
}
if !generateNodeID {
if err = StartLocalMachine(network, sidecar, blockchainName, deployBalance, availableBalance); err != nil {
return err
}
}
switch {
case len(bootstrapEndpoints) > 0:
if changeOwnerAddress == "" {
changeOwnerAddress, err = blockchain.GetKeyForChangeOwner(app, network)
if err != nil {
return err
}
}
for _, endpoint := range bootstrapEndpoints {
infoClient := info.NewClient(endpoint)
ctx, cancel := utils.GetAPILargeContext()
defer cancel()
nodeID, proofOfPossession, err := infoClient.GetNodeID(ctx)
if err != nil {
return err
}
publicKey = "0x" + hex.EncodeToString(proofOfPossession.PublicKey[:])
pop = "0x" + hex.EncodeToString(proofOfPossession.ProofOfPossession[:])
bootstrapValidators = append(bootstrapValidators, models.SubnetValidator{
NodeID: nodeID.String(),
Weight: constants.BootstrapValidatorWeight,
Balance: deployBalance,
BLSPublicKey: publicKey,
BLSProofOfPossession: pop,
ChangeOwnerAddr: changeOwnerAddress,
})
}
case clusterNameFlagValue != "":
// for remote clusters we don't need to ask for bootstrap validators and can read it from filesystem
bootstrapValidators, err = getClusterBootstrapValidators(clusterNameFlagValue, network, deployBalance)
if err != nil {
return fmt.Errorf("error getting bootstrap validators from cluster %s: %w", clusterNameFlagValue, err)
}
default:
bootstrapValidators, err = promptBootstrapValidators(
network,
changeOwnerAddress,
numBootstrapValidators,
deployBalance,
availableBalance,
)
if err != nil {
return err
}
}
requiredBalance := deployBalance * uint64(len(bootstrapValidators))
if availableBalance < requiredBalance {
return fmt.Errorf(
"required balance for %d validators dynamic fee on PChain is %d but the given key has %d",
len(bootstrapValidators),
requiredBalance,
availableBalance,
)
}
kcKeys, err := kc.PChainFormattedStrAddresses()
if err != nil {
return err
}
// get keys for blockchain tx signing
_, controlKeys, threshold, err = txutils.GetOwners(network, subnetID)
if err != nil {
return err
}
// get keys for convertL1 tx signing
if subnetAuthKeys != nil {
if err := prompts.CheckSubnetAuthKeys(kcKeys, subnetAuthKeys, controlKeys, threshold); err != nil {
return err
}
} else {
subnetAuthKeys, err = prompts.GetSubnetAuthKeys(app.Prompt, kcKeys, controlKeys, threshold)
if err != nil {
return err
}
}
ux.Logger.PrintToUser("Your auth keys for add validator tx creation: %s", subnetAuthKeys)
// deploy to public network
deployer := subnet.NewPublicDeployer(app, kc, network)
avaGoBootstrapValidators, savePartialTx, err := convertSubnetToL1(
bootstrapValidators,
deployer,
subnetID,
blockchainID,
network,
chain,
sidecar,
controlKeys,
subnetAuthKeys,
validatorManagerAddress,
)
if err != nil {
return err
}
if savePartialTx {
return nil
}
if !convertOnly && !generateNodeID {
if _, err = InitializeValidatorManager(
blockchainName,
sidecar.ValidatorManagerOwner,
subnetID,
blockchainID,
network,
avaGoBootstrapValidators,
sidecar.ValidatorManagement == models.ProofOfStake,
validatorManagerAddress,
); err != nil {
return err
}
} else {
ux.Logger.GreenCheckmarkToUser("Converted blockchain successfully generated")
ux.Logger.PrintToUser("To finish conversion to sovereign L1, create the corresponding Avalanche node(s) with the provided Node ID and BLS Info")
ux.Logger.PrintToUser("Created Node ID and BLS Info can be found at %s", app.GetSidecarPath(blockchainName))
ux.Logger.PrintToUser("Once the Avalanche Node(s) are created and are tracking the blockchain, call `avalanche contract initValidatorManager %s` to finish conversion to sovereign L1", blockchainName)
}
ux.Logger.PrintToUser("")
ux.Logger.PrintToUser(logging.Green.Wrap("Your L1 is ready for on-chain interactions."))
ux.Logger.PrintToUser("")
ux.Logger.GreenCheckmarkToUser("Subnet is successfully converted to sovereign L1")
return nil
}