-
Notifications
You must be signed in to change notification settings - Fork 55
/
create_devnet.go
286 lines (269 loc) · 9.69 KB
/
create_devnet.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
// Copyright (C) 2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package nodecmd
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/exp/slices"
"github.com/ava-labs/avalanche-cli/pkg/ansible"
"github.com/ava-labs/avalanche-cli/pkg/constants"
"github.com/ava-labs/avalanche-cli/pkg/key"
"github.com/ava-labs/avalanche-cli/pkg/models"
"github.com/ava-labs/avalanche-cli/pkg/ssh"
"github.com/ava-labs/avalanche-cli/pkg/utils"
"github.com/ava-labs/avalanche-cli/pkg/ux"
"github.com/ava-labs/avalanchego/config"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
"github.com/ava-labs/avalanchego/utils/formatting"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/vms/platformvm/signer"
coreth_params "github.com/ava-labs/coreth/params"
"golang.org/x/exp/maps"
)
// difference between unlock schedule locktime and startime in original genesis
const (
genesisLocktimeStartimeDelta = 2836800
hexa0Str = "0x0"
defaultLocalCChainFundedAddress = "8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC"
defaultLocalCChainFundedBalance = "0x295BE96E64066972000000"
allocationCommonEthAddress = "0xb3d82b1367d362de99ab59a658165aff520cbd4d"
)
func generateCustomCchainGenesis() ([]byte, error) {
cChainGenesisMap := map[string]interface{}{}
cChainGenesisMap["config"] = coreth_params.AvalancheLocalChainConfig
cChainGenesisMap["nonce"] = hexa0Str
cChainGenesisMap["timestamp"] = hexa0Str
cChainGenesisMap["extraData"] = "0x00"
cChainGenesisMap["gasLimit"] = "0x5f5e100"
cChainGenesisMap["difficulty"] = hexa0Str
cChainGenesisMap["mixHash"] = "0x0000000000000000000000000000000000000000000000000000000000000000"
cChainGenesisMap["coinbase"] = "0x0000000000000000000000000000000000000000"
cChainGenesisMap["alloc"] = map[string]interface{}{
defaultLocalCChainFundedAddress: map[string]interface{}{
"balance": defaultLocalCChainFundedBalance,
},
}
cChainGenesisMap["number"] = hexa0Str
cChainGenesisMap["gasUsed"] = hexa0Str
cChainGenesisMap["parentHash"] = "0x0000000000000000000000000000000000000000000000000000000000000000"
return json.Marshal(cChainGenesisMap)
}
func generateCustomGenesis(
networkID uint32,
walletAddr string,
stakingAddr string,
hosts []*models.Host,
) ([]byte, error) {
genesisMap := map[string]interface{}{}
// cchain
cChainGenesisBytes, err := generateCustomCchainGenesis()
if err != nil {
return nil, err
}
genesisMap["cChainGenesis"] = string(cChainGenesisBytes)
// pchain genesis
genesisMap["networkID"] = networkID
startTime := time.Now().Unix()
genesisMap["startTime"] = startTime
initialStakers := []map[string]interface{}{}
for _, host := range hosts {
nodeDirPath := app.GetNodeInstanceDirPath(host.GetCloudID())
blsPath := filepath.Join(nodeDirPath, constants.BLSKeyFileName)
blsKey, err := os.ReadFile(blsPath)
if err != nil {
return nil, err
}
blsSk, err := bls.SecretKeyFromBytes(blsKey)
if err != nil {
return nil, err
}
p := signer.NewProofOfPossession(blsSk)
pk, err := formatting.Encode(formatting.HexNC, p.PublicKey[:])
if err != nil {
return nil, err
}
pop, err := formatting.Encode(formatting.HexNC, p.ProofOfPossession[:])
if err != nil {
return nil, err
}
nodeID, err := getNodeID(nodeDirPath)
if err != nil {
return nil, err
}
initialStaker := map[string]interface{}{
"nodeID": nodeID,
"rewardAddress": walletAddr,
"delegationFee": 1000000,
"signer": map[string]interface{}{
"proofOfPossession": pop,
"publicKey": pk,
},
}
initialStakers = append(initialStakers, initialStaker)
}
genesisMap["initialStakeDuration"] = 31536000
genesisMap["initialStakeDurationOffset"] = 5400
genesisMap["initialStakers"] = initialStakers
lockTime := startTime + genesisLocktimeStartimeDelta
allocations := []interface{}{}
alloc := map[string]interface{}{
"avaxAddr": walletAddr,
"ethAddr": allocationCommonEthAddress,
"initialAmount": 300000000000000000,
"unlockSchedule": []interface{}{
map[string]interface{}{"amount": 20000000000000000},
map[string]interface{}{"amount": 10000000000000000, "locktime": lockTime},
},
}
allocations = append(allocations, alloc)
alloc = map[string]interface{}{
"avaxAddr": stakingAddr,
"ethAddr": allocationCommonEthAddress,
"initialAmount": 0,
"unlockSchedule": []interface{}{
map[string]interface{}{"amount": 10000000000000000, "locktime": lockTime},
},
}
allocations = append(allocations, alloc)
genesisMap["allocations"] = allocations
genesisMap["initialStakedFunds"] = []interface{}{
stakingAddr,
}
genesisMap["message"] = "{{ fun_quote }}"
return json.MarshalIndent(genesisMap, "", " ")
}
func setupDevnet(clusterName string, hosts []*models.Host, apiNodeIPMap map[string]string) error {
if err := checkCluster(clusterName); err != nil {
return err
}
inventoryPath := app.GetAnsibleInventoryDirPath(clusterName)
ansibleHostIDs, err := ansible.GetAnsibleHostsFromInventory(inventoryPath)
if err != nil {
return err
}
ansibleHosts, err := ansible.GetHostMapfromAnsibleInventory(app.GetAnsibleInventoryDirPath(clusterName))
if err != nil {
return err
}
if err != nil {
return err
}
// set devnet network
endpointIP := ""
if len(apiNodeIPMap) > 0 {
endpointIP = maps.Values(apiNodeIPMap)[0]
} else {
endpointIP = ansibleHosts[ansibleHostIDs[0]].IP
}
endpoint := fmt.Sprintf("http://%s:%d", endpointIP, constants.AvalanchegoAPIPort)
network := models.NewDevnetNetwork(endpoint, 0)
network = models.NewNetworkFromCluster(network, clusterName)
// get random staking key for devnet genesis
k, err := key.NewSoft(network.ID)
if err != nil {
return err
}
stakingAddrStr := k.X()[0]
// get ewoq key as funded key for devnet genesis
k, err = key.LoadEwoq(network.ID)
if err != nil {
return err
}
walletAddrStr := k.X()[0]
// exclude API nodes from genesis file generation as they will have no stake
hostsAPI := utils.Filter(hosts, func(h *models.Host) bool {
return slices.Contains(maps.Keys(apiNodeIPMap), h.GetCloudID())
})
hostsWithoutAPI := utils.Filter(hosts, func(h *models.Host) bool {
return !slices.Contains(maps.Keys(apiNodeIPMap), h.GetCloudID())
})
hostsWithoutAPIIDs := utils.Map(hostsWithoutAPI, func(h *models.Host) string { return h.NodeID })
// create genesis file at each node dir
genesisBytes, err := generateCustomGenesis(network.ID, walletAddrStr, stakingAddrStr, hostsWithoutAPI)
if err != nil {
return err
}
// create avalanchego conf node.json at each node dir
bootstrapIPs := []string{}
bootstrapIDs := []string{}
// append makes sure that hostsWithoutAPI i.e. validators are proccessed first and API nodes will have full list of validators to bootstrap
for _, host := range append(hostsWithoutAPI, hostsAPI...) {
confMap := map[string]interface{}{}
confMap[config.HTTPHostKey] = ""
confMap[config.PublicIPKey] = host.IP
confMap[config.NetworkNameKey] = fmt.Sprintf("network-%d", network.ID)
confMap[config.BootstrapIDsKey] = strings.Join(bootstrapIDs, ",")
confMap[config.BootstrapIPsKey] = strings.Join(bootstrapIPs, ",")
confMap[config.GenesisFileKey] = filepath.Join(constants.DockerNodeConfigPath, "genesis.json")
confBytes, err := json.MarshalIndent(confMap, "", " ")
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(app.GetNodeInstanceDirPath(host.GetCloudID()), "genesis.json"), genesisBytes, constants.WriteReadReadPerms); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(app.GetNodeInstanceDirPath(host.GetCloudID()), "node.json"), confBytes, constants.WriteReadReadPerms); err != nil {
return err
}
if slices.Contains(hostsWithoutAPIIDs, host.NodeID) {
nodeID, err := getNodeID(app.GetNodeInstanceDirPath(host.GetCloudID()))
if err != nil {
return err
}
bootstrapIDs = append(bootstrapIDs, nodeID.String())
bootstrapIPs = append(bootstrapIPs, fmt.Sprintf("%s:9651", host.IP))
}
}
// update node/s genesis + conf and start
wg := sync.WaitGroup{}
wgResults := models.NodeResults{}
for _, host := range hosts {
wg.Add(1)
go func(nodeResults *models.NodeResults, host *models.Host) {
defer wg.Done()
keyPath := filepath.Join(app.GetNodesDir(), host.GetCloudID())
if err := ssh.RunSSHSetupDevNet(host, keyPath); err != nil {
nodeResults.AddResult(host.NodeID, nil, err)
ux.Logger.RedXToUser(utils.ScriptLog(host.NodeID, "Setup devnet err: %v", err))
return
}
ux.Logger.GreenCheckmarkToUser(utils.ScriptLog(host.NodeID, "Setup devnet"))
}(&wgResults, host)
}
wg.Wait()
ux.Logger.PrintLineSeparator()
for _, node := range hosts {
if wgResults.HasNodeIDWithError(node.NodeID) {
ux.Logger.RedXToUser("Node %s is ERROR with error: %s", node.NodeID, wgResults.GetErrorHostMap()[node.NodeID])
} else {
nodeID, err := getNodeID(app.GetNodeInstanceDirPath(node.GetCloudID()))
if err != nil {
return err
}
ux.Logger.GreenCheckmarkToUser("Node %s[%s] is SETUP as devnet", node.GetCloudID(), nodeID)
}
}
// stop execution if at least one node failed
if wgResults.HasErrors() {
return fmt.Errorf("failed to deploy node(s) %s", wgResults.GetErrorHostMap())
}
ux.Logger.PrintLineSeparator()
ux.Logger.PrintToUser("Devnet Network Id: %s", logging.Green.Wrap(strconv.FormatUint(uint64(network.ID), 10)))
ux.Logger.PrintToUser("Devnet Endpoint: %s", logging.Green.Wrap(network.Endpoint))
ux.Logger.PrintLineSeparator()
// update cluster config with network information
clustersConfig, err := app.LoadClustersConfig()
if err != nil {
return err
}
clusterConfig := clustersConfig.Clusters[clusterName]
clusterConfig.Network = network
clustersConfig.Clusters[clusterName] = clusterConfig
return app.WriteClustersConfigFile(&clustersConfig)
}