-
Notifications
You must be signed in to change notification settings - Fork 38
/
init.go
462 lines (417 loc) · 12.4 KB
/
init.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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"time"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/sec-bit/zkPoD-lib/pod_go/setup"
"github.com/urfave/cli"
)
//Config is the struct of config info
type Config struct {
Operation string `json:"operation"`
Password string `json:"password"`
AliceAddress string `json:"Alice_address"`
BasicConfig BasicConfig `json:"basic_config"`
RequestData RequestData `json:"request_data"`
PurchaseConfigPath string `json:"purchase_path"`
InitPublishConfigPath string `json:"init_path"`
MerkleRoot string `json:"merkle_root"`
ETHValue string `json:"value"`
SessionID string `json:"session_id"`
}
type BasicConfig struct {
InitKeyPath string `json:"init_key_path"`
PublishBINPath string `json:"publish_bin_path"`
ContractAddr string `json:"contract_addr"`
BobDir string `json:"B_dir"`
AliceDir string `json:"A_dir"`
KeyStoreFile string `json:"keystore_file"`
NetIP string `json:"net_ip"`
Port string `json:"port"`
}
// RequestData is the struct of Bob's request data
type RequestData struct {
MerkleRoot string `json:"merkle_root"`
AliceIP string `json:"Alice_ip"`
AliceAddr string `json:"Alice_addr"`
PubPath string `json:"pub_path"`
BulletinFile string `json:"bulletin_file"`
SubMode string `json:"sub_mode"`
OT bool `json:"ot"`
Demands []Demand `json:"demands"`
Phantoms []Phantom `json:"phantoms"`
KeyName string `json:"key_name"`
KeyValue []string `json:"key_value"`
PhantomKeyValue []string `json:"phantom_key_value"`
UnitPrice int64 `json:"unit_price"`
}
// Demand is the struct of demand
type Demand struct {
DemandStart uint64 `json:"demand_start"`
DemandCount uint64 `json:"demand_count"`
}
// Phantom is the struct of phantom for ot mode
type Phantom struct {
PhantomStart uint64 `json:"phantom_start"`
PhantomCount uint64 `json:"phantom_count"`
}
// initCli reads command line inputs.
func initCli() (config Config) {
app := cli.NewApp()
app.Version = "0.0.1"
app.Name = "zkPod-node"
app.Authors = []cli.Author{
cli.Author{
Name: "SECBIT Labs",
Email: "[email protected]",
},
}
app.Copyright = "(c) 2019 SECBIT Labs"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "o",
Value: "start",
Usage: "operation type \n" +
" start, initdata, publish, close, purchase, withdraw, deposit, undeposit.",
},
cli.StringFlag{
Name: "k",
Value: "",
Usage: "keystore file path.",
},
cli.StringFlag{
Name: "pass",
Value: "",
Usage: "the password of keystore file.",
},
cli.StringFlag{
Name: "ip",
Value: "",
Usage: "the Alice's node ip addr for pod net.",
},
cli.StringFlag{
Name: "port",
Value: "",
Usage: "the api server port.",
},
cli.StringFlag{
Name: "c",
Value: "",
Usage: "config file path while Bob's operation is 'purchase'.",
},
cli.StringFlag{
Name: "mkl",
Value: "",
Usage: "the sigma merkle root.",
},
cli.StringFlag{
Name: "eth",
Value: "0",
Usage: "the ETH's value(wei) for withdrawing or depositing.",
},
cli.StringFlag{
Name: "init",
Value: "",
Usage: "the Alice initializes a file for publishing.",
},
cli.StringFlag{
Name: "addr",
Value: "",
Usage: "the Alice's address.",
},
cli.StringFlag{
Name: "sid",
Value: "",
Usage: "the transaction's session Id.",
},
}
var exit = true
app.Action = func(c *cli.Context) error {
exit = false
config.Operation = c.String("o")
config.BasicConfig.NetIP = c.String("ip")
config.BasicConfig.Port = c.String("port")
config.BasicConfig.KeyStoreFile = c.String("k")
config.Password = c.String("pass")
config.PurchaseConfigPath = c.String("c")
config.MerkleRoot = c.String("mkl")
config.ETHValue = c.String("eth")
config.InitPublishConfigPath = c.String("init")
config.AliceAddress = c.String("addr")
config.SessionID = c.String("sid")
// config.BasicConfig.SyncthingID = c.String("id")
// config.BasicConfig.DataBase = c.String("db")
return nil
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
return
}
if exit {
os.Exit(1)
}
return
}
func readBasicFile(basic BasicConfig) (BasicConfig, error) {
basicFile := DEFAULT_BASIC_CONFGI_FILE
rs, err := pathExists(basicFile)
if err != nil {
return basic, fmt.Errorf("failed to read basic config file. config file=%v, err=%v", basicFile, err)
}
if rs {
conf, err := ioutil.ReadFile(basicFile)
if err != nil {
return basic, fmt.Errorf("failed to read config file. config file=%v, err=%v", basicFile, err)
}
var preBasic BasicConfig
err = json.Unmarshal(conf, &preBasic)
if err != nil {
return basic, fmt.Errorf("failed to parse basic config file. err=%v", err)
}
if basic.NetIP == "" {
basic.NetIP = preBasic.NetIP
}
if basic.Port == "" {
basic.Port = preBasic.Port
}
if basic.KeyStoreFile == "" {
basic.KeyStoreFile = preBasic.KeyStoreFile
}
basic.InitKeyPath = preBasic.InitKeyPath
basic.PublishBINPath = preBasic.PublishBINPath
basic.BobDir = preBasic.BobDir
basic.AliceDir = preBasic.AliceDir
basic.ContractAddr = preBasic.ContractAddr
}
if basic.Port == "" {
basic.Port = DEFAULT_SERVER_PORT
}
if basic.KeyStoreFile == "" {
basic.KeyStoreFile = DEFAULT_KEYSTORE_FILE
}
if basic.NetIP == "" {
basic.NetIP = DEFAULT_NET_IP
}
if basic.InitKeyPath == "" {
basic.InitKeyPath = DEFAULT_KEY_PATH
}
if basic.PublishBINPath == "" {
basic.PublishBINPath = DEFAULT_PUBLISH_BIN_FILE
}
if basic.BobDir == "" {
basic.BobDir = DEFAULT_BOB_DIR
}
if basic.AliceDir == "" {
basic.AliceDir = DEFAULT_ALICE_DIR
}
if basic.ContractAddr == "" {
basic.ContractAddr = DEFAULT_PODEX_CONTRACT_ADDRESS
}
return basic, nil
}
func saveBasicFile(basic BasicConfig) error {
basicFile := DEFAULT_BASIC_CONFGI_FILE
err := saveBasicConfig(basic, basicFile)
if err != nil {
return err
}
return nil
}
// readKeyStore reads keystore file.
func readKeyStore(config BasicConfig, password string) (*keystore.Key, error) {
Log := Logger.NewSessionLogger()
var key *keystore.Key
if password == "" {
Log.Warnf("no password to read!")
return nil, fmt.Errorf("no keystore password!")
}
rs, err := pathExists(config.KeyStoreFile)
if err != nil {
Log.Errorf("failed to check key store file. err=%v", err)
return nil, errors.New("failed to check key store file")
}
if !rs {
var tmpKeystore = "./tmp" + time.Now().String()
ks := keystore.NewKeyStore(tmpKeystore, keystore.StandardScryptN, keystore.StandardScryptP)
account, err := ks.NewAccount(password)
if err != nil {
Log.Warnf("failed to create a account. err=%v", err)
return nil, errors.New("failed to create a account")
}
err = copyKeyStore(tmpKeystore, config.KeyStoreFile)
if err != nil {
Log.Errorf("failed to save key store file. err=%v", err)
return nil, errors.New("failed to save key store file")
}
Log.Infof("create a new account finish. keystore file=%v, ethaddr=%v.", config.KeyStoreFile, account.Address.Hex())
}
key, err = initKeyStore(config.KeyStoreFile, password, Log)
if err != nil {
Log.Errorf("failed to initialize key store file. err=%v", err)
return nil, errors.New("invalid key store file")
}
Log.Infof("initialize key store finish. ethaddr=%v.", key.Address.Hex())
if config.ContractAddr == "" {
Log.Warnf("invalid contract addr. contract=%v", config.ContractAddr)
return nil, errors.New("invalid contract addr")
}
err = ConnectToProvider(key, config.ContractAddr, Log)
if err != nil {
Log.Warnf("failed to connect to provider for contract. err=%v", err)
return nil, errors.New("failed to connect to provider for contract")
}
Log.Infof("success to connect to provider for contract")
return key, nil
}
// initKeyStore inits key store for ethereum account.
func initKeyStore(keystoreFile string, password string, Log ILogger) (key *keystore.Key, err error) {
var jsonBytes []byte
jsonBytes, err = ioutil.ReadFile(keystoreFile)
if err != nil {
Log.Warnf("failed to read keystore file. err=%v", err)
return nil, errors.New("failed to read keystore file")
}
key, err = keystore.DecryptKey(jsonBytes, password)
if err != nil {
Log.Warnf("failed to read keystore file. err=%v", err)
return nil, errors.New("failed to read keystore file")
}
return
}
func readRequestData(configFile string) (RequestData, error) {
var requestData RequestData
if configFile == "" {
configFile = DEFAULT_CONFIG_FILE
}
rs, err := pathExists(configFile)
if err != nil {
return requestData, fmt.Errorf("failed to read config file. config file=%v, err=%v", configFile, err)
}
if !rs {
return requestData, fmt.Errorf("the config file does not exist. config file=%v", configFile)
}
conf, err := ioutil.ReadFile(configFile)
if err != nil {
return requestData, fmt.Errorf("failed to read config file. config file=%v, err=%v", configFile, err)
}
err = json.Unmarshal(conf, &requestData)
if err != nil {
return requestData, fmt.Errorf("failed to parse config file. config path=%v, err=%v", string(conf), err)
}
return requestData, nil
}
//initDir initializes node and check dictionary
func initDir(BobDir string, AliceDir string) error {
if BobDir == "" || AliceDir == "" {
fmt.Errorf("invalid dictionary. Bob dictionary=%v, Alice dictionary=%v", BobDir, AliceDir)
}
BobTxDir := BobDir + "/transaction"
AliceTxDir := AliceDir + "/transaction"
AlicePublishDir := AliceDir + "/publish"
rs, err := pathExists(BobDir)
if err != nil {
return fmt.Errorf("failed to check dictionary. spath=%v, err=%v", BobDir, err)
}
if !rs {
err = os.Mkdir(BobDir, os.ModePerm)
if err != nil {
return fmt.Errorf("create dictionary %v error. err=%v", BobDir, err)
}
fmt.Printf("success to create dictionary=%v.\n", BobDir)
}
rs, err = pathExists(BobTxDir)
if err != nil {
return fmt.Errorf("check dictonary exist error. path=%v, err=%v", BobTxDir, err)
}
if !rs {
err = os.Mkdir(BobTxDir, os.ModePerm)
if err != nil {
return fmt.Errorf("create dictionary %v error. err=%v", BobTxDir, err)
}
fmt.Printf("success to create dictionary=%v.\n", BobTxDir)
}
rs, err = pathExists(AliceDir)
if err != nil {
return fmt.Errorf("check dictonary error. path=%v, err=%v", AliceDir, err)
}
if !rs {
err = os.Mkdir(AliceDir, os.ModePerm)
if err != nil {
return fmt.Errorf("create dictionary %v error. err=%v", AliceDir, err)
}
fmt.Printf("success to create dictionary=%v.\n", AliceDir)
}
rs, err = pathExists(AliceTxDir)
if err != nil {
return fmt.Errorf("check dictonary error. path=%v, err=%v", AliceTxDir, err)
}
if !rs {
err = os.Mkdir(AliceTxDir, os.ModePerm)
if err != nil {
return fmt.Errorf("create dictionary %v error. err=%v", AliceTxDir, err)
}
fmt.Printf("success to create dictionary=%v.\n", AliceTxDir)
}
rs, err = pathExists(AlicePublishDir)
if err != nil {
return fmt.Errorf("check dictonary error. path=%v, err=%v", AlicePublishDir, err)
}
if !rs {
err = os.Mkdir(AlicePublishDir, os.ModePerm)
if err != nil {
return fmt.Errorf("create dictionary %v error. err=%v", AlicePublishDir, err)
}
fmt.Printf("success to create dictionary=%v.\n", AlicePublishDir)
}
return nil
}
func initMap() {
AliceTxMap = make(map[string]Transaction)
BobTxMap = make(map[string]BobTransaction)
DepositLockMap = make(map[string]int64)
}
func preparePOD(initKeyPath string) bool {
Log := Logger.NewSessionLogger()
rs, err := pathExists(initKeyPath)
if err != nil {
Log.Errorf("check path exist error. path=%v, err=%v", initKeyPath, err)
return false
}
if !rs {
Log.Warnf("no key.")
return false
}
zksnarkPath := initKeyPath + "/zksnark_key"
rs, err = pathExists(zksnarkPath)
if err != nil {
Log.Errorf("check path exist error. path=%v, err=%v", zksnarkPath, err)
return false
}
if !rs {
Log.Warnf("no zksnark key.")
return false
}
zksnarkpkPath := zksnarkPath + "/atomic_swap_vc.pk"
rs1, err := pathExists(zksnarkpkPath)
if err != nil {
Log.Errorf("check path exist error. path=%v, err=%v", zksnarkpkPath, err)
return false
}
zksnarkvkPath := zksnarkPath + "/atomic_swap_vc.vk"
rs2, err := pathExists(zksnarkvkPath)
if err != nil {
Log.Errorf("check path exist error. path=%v, err=%v", zksnarkvkPath, err)
return false
}
if !rs1 || !rs2 {
Log.Warnf("zksnark keys are incomplete.")
return false
}
return setup.Load(initKeyPath)
}