forked from ava-labs/avalanche-network-runner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.go
1505 lines (1382 loc) · 43.1 KB
/
blockchain.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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package local
import (
"context"
"encoding/base64"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/MetalBlockchain/metalgo/vms/platformvm/reward"
"github.com/MetalBlockchain/metalgo/vms/avm"
"github.com/MetalBlockchain/metalgo/vms/components/avax"
"github.com/MetalBlockchain/metalgo/vms/components/verify"
"github.com/MetalBlockchain/metalgo/wallet/chain/x"
xbuilder "github.com/MetalBlockchain/metalgo/wallet/chain/x/builder"
xsigner "github.com/MetalBlockchain/metalgo/wallet/chain/x/signer"
"github.com/MetalBlockchain/metal-network-runner/network"
"github.com/MetalBlockchain/metal-network-runner/network/node"
"github.com/MetalBlockchain/metal-network-runner/utils"
"github.com/MetalBlockchain/metalgo/api/admin"
"github.com/MetalBlockchain/metalgo/config"
"github.com/MetalBlockchain/metalgo/genesis"
"github.com/MetalBlockchain/metalgo/ids"
"github.com/MetalBlockchain/metalgo/utils/constants"
"github.com/MetalBlockchain/metalgo/utils/crypto/bls"
"github.com/MetalBlockchain/metalgo/utils/logging"
"github.com/MetalBlockchain/metalgo/utils/set"
"github.com/MetalBlockchain/metalgo/vms/platformvm"
"github.com/MetalBlockchain/metalgo/vms/platformvm/signer"
"github.com/MetalBlockchain/metalgo/vms/platformvm/txs"
"github.com/MetalBlockchain/metalgo/vms/secp256k1fx"
"github.com/MetalBlockchain/metalgo/wallet/chain/p"
pbuilder "github.com/MetalBlockchain/metalgo/wallet/chain/p/builder"
psigner "github.com/MetalBlockchain/metalgo/wallet/chain/p/signer"
"github.com/MetalBlockchain/metalgo/wallet/subnet/primary"
"github.com/MetalBlockchain/metalgo/wallet/subnet/primary/common"
"go.uber.org/zap"
"golang.org/x/exp/maps"
)
const (
// offset of validation start from current time
validationStartOffset = 20 * time.Second
permissionlessValidationStartOffset = 30 * time.Second
// duration for primary network validators
validationDuration = 365 * 24 * time.Hour
// weight assigned to subnet validators
subnetValidatorsWeight = 1000
// check period for blockchain logs while waiting for custom chains to be ready
blockchainLogPullFrequency = time.Second
// check period while waiting for all validators to be ready
waitForValidatorsPullFrequency = time.Second
defaultTimeout = time.Minute
stakingMinimumLeadTime = 25 * time.Second
minStakeDuration = 24 * 14 * time.Hour
)
var (
errAborted = errors.New("aborted")
defaultPoll = common.WithPollFrequency(100 * time.Millisecond)
)
type blockchainInfo struct {
chainName string
vmID ids.ID
subnetID ids.ID
blockchainID ids.ID
}
// get node with minimum port number
func (ln *localNetwork) getNode() node.Node {
var node node.Node
minAPIPortNumber := uint16(MaxPort)
for _, n := range ln.nodes {
if n.paused {
continue
}
if n.GetAPIPort() < minAPIPortNumber {
minAPIPortNumber = n.GetAPIPort()
node = n
}
}
return node
}
// get node client URI for an arbitrary node in the network
func (ln *localNetwork) getClientURI() (string, error) { //nolint
node := ln.getNode()
clientURI := fmt.Sprintf("http://%s:%d", node.GetURL(), node.GetAPIPort())
ln.log.Info("getClientURI",
zap.String("nodeName", node.GetName()),
zap.String("uri", clientURI))
return clientURI, nil
}
func (ln *localNetwork) CreateBlockchains(
ctx context.Context,
chainSpecs []network.BlockchainSpec, // VM name + genesis bytes
) ([]ids.ID, error) {
ln.lock.Lock()
defer ln.lock.Unlock()
chainInfos, err := ln.installCustomChains(ctx, chainSpecs)
if err != nil {
return nil, err
}
if err := ln.waitForCustomChainsReady(ctx, chainInfos); err != nil {
return nil, err
}
if err := ln.RegisterBlockchainAliases(ctx, chainInfos, chainSpecs); err != nil {
return nil, err
}
chainIDs := []ids.ID{}
for _, chainInfo := range chainInfos {
chainIDs = append(chainIDs, chainInfo.blockchainID)
}
return chainIDs, nil
}
// if alias is defined in blockchain-specs, registers an alias for the previously created blockchain
func (ln *localNetwork) RegisterBlockchainAliases(
ctx context.Context,
chainInfos []blockchainInfo,
chainSpecs []network.BlockchainSpec,
) error {
fmt.Println()
ln.log.Info(logging.Blue.Wrap(logging.Bold.Wrap("registering blockchain aliases")))
for i, chainSpec := range chainSpecs {
if chainSpec.BlockchainAlias == "" {
continue
}
blockchainAlias := chainSpec.BlockchainAlias
chainID := chainInfos[i].blockchainID.String()
ln.log.Info("registering blockchain alias",
zap.String("alias", blockchainAlias),
zap.String("chain-id", chainID))
for nodeName, node := range ln.nodes {
if node.paused {
continue
}
if err := node.client.AdminAPI().AliasChain(ctx, chainID, blockchainAlias); err != nil {
return fmt.Errorf("failure to register blockchain alias %v on node %v: %w", blockchainAlias, nodeName, err)
}
}
}
return nil
}
func (ln *localNetwork) RemoveSubnetValidators(
ctx context.Context,
removeSubnetSpecs []network.RemoveSubnetValidatorSpec,
) error {
ln.lock.Lock()
defer ln.lock.Unlock()
return ln.removeSubnetValidators(ctx, removeSubnetSpecs)
}
func (ln *localNetwork) AddPermissionlessValidators(
ctx context.Context,
validatorSpec []network.PermissionlessValidatorSpec,
) error {
ln.lock.Lock()
defer ln.lock.Unlock()
return ln.addPermissionlessValidators(ctx, validatorSpec)
}
func (ln *localNetwork) TransformSubnet(
ctx context.Context,
elasticSubnetConfig []network.ElasticSubnetSpec,
) ([]ids.ID, []ids.ID, error) {
ln.lock.Lock()
defer ln.lock.Unlock()
return ln.transformToElasticSubnets(ctx, elasticSubnetConfig)
}
func (ln *localNetwork) CreateSubnets(
ctx context.Context,
subnetSpecs []network.SubnetSpec,
) ([]ids.ID, error) {
ln.lock.Lock()
defer ln.lock.Unlock()
return ln.installSubnets(ctx, subnetSpecs)
}
// provisions local cluster and install custom chains if applicable
// assumes the local cluster is already set up and healthy
func (ln *localNetwork) installCustomChains(
ctx context.Context,
chainSpecs []network.BlockchainSpec,
) ([]blockchainInfo, error) {
fmt.Println()
ln.log.Info(logging.Blue.Wrap(logging.Bold.Wrap("create and install custom chains")))
clientURI, err := ln.getClientURI()
if err != nil {
return nil, err
}
platformCli := platformvm.NewClient(clientURI)
// wallet needs txs for all previously created subnets
var preloadTXs []ids.ID
for _, chainSpec := range chainSpecs {
// if subnet id for the blockchain is specified, we need to add the subnet id
// tx info to the wallet so blockchain creation does not fail
// if subnet id is not specified, a new subnet will later be created by using the wallet,
// and the wallet will obtain the tx info at that moment
if chainSpec.SubnetID != nil {
subnetID, err := ids.FromString(*chainSpec.SubnetID)
if err != nil {
return nil, err
}
preloadTXs = append(preloadTXs, subnetID)
}
}
w, err := newWallet(ctx, clientURI, preloadTXs)
if err != nil {
return nil, err
}
// get subnet specs for all new subnets to create
// for the list of requested blockchains, we take those that have undefined subnet id
// and use the provided subnet spec. if not given, use an empty default subnet spec
// that subnets will be created and later on assigned to the blockchain requests
subnetSpecs := []network.SubnetSpec{}
for _, chainSpec := range chainSpecs {
if chainSpec.SubnetID == nil {
if chainSpec.SubnetSpec == nil {
subnetSpecs = append(subnetSpecs, network.SubnetSpec{})
} else {
subnetSpecs = append(subnetSpecs, *chainSpec.SubnetSpec)
}
}
}
// if no participants are given for a new subnet, assume all nodes should be participants
allNodeNames := maps.Keys(ln.nodes)
sort.Strings(allNodeNames)
for i := range subnetSpecs {
if len(subnetSpecs[i].Participants) == 0 {
subnetSpecs[i].Participants = allNodeNames
}
}
// create new nodes
for _, subnetSpec := range subnetSpecs {
for _, nodeName := range subnetSpec.Participants {
_, ok := ln.nodes[nodeName]
if !ok {
ln.log.Info(logging.Green.Wrap(fmt.Sprintf("adding new participant %s", nodeName)))
if _, err := ln.addNode(node.Config{Name: nodeName}); err != nil {
return nil, err
}
}
}
}
if err := ln.healthy(ctx); err != nil {
return nil, err
}
// just ensure all nodes are primary validators (so can be subnet validators)
if err := ln.addPrimaryValidators(ctx, platformCli, w); err != nil {
return nil, err
}
// create missing subnets
subnetIDs, err := createSubnets(ctx, uint32(len(subnetSpecs)), w, ln.log)
if err != nil {
return nil, err
}
if err := ln.setSubnetConfigFiles(subnetIDs, subnetSpecs); err != nil {
return nil, err
}
// assign created subnets to blockchain requests with undefined subnet id
j := 0
for i := range chainSpecs {
if chainSpecs[i].SubnetID == nil {
subnetIDStr := subnetIDs[j].String()
chainSpecs[i].SubnetID = &subnetIDStr
j++
}
}
// wait for nodes to be primary validators before trying to add them as subnet ones
if err = ln.waitPrimaryValidators(ctx, platformCli); err != nil {
return nil, err
}
if err = ln.addSubnetValidators(ctx, platformCli, w, subnetIDs, subnetSpecs); err != nil {
return nil, err
}
blockchainTxs, err := createBlockchainTxs(ctx, chainSpecs, w, ln.log)
if err != nil {
return nil, err
}
nodesToRestartForBlockchainConfigUpdate, err := ln.setBlockchainConfigFiles(ctx, chainSpecs, blockchainTxs, subnetIDs, subnetSpecs, ln.log)
if err != nil {
return nil, err
}
if len(subnetSpecs) > 0 || len(nodesToRestartForBlockchainConfigUpdate) > 0 {
// we need to restart if there are new subnets or if there are new network config files
// add missing subnets, restarting network and waiting for subnet validation to start
if err := ln.restartNodes(ctx, subnetIDs, subnetSpecs, nil, nil, nodesToRestartForBlockchainConfigUpdate); err != nil {
return nil, err
}
clientURI, err = ln.getClientURI()
if err != nil {
return nil, err
}
w.reload(clientURI)
}
// refresh vm list
if err := ln.reloadVMPlugins(ctx); err != nil {
return nil, err
}
if err = ln.waitSubnetValidators(ctx, platformCli, subnetIDs, subnetSpecs); err != nil {
return nil, err
}
// create blockchain from txs before spending more utxos
if err := ln.createBlockchains(ctx, chainSpecs, blockchainTxs, w, ln.log); err != nil {
return nil, err
}
chainInfos := make([]blockchainInfo, len(chainSpecs))
for i, chainSpec := range chainSpecs {
vmID, err := utils.VMID(chainSpec.VMName)
if err != nil {
return nil, err
}
subnetID, err := ids.FromString(*chainSpec.SubnetID)
if err != nil {
return nil, err
}
chainInfos[i] = blockchainInfo{
// we keep a record of VM name in blockchain name field,
// as there is no way to recover VM name from VM ID
chainName: chainSpec.VMName,
vmID: vmID,
subnetID: subnetID,
blockchainID: blockchainTxs[i].ID(),
}
}
return chainInfos, nil
}
func (ln *localNetwork) installSubnets(
ctx context.Context,
subnetSpecs []network.SubnetSpec,
) ([]ids.ID, error) {
fmt.Println()
ln.log.Info(logging.Blue.Wrap(logging.Bold.Wrap("create subnets")))
clientURI, err := ln.getClientURI()
if err != nil {
return nil, err
}
platformCli := platformvm.NewClient(clientURI)
w, err := newWallet(ctx, clientURI, []ids.ID{})
if err != nil {
return nil, err
}
// if no participants are given, assume all nodes should be participants
allNodeNames := maps.Keys(ln.nodes)
sort.Strings(allNodeNames)
for i := range subnetSpecs {
if len(subnetSpecs[i].Participants) == 0 {
subnetSpecs[i].Participants = allNodeNames
}
}
// create new nodes
for _, subnetSpec := range subnetSpecs {
for _, nodeName := range subnetSpec.Participants {
_, ok := ln.nodes[nodeName]
if !ok {
ln.log.Info(logging.Green.Wrap(fmt.Sprintf("adding new participant %s", nodeName)))
if _, err := ln.addNode(node.Config{Name: nodeName}); err != nil {
return nil, err
}
}
}
}
if err := ln.healthy(ctx); err != nil {
return nil, err
}
// just ensure all nodes are primary validators (so can be subnet validators)
if err := ln.addPrimaryValidators(ctx, platformCli, w); err != nil {
return nil, err
}
subnetIDs, err := createSubnets(ctx, uint32(len(subnetSpecs)), w, ln.log)
if err != nil {
return nil, err
}
if err := ln.setSubnetConfigFiles(subnetIDs, subnetSpecs); err != nil {
return nil, err
}
// wait for nodes to be primary validators before trying to add them as subnet ones
if err = ln.waitPrimaryValidators(ctx, platformCli); err != nil {
return nil, err
}
if err = ln.addSubnetValidators(ctx, platformCli, w, subnetIDs, subnetSpecs); err != nil {
return nil, err
}
if err := ln.restartNodes(ctx, subnetIDs, subnetSpecs, nil, nil, nil); err != nil {
return nil, err
}
if err = ln.waitSubnetValidators(ctx, platformCli, subnetIDs, subnetSpecs); err != nil {
return nil, err
}
return subnetIDs, nil
}
func (ln *localNetwork) getSubnetValidatorsNodenames(
ctx context.Context,
subnetID ids.ID,
) ([]string, error) {
clientURI, err := ln.getClientURI()
if err != nil {
return nil, err
}
platformCli := platformvm.NewClient(clientURI)
cctx, cancel := createDefaultCtx(ctx)
vs, err := platformCli.GetCurrentValidators(cctx, subnetID, nil)
cancel()
if err != nil {
return nil, err
}
nodeNames := []string{}
for _, v := range vs {
for nodeName, node := range ln.nodes {
if v.NodeID == node.GetNodeID() {
nodeNames = append(nodeNames, nodeName)
}
}
}
if len(nodeNames) != len(vs) {
return nil, fmt.Errorf("not all validators for subnet %s are present in network", subnetID.String())
}
return nodeNames, nil
}
func (ln *localNetwork) waitForCustomChainsReady(
ctx context.Context,
chainInfos []blockchainInfo,
) error {
fmt.Println()
ln.log.Info(logging.Blue.Wrap(logging.Bold.Wrap("waiting for custom chains to report healthy...")))
if err := ln.healthy(ctx); err != nil {
return err
}
for _, chainInfo := range chainInfos {
nodeNames, err := ln.getSubnetValidatorsNodenames(ctx, chainInfo.subnetID)
if err != nil {
return err
}
for _, nodeName := range nodeNames {
node := ln.nodes[nodeName]
if node.paused {
continue
}
ln.log.Info("inspecting node log directory for custom chain logs", zap.String("log-dir", node.GetLogsDir()), zap.String("node-name", nodeName))
p := filepath.Join(node.GetLogsDir(), chainInfo.blockchainID.String()+".log")
ln.log.Info("checking log",
zap.String("vm-ID", chainInfo.vmID.String()),
zap.String("subnet-ID", chainInfo.subnetID.String()),
zap.String("blockchain-ID", chainInfo.blockchainID.String()),
zap.String("path", p),
)
for {
if _, err := os.Stat(p); err == nil {
ln.log.Info("found the log", zap.String("path", p))
break
}
ln.log.Info("log not found yet, retrying...",
zap.String("vm-ID", chainInfo.vmID.String()),
zap.String("subnet-ID", chainInfo.subnetID.String()),
zap.String("blockchain-ID", chainInfo.blockchainID.String()),
)
select {
case <-ln.onStopCh:
return errAborted
case <-ctx.Done():
return ctx.Err()
case <-time.After(blockchainLogPullFrequency):
}
}
}
}
fmt.Println()
ln.log.Info(logging.Green.Wrap("all custom chains are running!!!"))
fmt.Println()
ln.log.Info(logging.Green.Wrap(logging.Bold.Wrap("all custom chains are ready on RPC server-side -- network-runner RPC client can poll and query the cluster status")))
return nil
}
func (ln *localNetwork) restartNodes(
ctx context.Context,
subnetIDs []ids.ID,
subnetSpecs []network.SubnetSpec,
validatorSpecs []network.PermissionlessValidatorSpec,
removeValidatorSpecs []network.RemoveSubnetValidatorSpec,
nodesToRestartForBlockchainConfigUpdate set.Set[string],
) (err error) {
if (subnetSpecs != nil && validatorSpecs != nil) || (subnetSpecs != nil && removeValidatorSpecs != nil) ||
(validatorSpecs != nil && removeValidatorSpecs != nil) {
return errors.New("only one type of spec between subnet specs, add permissionless validator specs and " +
"remove validator specs can be supplied at one time")
}
fmt.Println()
ln.log.Info(logging.Blue.Wrap(logging.Bold.Wrap("restarting network")))
nodeNames := maps.Keys(ln.nodes)
sort.Strings(nodeNames)
for _, nodeName := range nodeNames {
node := ln.nodes[nodeName]
// delete node specific flag so as to use default one
nodeConfig := node.GetConfig()
previousTrackedSubnets := ""
previousTrackedSubnetsIntf, ok := nodeConfig.Flags[config.TrackSubnetsKey]
if ok {
previousTrackedSubnets, ok = previousTrackedSubnetsIntf.(string)
if !ok {
return fmt.Errorf("expected node config %s to have type string obtained %T", config.TrackSubnetsKey, previousTrackedSubnetsIntf)
}
}
trackSubnetIDsSet := set.Set[string]{}
if previousTrackedSubnets != "" {
for _, s := range strings.Split(previousTrackedSubnets, ",") {
trackSubnetIDsSet.Add(s)
}
}
needsRestart := false
for _, validatorSpec := range validatorSpecs {
if validatorSpec.NodeName == node.name {
trackSubnetIDsSet.Add(validatorSpec.SubnetID)
needsRestart = true
}
}
for _, removeValidatorSpec := range removeValidatorSpecs {
for _, toRemoveNode := range removeValidatorSpec.NodeNames {
if toRemoveNode == node.name {
trackSubnetIDsSet.Remove(removeValidatorSpec.SubnetID)
needsRestart = true
}
}
}
for i, subnetID := range subnetIDs {
for _, participant := range subnetSpecs[i].Participants {
if participant == nodeName {
trackSubnetIDsSet.Add(subnetID.String())
needsRestart = true
}
}
}
trackSubnetIDs := trackSubnetIDsSet.List()
sort.Strings(trackSubnetIDs)
tracked := strings.Join(trackSubnetIDs, ",")
nodeConfig.Flags[config.TrackSubnetsKey] = tracked
if subnetSpecs != nil {
if nodesToRestartForBlockchainConfigUpdate.Contains(nodeName) {
needsRestart = true
}
}
if !needsRestart {
continue
}
if node.paused {
continue
}
if removeValidatorSpecs != nil {
ln.log.Info(logging.Green.Wrap(fmt.Sprintf("restarting node %s to stop tracking subnets %s", nodeName, tracked)))
} else {
ln.log.Info(logging.Green.Wrap(fmt.Sprintf("restarting node %s to track subnets %s", nodeName, tracked)))
}
if err := ln.restartNode(ctx, nodeName, "", "", "", nil, nil, nil); err != nil {
return err
}
}
if err := ln.healthy(ctx); err != nil {
return err
}
return nil
}
type wallet struct {
addr ids.ShortID
pWallet p.Wallet
pBackend p.Backend
pBuilder pbuilder.Builder
pSigner psigner.Signer
pContext *pbuilder.Context
xContext *xbuilder.Context
xWallet x.Wallet
}
func newWallet(
ctx context.Context,
uri string,
preloadTXs []ids.ID,
) (*wallet, error) {
kc := secp256k1fx.NewKeychain(genesis.EWOQKey)
state, err := primary.FetchState(ctx, uri, kc.Addresses())
if err != nil {
return nil, err
}
pClient := platformvm.NewClient(uri)
pTXs := make(map[ids.ID]*txs.Tx)
for _, id := range preloadTXs {
txBytes, err := pClient.GetTx(ctx, id)
if err != nil {
return nil, err
}
tx, err := txs.Parse(txs.Codec, txBytes)
if err != nil {
return nil, err
}
pTXs[id] = tx
}
pUTXOs := common.NewChainUTXOs(constants.PlatformChainID, state.UTXOs)
xChainID := state.XCTX.BlockchainID
xUTXOs := common.NewChainUTXOs(xChainID, state.UTXOs)
var w wallet
w.xContext, w.pContext = state.XCTX, state.PCTX
w.addr = genesis.EWOQKey.PublicKey().Address()
w.pBackend = p.NewBackend(state.PCTX, pUTXOs, pTXs)
w.pBuilder = pbuilder.New(kc.Addresses(), state.PCTX, w.pBackend)
w.pSigner = psigner.New(kc, w.pBackend)
w.pWallet = p.NewWallet(w.pBuilder, w.pSigner, pClient, w.pBackend)
xBackend := x.NewBackend(state.XCTX, xUTXOs)
xBuilder := xbuilder.New(kc.Addresses(), state.XCTX, xBackend)
xSigner := xsigner.New(kc, xBackend)
xClient := avm.NewClient(uri, "X")
w.xWallet = x.NewWallet(xBuilder, xSigner, xClient, xBackend)
return &w, nil
}
func (w *wallet) reload(uri string) {
pClient := platformvm.NewClient(uri)
w.pWallet = p.NewWallet(w.pBuilder, w.pSigner, pClient, w.pBackend)
}
// add all nodes as validators of the primary network, in case they are not
// the validation starts as soon as possible and its duration is as long as possible, that is,
// it is set to max accepted duration by metalgo
func (ln *localNetwork) addPrimaryValidators(
ctx context.Context,
platformCli platformvm.Client,
w *wallet,
) error {
ln.log.Info(logging.Green.Wrap("adding the nodes as primary network validators"))
// ref. https://docs.metalblockchain.org/build/metalgo-apis/p-chain/#platformgetcurrentvalidators
cctx, cancel := createDefaultCtx(ctx)
vdrs, err := platformCli.GetCurrentValidators(cctx, constants.PrimaryNetworkID, nil)
cancel()
if err != nil {
return err
}
curValidators := set.Set[ids.NodeID]{}
for _, v := range vdrs {
curValidators.Add(v.NodeID)
}
for nodeName, node := range ln.nodes {
nodeID := node.GetNodeID()
if curValidators.Contains(nodeID) {
continue
}
// Prepare node BLS PoP
// It is important to note that this will ONLY register BLS signers for
// nodes registered AFTER genesis.
blsKeyBytes, err := base64.StdEncoding.DecodeString(node.GetConfig().StakingSigningKey)
if err != nil {
return err
}
blsSk, err := bls.SecretKeyFromBytes(blsKeyBytes)
if err != nil {
return err
}
proofOfPossession := signer.NewProofOfPossession(blsSk)
cctx, cancel = createDefaultCtx(ctx)
txID, err := w.pWallet.IssueAddPermissionlessValidatorTx(
&txs.SubnetValidator{
Validator: txs.Validator{
NodeID: nodeID,
Start: uint64(time.Now().Add(validationStartOffset).Unix()),
End: uint64(time.Now().Add(validationDuration).Unix()),
Wght: genesis.LocalParams.MinValidatorStake,
},
Subnet: ids.Empty,
},
proofOfPossession,
w.pContext.AVAXAssetID,
&secp256k1fx.OutputOwners{
Threshold: 1,
Addrs: []ids.ShortID{w.addr},
},
&secp256k1fx.OutputOwners{
Threshold: 1,
Addrs: []ids.ShortID{w.addr},
},
10*10000, // 10% fee percent, times 10000 to make it as shares
common.WithContext(cctx),
)
cancel()
if err != nil {
return fmt.Errorf("P-Wallet Tx Error %s %w, node ID %s", "IssueAddPermissionlessValidatorTx", err, nodeID.String())
}
ln.log.Info("added node as primary subnet validator", zap.String("node-name", nodeName), zap.String("node-ID", nodeID.String()), zap.String("tx-ID", txID.ID().String()))
}
return nil
}
func getXChainAssetID(ctx context.Context, w *wallet, tokenName string, tokenSymbol string, maxSupply uint64) (ids.ID, error) {
owner := &secp256k1fx.OutputOwners{
Threshold: 1,
Addrs: []ids.ShortID{
w.addr,
},
}
cctx, cancel := createDefaultCtx(ctx)
defer cancel()
createAssetTx, err := w.xWallet.IssueCreateAssetTx(
tokenName,
tokenSymbol,
9, // denomination for UI purposes only in explorer
map[uint32][]verify.State{
0: {
&secp256k1fx.TransferOutput{
Amt: maxSupply,
OutputOwners: *owner,
},
},
},
common.WithContext(cctx),
defaultPoll,
)
if err != nil {
return ids.Empty, err
}
return createAssetTx.ID(), nil
}
func exportXChainToPChain(ctx context.Context, w *wallet, owner *secp256k1fx.OutputOwners, subnetAssetID ids.ID, assetAmount uint64) error {
cctx, cancel := createDefaultCtx(ctx)
defer cancel()
_, err := w.xWallet.IssueExportTx(
ids.Empty,
[]*avax.TransferableOutput{
{
Asset: avax.Asset{
ID: subnetAssetID,
},
Out: &secp256k1fx.TransferOutput{
Amt: assetAmount,
OutputOwners: *owner,
},
},
},
common.WithContext(cctx),
defaultPoll,
)
return err
}
func importPChainFromXChain(ctx context.Context, w *wallet, owner *secp256k1fx.OutputOwners) error {
pWallet := w.pWallet
cctx, cancel := createDefaultCtx(ctx)
defer cancel()
_, err := pWallet.IssueImportTx(
w.xContext.BlockchainID,
owner,
common.WithContext(cctx),
defaultPoll,
)
return err
}
func (ln *localNetwork) removeSubnetValidators(
ctx context.Context,
removeSubnetSpecs []network.RemoveSubnetValidatorSpec,
) error {
ln.log.Info("removing subnet validator tx")
removeSubnetSpecIDs := make([]ids.ID, len(removeSubnetSpecs))
clientURI, err := ln.getClientURI()
if err != nil {
return err
}
platformCli := platformvm.NewClient(clientURI)
// wallet needs txs for all previously created subnets
preloadTXs := make([]ids.ID, len(removeSubnetSpecs))
for i, removeSubnetSpec := range removeSubnetSpecs {
subnetID, err := ids.FromString(removeSubnetSpec.SubnetID)
if err != nil {
return err
}
preloadTXs[i] = subnetID
}
w, err := newWallet(ctx, clientURI, preloadTXs)
if err != nil {
return err
}
ln.log.Info(logging.Green.Wrap("removing the nodes as subnet validators"))
for i, subnetSpec := range removeSubnetSpecs {
subnetID, err := ids.FromString(subnetSpec.SubnetID)
if err != nil {
return err
}
cctx, cancel := createDefaultCtx(ctx)
vs, err := platformCli.GetCurrentValidators(cctx, subnetID, nil)
cancel()
if err != nil {
return err
}
subnetValidators := set.Set[ids.NodeID]{}
for _, v := range vs {
subnetValidators.Add(v.NodeID)
}
toRemoveNodes := subnetSpec.NodeNames
for _, nodeName := range toRemoveNodes {
node, b := ln.nodes[nodeName]
if !b {
return fmt.Errorf("node %s is not in network nodes", nodeName)
}
nodeID := node.GetNodeID()
if isValidator := subnetValidators.Contains(nodeID); !isValidator {
return fmt.Errorf("node %s is currently not a subnet validator of subnet %s", nodeName, subnetID.String())
}
cctx, cancel := createDefaultCtx(ctx)
txID, err := w.pWallet.IssueRemoveSubnetValidatorTx(
nodeID,
subnetID,
common.WithContext(cctx),
defaultPoll,
)
cancel()
if err != nil {
return fmt.Errorf("P-Wallet Tx Error %s %w, node ID %s, subnetID %s", "IssueRemoveSubnetValidatorTx", err, nodeID.String(), subnetID.String())
}
ln.log.Info("removed node as subnet validator",
zap.String("node-name", nodeName),
zap.String("node-ID", nodeID.String()),
zap.String("subnet-ID", subnetID.String()),
zap.String("tx-ID", txID.ID().String()),
)
removeSubnetSpecIDs[i] = txID.ID()
}
}
return ln.restartNodes(ctx, nil, nil, nil, removeSubnetSpecs, nil)
}
func (ln *localNetwork) addPermissionlessValidators(
ctx context.Context,
validatorSpecs []network.PermissionlessValidatorSpec,
) error {
ln.log.Info("adding permissionless validator tx")
clientURI, err := ln.getClientURI()
if err != nil {
return err
}
platformCli := platformvm.NewClient(clientURI)
// wallet needs txs for all previously created subnets
preloadTXs := make([]ids.ID, len(validatorSpecs))
for i, validatorSpec := range validatorSpecs {
subnetID, err := ids.FromString(validatorSpec.SubnetID)
if err != nil {
return err
}
preloadTXs[i] = subnetID
}
w, err := newWallet(ctx, clientURI, preloadTXs)
if err != nil {
return err
}
owner := &secp256k1fx.OutputOwners{
Threshold: 1,
Addrs: []ids.ShortID{
w.addr,
},
}
// create new nodes
for _, validatorSpec := range validatorSpecs {
_, ok := ln.nodes[validatorSpec.NodeName]
if !ok {
ln.log.Info(logging.Green.Wrap(fmt.Sprintf("adding new participant %s", validatorSpec.NodeName)))
if _, err := ln.addNode(node.Config{Name: validatorSpec.NodeName}); err != nil {
return err
}
}
}
if err := ln.healthy(ctx); err != nil {
return err
}
// just ensure all nodes are primary validators (so can be subnet validators)
if err := ln.addPrimaryValidators(ctx, platformCli, w); err != nil {
return err
}
// wait for nodes to be primary validators before trying to add them as subnet ones
if err = ln.waitPrimaryValidators(ctx, platformCli); err != nil {
return err
}
cctx, cancel := createDefaultCtx(ctx)
vs, err := platformCli.GetCurrentValidators(cctx, constants.PrimaryNetworkID, nil)
cancel()
if err != nil {
return err
}
primaryValidatorsEndtime := make(map[ids.NodeID]time.Time)
for _, v := range vs {
primaryValidatorsEndtime[v.NodeID] = time.Unix(int64(v.EndTime), 0)
}
for _, validatorSpec := range validatorSpecs {
ln.log.Info(logging.Green.Wrap("adding permissionless validator"), zap.String("node ", validatorSpec.NodeName))
cctx, cancel := createDefaultCtx(ctx)
validatorNodeID := ln.nodes[validatorSpec.NodeName].nodeID
subnetID, err := ids.FromString(validatorSpec.SubnetID)
if err != nil {
return err
}
assetID, err := ids.FromString(validatorSpec.AssetID)
if err != nil {
return err
}
var startTime uint64
var endTime uint64
if validatorSpec.StartTime.IsZero() {
startTime = uint64(time.Now().Add(permissionlessValidationStartOffset).Unix())
} else {
startTime = uint64(validatorSpec.StartTime.Unix())
}
if validatorSpec.StakeDuration == 0 {
endTime = uint64(primaryValidatorsEndtime[validatorNodeID].Unix())
} else {
endTime = uint64(validatorSpec.StartTime.Add(validatorSpec.StakeDuration).Unix())
}
txID, err := w.pWallet.IssueAddPermissionlessValidatorTx(