-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap.go
354 lines (307 loc) · 11.3 KB
/
bootstrap.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
//
// Copyright 2019 Insolar Technologies GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package bootstrap
import (
"bytes"
"context"
"crypto"
"encoding/json"
"fmt"
"io/ioutil"
"path"
"strconv"
"github.com/pkg/errors"
"github.com/insolar/insolar/certificate"
"github.com/insolar/insolar/insolar"
"github.com/insolar/insolar/insolar/genesisrefs"
"github.com/insolar/insolar/insolar/secrets"
"github.com/insolar/insolar/instrumentation/inslogger"
"github.com/insolar/insolar/logicrunner/builtin/foundation"
)
// Generator is a component for generating bootstrap files required for discovery nodes bootstrap and heavy genesis.
type Generator struct {
config *Config
certificatesOutDir string
}
// NewGenerator parses config file and creates new generator on success.
func NewGenerator(configFile, certificatesOutDir string) (*Generator, error) {
config, err := ParseConfig(configFile)
if err != nil {
return nil, err
}
return NewGeneratorWithConfig(config, certificatesOutDir), nil
}
// NewGeneratorWithConfig creates new Generator with provided config.
func NewGeneratorWithConfig(config *Config, certificatesOutDir string) *Generator {
return &Generator{
config: config,
certificatesOutDir: certificatesOutDir,
}
}
func (g *Generator) readMigrationAddresses() ([][]string, error) {
file := g.config.MembersKeysDir + "migration_addresses.json"
result := make([][]string, g.config.MAShardCount)
b, err := ioutil.ReadFile(file)
if err != nil {
return result, errors.Wrapf(err, " couldn't read migration addresses file %v", file)
}
var ma []string
err = json.NewDecoder(bytes.NewReader(b)).Decode(&ma)
if err != nil {
return result, errors.Wrapf(err, "fail unmarshal migration addresses data")
}
for _, a := range ma {
address := foundation.TrimAddress(a)
i := foundation.GetShardIndex(address, g.config.MAShardCount)
result[i] = append(result[i], address)
}
return result, nil
}
// Run generates bootstrap data.
//
// 1. builds Go plugins for genesis contracts
// (gone when built-in contracts (INS-2308) would be implemented)
// 2. read root keys file and generates keys and certificates for discovery nodes.
// 3. generates genesis config for heavy node.
func (g *Generator) Run(ctx context.Context) error {
fmt.Printf("[ bootstrap ] config:\n%v\n", dumpAsJSON(g.config))
inslog := inslogger.FromContext(ctx)
inslog.Info("[ bootstrap ] read keys files")
rootPublicKey, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + "root_member_keys.json")
if err != nil {
return errors.Wrap(err, "couldn't get root keys")
}
feePublicKey, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + "fee_member_keys.json")
if err != nil {
return errors.Wrap(err, "couldn't get fees keys")
}
migrationAdminPublicKey, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + "migration_admin_member_keys.json")
if err != nil {
return errors.Wrap(err, "couldn't get migration admin keys")
}
migrationDaemonPublicKeys := []string{}
for i := 0; i < insolar.GenesisAmountMigrationDaemonMembers; i++ {
k, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + GetMigrationDaemonPath(i))
if err != nil {
return errors.Wrap(err, "couldn't get migration daemon keys")
}
migrationDaemonPublicKeys = append(migrationDaemonPublicKeys, k)
}
fundsAndEnterprisePublicKey, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + "funds_and_enterprise_member_keys.json")
if err != nil {
return errors.Wrap(err, "couldn't get enterprise keys")
}
networkIncentivesPublicKeys := []string{}
for i := 0; i < insolar.GenesisAmountNetworkIncentivesMembers; i++ {
k, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + GetFundPath(i, "network_incentives_"))
if err != nil {
return errors.Wrap(err, "couldn't get network incentives keys")
}
networkIncentivesPublicKeys = append(networkIncentivesPublicKeys, k)
}
applicationIncentivesPublicKeys := []string{}
for i := 0; i < insolar.GenesisAmountApplicationIncentivesMembers; i++ {
k, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + GetFundPath(i, "application_incentives_"))
if err != nil {
return errors.Wrap(err, "couldn't get application incentives keys")
}
applicationIncentivesPublicKeys = append(applicationIncentivesPublicKeys, k)
}
foundationPublicKeys := []string{}
for i := 0; i < insolar.GenesisAmountFoundationMembers; i++ {
k, err := secrets.GetPublicKeyFromFile(g.config.MembersKeysDir + GetFundPath(i, "foundation_"))
if err != nil {
return errors.Wrap(err, "couldn't get foundation keys")
}
foundationPublicKeys = append(foundationPublicKeys, k)
}
if g.config.MAShardCount <= 0 {
panic(fmt.Sprintf("[genesis] store contracts failed: setup ma_shard_count parameter, current value %v", g.config.MAShardCount))
}
inslog.Info("[ bootstrap ] read migration addresses ...")
migrationAddresses, err := g.readMigrationAddresses()
if err != nil {
return errors.Wrap(err, "couldn't get migration addresses")
}
inslog.Info("[ bootstrap ] create discovery keys ...")
discoveryNodes, err := createKeysInDir(
ctx,
g.config.DiscoveryKeysDir,
g.config.KeysNameFormat,
g.config.DiscoveryNodes,
g.config.ReuseKeys,
)
if err != nil {
return errors.Wrapf(err, "create keys step failed")
}
inslog.Info("[ bootstrap ] create discovery certificates ...")
err = g.makeCertificates(ctx, discoveryNodes, discoveryNodes)
if err != nil {
return errors.Wrap(err, "generate discovery certificates failed")
}
vestingStep := g.config.VestingStepInPulses
if vestingStep == 0 {
vestingStep = 60 * 60 * 24
}
if g.config.NotDiscoveryKeysDir != "" {
inslog.Info("[ bootstrap ] create not discovery keys ...")
nodes, err := createKeysInDir(
ctx,
g.config.NotDiscoveryKeysDir,
g.config.KeysNameFormat,
g.config.Nodes,
g.config.ReuseKeys,
)
if err != nil {
return errors.Wrapf(err, "create keys step failed")
}
inslog.Info("[ bootstrap ] create not discovery certificates ...", nodes)
err = g.makeCertificates(ctx, nodes, discoveryNodes)
if err != nil {
return errors.Wrap(err, "generate not discovery certificates failed")
}
}
inslog.Info("[ bootstrap ] create heavy genesis config ...")
contractsConfig := insolar.GenesisContractsConfig{
RootBalance: g.config.RootBalance,
MDBalance: g.config.MDBalance,
RootPublicKey: rootPublicKey,
FeePublicKey: feePublicKey,
FundsAndEnterprisePublicKey: fundsAndEnterprisePublicKey,
MigrationAdminPublicKey: migrationAdminPublicKey,
MigrationDaemonPublicKeys: migrationDaemonPublicKeys,
NetworkIncentivesPublicKeys: networkIncentivesPublicKeys,
ApplicationIncentivesPublicKeys: applicationIncentivesPublicKeys,
FoundationPublicKeys: foundationPublicKeys,
MigrationAddresses: migrationAddresses,
VestingPeriodInPulses: g.config.VestingPeriodInPulses,
LoсkupPeriodInPulses: g.config.LockupPeriodInPulses,
VestingStepInPulses: vestingStep,
MAShardCount: g.config.MAShardCount,
PKShardCount: g.config.PKShardCount,
}
err = g.makeHeavyGenesisConfig(discoveryNodes, contractsConfig)
if err != nil {
return errors.Wrap(err, "generate heavy genesis config failed")
}
return nil
}
type nodeInfo struct {
privateKey crypto.PrivateKey
publicKey string
role string
certName string
}
func (ni nodeInfo) reference() insolar.Reference {
return genesisrefs.GenesisRef(ni.publicKey)
}
func (g *Generator) makeCertificates(ctx context.Context, nodesInfo []nodeInfo, discoveryNodes []nodeInfo) error {
certs := make([]certificate.Certificate, 0, len(g.config.DiscoveryNodes))
for _, node := range nodesInfo {
c := certificate.Certificate{
AuthorizationCertificate: certificate.AuthorizationCertificate{
PublicKey: node.publicKey,
Role: node.role,
Reference: node.reference().String(),
},
MajorityRule: g.config.MajorityRule,
RootDomainReference: genesisrefs.ContractRootDomain.String(),
}
c.MinRoles.Virtual = g.config.MinRoles.Virtual
c.MinRoles.HeavyMaterial = g.config.MinRoles.HeavyMaterial
c.MinRoles.LightMaterial = g.config.MinRoles.LightMaterial
c.BootstrapNodes = []certificate.BootstrapNode{}
for j, n2 := range discoveryNodes {
host := g.config.DiscoveryNodes[j].Host
c.BootstrapNodes = append(c.BootstrapNodes, certificate.BootstrapNode{
PublicKey: n2.publicKey,
Host: host,
NodeRef: n2.reference().String(),
NodeRole: n2.role,
})
}
certs = append(certs, c)
}
var err error
for i, node := range nodesInfo {
for j := range g.config.DiscoveryNodes {
dn := discoveryNodes[j]
certs[i].BootstrapNodes[j].NetworkSign, err = certs[i].SignNetworkPart(dn.privateKey)
if err != nil {
return errors.Wrapf(err, "can't SignNetworkPart for %s",
dn.reference())
}
certs[i].BootstrapNodes[j].NodeSign, err = certs[i].SignNodePart(dn.privateKey)
if err != nil {
return errors.Wrapf(err, "can't SignNodePart for %s",
dn.reference())
}
}
// save cert to disk
cert, err := json.MarshalIndent(certs[i], "", " ")
if err != nil {
return errors.Wrapf(err, "can't MarshalIndent")
}
if len(node.certName) == 0 {
return errors.New("cert_name must not be empty for node number " + strconv.Itoa(i+1))
}
certFile := path.Join(g.certificatesOutDir, node.certName)
err = ioutil.WriteFile(certFile, cert, 0600)
if err != nil {
return errors.Wrapf(err, "failed to create certificate: %v", certFile)
}
inslogger.FromContext(ctx).Infof("[ bootstrap ] write certificate file: %v", certFile)
}
return nil
}
func (g *Generator) makeHeavyGenesisConfig(
discoveryNodes []nodeInfo,
contractsConfig insolar.GenesisContractsConfig,
) error {
items := make([]insolar.DiscoveryNodeRegister, 0, len(g.config.DiscoveryNodes))
for _, node := range discoveryNodes {
items = append(items, insolar.DiscoveryNodeRegister{
Role: node.role,
PublicKey: node.publicKey,
})
}
cfg := &insolar.GenesisHeavyConfig{
DiscoveryNodes: items,
ContractsConfig: contractsConfig,
}
b, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return errors.Wrapf(err, "failed to decode heavy config to json")
}
err = ioutil.WriteFile(g.config.HeavyGenesisConfigFile, b, 0600)
return errors.Wrapf(err,
"failed to write heavy config %v", g.config.HeavyGenesisConfigFile)
}
func dumpAsJSON(data interface{}) string {
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
panic(err)
}
return string(b)
}
// GetMigrationDaemonPath generate key file name for migration daemon
func GetMigrationDaemonPath(i int) string {
return "migration_daemon_" + strconv.Itoa(i) + "_member_keys.json"
}
// GetFundPath generate key file name for composite name
func GetFundPath(i int, prefix string) string {
return prefix + strconv.Itoa(i) + "_member_keys.json"
}