-
Notifications
You must be signed in to change notification settings - Fork 6
/
subchain.go
333 lines (277 loc) · 8.36 KB
/
subchain.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
/**
* @file
* @copyright defined in scdo/LICENSE
*/
package cmd
import (
"context"
"crypto/ecdsa"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"path/filepath"
"strings"
"time"
"github.com/scdoproject/go-scdo/cmd/util"
"github.com/scdoproject/go-scdo/common"
"github.com/scdoproject/go-scdo/common/hexutil"
"github.com/scdoproject/go-scdo/contract/system"
"github.com/scdoproject/go-scdo/core"
"github.com/scdoproject/go-scdo/crypto"
"github.com/scdoproject/go-scdo/log/comm"
"github.com/scdoproject/go-scdo/metrics"
"github.com/scdoproject/go-scdo/node"
"github.com/scdoproject/go-scdo/p2p"
"github.com/scdoproject/go-scdo/p2p/discovery"
"github.com/scdoproject/go-scdo/rpc"
"github.com/urfave/cli"
)
var (
errInvalidVersion = errors.New("invalid subchain version")
errInvalidTokenFullName = errors.New("invalid subchain token full name")
errInvalidTokenShortName = errors.New("invalid subchain token short name")
errInvalidTokenAmount = errors.New("invalid subchain token amount")
errSubChainInfo = errors.New("failed to get sub-chain information")
defaultTokenFullName = "scdocoin"
defaultTokenShortName = "scdo"
)
func registerSubChain(client *rpc.Client) (interface{}, interface{}, error) {
amountValue = "0"
subChain, err := getSubChainFromFile(subChainJSONFileVale)
if err != nil {
return nil, nil, err
}
if err := system.ValidateDomainName([]byte(subChain.Name)); err != nil {
return nil, nil, err
}
if len(subChain.Version) == 0 {
return nil, nil, errInvalidVersion
}
if len(subChain.TokenFullName) == 0 || strings.ToLower(subChain.TokenFullName) == defaultTokenFullName {
return nil, nil, errInvalidTokenFullName
}
if len(subChain.TokenShortName) == 0 || strings.ToLower(subChain.TokenShortName) == defaultTokenShortName {
return nil, nil, errInvalidTokenShortName
}
if subChain.TokenAmount == 0 {
return nil, nil, errInvalidTokenAmount
}
subChainBytes, err := json.Marshal(subChain)
if err != nil {
return nil, nil, err
}
tx, err := sendSystemContractTx(client, system.SubChainContractAddress, system.CmdSubChainRegister, subChainBytes)
if err != nil {
return nil, nil, err
}
output := make(map[string]interface{})
output["Tx"] = *tx
output["SubChainName"] = subChain.Name
output["TokenFullName"] = subChain.TokenFullName
output["TokenShortName"] = subChain.TokenShortName
return output, tx, err
}
func querySubChain(client *rpc.Client) (interface{}, interface{}, error) {
amountValue = "0"
if err := system.ValidateDomainName([]byte(nameValue)); err != nil {
return nil, nil, err
}
tx, err := sendSystemContractTx(client, system.SubChainContractAddress, system.CmdSubChainQuery, []byte(nameValue))
if err != nil {
return nil, nil, err
}
return tx, tx, err
}
func createSubChainConfigFile(c *cli.Context) error {
client, err := rpc.DialTCP(context.Background(), addressValue)
if err != nil {
return err
}
subChainInfo, err := getSubChainFromReceipt(client)
if err != nil {
return err
}
networkID, err := util.GetNetworkID(client)
if err != nil {
return err
}
config, err := getConfigFromSubChain(networkID, subChainInfo)
if err != nil {
return err
}
// save accounts file
byteAccounts, err := json.MarshalIndent(subChainInfo.GenesisAccounts, "", "\t")
if err != nil {
return err
}
if err = common.SaveFile(filepath.Join(outPutValue, "accounts.json"), byteAccounts); err != nil {
return err
}
// save node file
byteNode, err := json.MarshalIndent(config, "", "\t")
if err != nil {
return err
}
if err = common.SaveFile(filepath.Join(outPutValue, "node.json"), byteNode); err != nil {
return err
}
fmt.Println("generate sub chain config files successfully")
return nil
}
func getSubChainFromFile(filepath string) (*system.SubChainInfo, error) {
var subChain system.SubChainInfo
buff, err := ioutil.ReadFile(filepath)
if err != nil {
return &subChain, err
}
err = json.Unmarshal(buff, &subChain)
return &subChain, err
}
func getSubChainFromReceipt(client *rpc.Client) (*system.SubChainInfo, error) {
if err := system.ValidateDomainName([]byte(nameValue)); err != nil {
return nil, err
}
payloadBytes := append([]byte{system.CmdSubChainQuery}, []byte(nameValue)...)
mapReceipt, err := util.CallContract(client, system.SubChainContractAddress.Hex(), hexutil.BytesToHex(payloadBytes), -1)
if err != nil {
return nil, err
}
resultFlag, ok := mapReceipt["failed"].(bool)
if !ok {
return nil, errSubChainInfo
}
result, ok := mapReceipt["result"].(string)
if !ok {
return nil, errSubChainInfo
}
if resultFlag {
return nil, fmt.Errorf("failed to get sub-chain information, %s", result)
}
bytesSubChainInfo, err := hexutil.HexToBytes(result)
if err != nil {
return nil, err
}
if len(bytesSubChainInfo) == 0 {
return nil, fmt.Errorf("sub-chain %s does not exist", nameValue)
}
var subChainInfo system.SubChainInfo
if err = json.Unmarshal(bytesSubChainInfo, &subChainInfo); err != nil {
return nil, err
}
return &subChainInfo, nil
}
// getPrivateKey get private key and validate shard
func getPrivateKey() (*ecdsa.PrivateKey, error) {
var privateKey *ecdsa.PrivateKey
var err error
if len(privateKeyValue) == 0 {
_, privateKey, err = util.GenerateKey(shardValue)
if err != nil {
return nil, err
}
} else {
privateKey, err = crypto.LoadECDSAFromString(privateKeyValue)
if err != nil {
return nil, fmt.Errorf("invalid key: %s", err)
}
}
return privateKey, nil
}
func getStaticNodes() ([]*discovery.Node, error) {
var arrayNode []*discovery.Node
for _, strNode := range staticNodesValue.Value() {
node, err := discovery.NewNodeFromIP(strNode)
if err != nil {
return nil, err
}
arrayNode = append(arrayNode, node)
}
return arrayNode, nil
}
func getConfigFromSubChain(networkID string, subChainInfo *system.SubChainInfo) (*util.Config, error) {
addr, err := common.HexToAddress(coinbaseValue)
if err != nil {
return nil, fmt.Errorf("invalid coinbase, err:%s", err.Error())
}
shardNumber := addr.Shard()
if shardValue == 0 {
shardValue = shardNumber
}
if shardValue != shardNumber {
return nil, fmt.Errorf("input shard(%d) is not equal to shard nubmer(%d) obtained from the input coinbase:%s", shardValue, shardNumber, coinbaseValue)
}
privateKey, err := getPrivateKey()
if err != nil {
return nil, err
}
staticNodes, err := getStaticNodes()
if err != nil {
return nil, err
}
config := &util.Config{}
config.BasicConfig = node.BasicConfig{
Name: subChainInfo.Name,
Version: subChainInfo.Version,
DataDir: subChainInfo.Name,
RPCAddr: "0.0.0.0:8127",
Coinbase: coinbaseValue,
MinerAlgorithm: algorithmValue,
}
config.P2PConfig = p2p.Config{
NetworkID: fmt.Sprintf("%s.%d.%s", subChainInfo.Name, subChainInfo.Owner.Shard(), networkID),
ListenAddr: "0.0.0.0:8157",
StaticNodes: append(subChainInfo.StaticNodes, staticNodes...),
SubPrivateKey: hexutil.BytesToHex(crypto.FromECDSA(privateKey)),
}
config.LogConfig = comm.LogConfig{
PrintLog: true,
}
config.HTTPServer = node.HTTPServer{
HTTPAddr: "127.0.0.1:8136",
HTTPCors: []string{"*"},
HTTPWhiteHost: []string{"*"},
}
config.WSServerConfig = node.WSServerConfig{
Address: "127.0.0.1:8146",
CrossOrigins: []string{"*"},
}
config.MetricsConfig = &metrics.Config{
Addr: "127.0.0.1:8187",
Duration: time.Duration(10),
Database: "influxdb",
Username: "test",
Password: "test123",
}
config.GenesisConfig = core.GenesisInfo{
Difficult: int64(subChainInfo.GenesisDifficulty),
ShardNumber: shardValue,
CreateTimestamp: subChainInfo.CreateTimestamp,
}
return config, nil
}
func generateTemplate(c *cli.Context) error {
if err := system.ValidateDomainName([]byte(nameValue)); err != nil {
return err
}
subChainInfo := system.SubChainInfo{
Name: nameValue,
Version: "1.0",
StaticNodes: []*discovery.Node{},
TokenFullName: defaultTokenFullName,
TokenShortName: defaultTokenShortName,
TokenAmount: 0,
GenesisDifficulty: 8000000,
GenesisAccounts: map[common.Address]*big.Int{},
}
byteSubChainInfo, err := json.MarshalIndent(subChainInfo, "", "\t")
if err != nil {
return err
}
if err = common.SaveFile(filepath.Join(subChainJSONFileVale, "subChainTemplate.json"), byteSubChainInfo); err != nil {
return err
}
fmt.Println("generate template json file for sub chain register successfully")
return nil
}