-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.go
413 lines (357 loc) · 11.6 KB
/
main.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
package main
import (
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"math/big"
"os"
"path/filepath"
"strings"
"sync"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ChainSafeSystems/ChainBridge/client"
"github.com/ChainSafeSystems/ChainBridge/logger"
)
/* global vars */
var flags map[string]bool
var ks *keystore.KeyStore
type Config struct {
Chain map[string]*Chain `json:"networks"`
}
type Chain struct {
Name string `json:"name"`
Url string `json:"url"`
Id *big.Int `json:"id,omitempty"`
Contract string `json:"contractAddr"`
GasPrice *big.Int `json:"gasPrice"`
From string `json:"from"`
Password string `json:"password,omitempty"`
StartBlock int `json:"startBlock,omitempty"`
}
// NewKeyStore creates a general keystore at given path
func newKeyStore(path string) *keystore.KeyStore {
return keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP)
}
// ReadAbi parses solidity/Bridge/build/Bridge.abi for events and stores the keccak hash of each in an Event struct
func readAbi(verbose bool) *client.Events {
e := new(client.Events)
// read bridge contract abi
path, _ := filepath.Abs("./solidity/Bridge/build/contracts_Bridge_sol_Bridge.abi")
file, err := ioutil.ReadFile(path)
if err != nil {
logger.Warn("Failed to read file: %s: will try to read solidity/build/Bridge.abi", err)
path, _ = filepath.Abs("./solidity/Bridge/build/Bridge.abi")
file, err = ioutil.ReadFile(path)
if err != nil {
logger.FatalError("Failed to read file: %s", err)
}
}
bridgeabi, err := abi.JSON(strings.NewReader(string(file)))
if err != nil {
logger.FatalError("Invalid abi: %s", err)
}
// checking abi for events
bridgeEvents := bridgeabi.Events
// save event Ids which will be what we check for in event topics
e.DepositId = bridgeEvents["Deposit"].Id().Hex()
e.CreationId = bridgeEvents["ContractCreation"].Id().Hex()
e.WithdrawId = bridgeEvents["Withdraw"].Id().Hex()
e.BridgeFundedId = bridgeEvents["BridgeFunded"].Id().Hex()
e.PaidId = bridgeEvents["Paid"].Id().Hex()
// e.AuthorityAddedId = bridgeEvents["AuthorityAdded"].Id().Hex()
return e
}
// check if file or directory at path exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
// create log/ directory if it does not exist
// will store the latest block number read
func startup(id *big.Int) *big.Int {
logExists, err := exists("log")
if err != nil {
logger.Error("%s", err)
}
if !logExists {
logger.Info("creating log/ directory...")
err = os.Mkdir("./log", os.ModePerm)
if err != nil {
logger.Error(err.Error())
}
}
path, _ := filepath.Abs("./log/" + id.String() + "_lastblock.txt")
file, err := ioutil.ReadFile(path)
if err != nil {
logger.Warn("%s", err)
}
startBlock := new(big.Int)
startBlock.SetString(string(file), 10)
return startBlock
}
func printHeader() {
fmt.Println("██████╗ ██████╗ ██╗██████╗ ██████╗ ███████╗")
fmt.Println("██╔══██╗██╔══██╗██║██╔══██╗██╔════╝ ██╔════╝")
fmt.Println("██████╔╝██████╔╝██║██║ ██║██║ ███╗█████╗ ")
fmt.Println("██╔══██╗██╔══██╗██║██║ ██║██║ ██║██╔══╝ ")
fmt.Println("██████╔╝██║ ██║██║██████╔╝╚██████╔╝███████╗")
fmt.Println("╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚══════╝")
}
func main() {
/* flags */
headerPtr := flag.Bool("header", true, "a bool representing whether to print out the header or not")
verbosePtr := flag.Bool("v", false, "increase verbosity of output")
readAllPtr := flag.Bool("a", false, "a bool representing whether to read logs from every contract or not")
configPtr := flag.String("config", "./config.json", "a string of the path to the config file")
keysPtr := flag.String("keystore", "./keystore", "a string of the path to the keystore directory")
// password flag assumes you have the same account on every chain
passwordPtr := flag.String("password", "password", "a string of the password to the account specified in the config file")
noListenPtr := flag.Bool("no-listen", false, "a bool; if true, do not start the listener")
/* subcommands */
depositCommand := flag.NewFlagSet("deposit", flag.ExitOnError)
fundCommand := flag.NewFlagSet("fund", flag.ExitOnError)
payCommand := flag.NewFlagSet("payCommand", flag.ExitOnError)
withdrawCommand := flag.NewFlagSet("withrawCommand", flag.ExitOnError)
/* admin subcommands */
addAuthority := flag.NewFlagSet("addauth", flag.ExitOnError)
removeAuthory := flag.NewFlagSet("removeauth", flag.ExitOnError)
// subcommands
if len(os.Args) > 1 {
switch os.Args[1] {
case "deposit":
depositCommand.Parse(os.Args[2:])
case "fund":
fundCommand.Parse(os.Args[2:])
case "pay":
payCommand.Parse(os.Args[2:])
case "withdraw":
withdrawCommand.Parse(os.Args[2:])
case "addauth":
addAuthority.Parse(os.Args[2:])
case "removeauth":
removeAuthory.Parse(os.Args[2:])
default:
// continue
}
}
flag.Parse()
header := *headerPtr
if header {
printHeader()
}
configStr := *configPtr
logger.Info("config path: %s", configStr)
verbose := *verbosePtr
if verbose {
logger.Info("verbose: %t", verbose)
}
readAll := *readAllPtr
if readAll {
logger.Info("read from all contracts? %t", readAll)
}
keystorePath := *keysPtr
logger.Info("keystore path: %s", keystorePath)
password := *passwordPtr
noListen := *noListenPtr
var isSubCommandParsed [4]bool
isSubCommandParsed[0] = depositCommand.Parsed()
isSubCommandParsed[1] = fundCommand.Parsed()
isSubCommandParsed[2] = payCommand.Parsed()
isSubCommandParsed[3] = withdrawCommand.Parsed()
var subCommandArgs [4][]string
subCommandArgs[0] = depositCommand.Args()
subCommandArgs[1] = fundCommand.Args()
subCommandArgs[2] = payCommand.Args()
subCommandArgs[3] = withdrawCommand.Args()
var chains []string
// Loop through arguments for the subcommand that is parsed, extract the password for either format --password="pass"
// or --password pass return the parameter before the index of the password -> [chains]
var commandsNotParsed = 0
for commandIndex, subCommand := range isSubCommandParsed {
if subCommand {
for paramIndex, param := range subCommandArgs[commandIndex] {
if strings.Contains(param, "--password") {
/*
Check if the index of the password flag == same length of all subcommand parameters
If == => --password="keystorePassword"
else if password flag index == length - 1 => --password keystorePassword
*/
if paramIndex == len(subCommandArgs[commandIndex])-1 {
password = subCommandArgs[commandIndex][paramIndex][11:len(subCommandArgs[commandIndex][paramIndex])]
} else {
password = subCommandArgs[commandIndex][paramIndex+1]
}
chains = subCommandArgs[commandIndex][0:paramIndex]
break
} else {
chains = subCommandArgs[commandIndex]
password = *passwordPtr
}
}
} else {
commandsNotParsed++
}
}
if commandsNotParsed == len(isSubCommandParsed) {
chains = flag.Args()
if len(chains) == 0 {
chains = append(chains, "1")
}
}
flags = make(map[string]bool)
flags["v"] = verbose
flags["a"] = readAll
flags["nolisten"] = noListen
/* keys */
ks = newKeyStore(keystorePath)
ksaccounts := ks.Accounts()
for i, account := range ksaccounts {
if verbose {
logger.Info("account %d: %s", i, account.Address.Hex())
}
}
// config file reading
path, _ := filepath.Abs(configStr)
file, err := ioutil.ReadFile(path)
if err != nil {
logger.FatalError("Failed to read file: %s", err)
}
clients := make([]*client.Chain, len(chains))
// unmarshal config
config := new(Config)
err = json.Unmarshal(file, config)
if err != nil {
logger.FatalError("could not unmarshal config: %s", err)
}
// read config file for each chain id
for i, name := range chains {
if _, ok := config.Chain[name]; ok {
// continue
} else {
logger.FatalError("could not find chain %s", name)
}
clients[i] = new(client.Chain)
clients[i].Id = config.Chain[name].Id
clients[i].Name = name
// to start at block 0, `rm -rf log/`
startBlock := startup(clients[i].Id)
clients[i].StartBlock = startBlock
contractAddr := config.Chain[name].Contract
logger.Info("contract address of chain %s: %s", name, contractAddr)
contract := new(common.Address)
contractBytes, err := hex.DecodeString(contractAddr[2:])
if err != nil {
logger.FatalError("%s", err)
}
contract.SetBytes(contractBytes)
clients[i].Contract = contract
url := config.Chain[name].Url
logger.Info("url of chain %s: %s", name, url)
clients[i].Url = url
gasPrice := config.Chain[name].GasPrice
clients[i].GasPrice = gasPrice
fromAccount := config.Chain[name].From
logger.Info("account to send txs from on chain %s: %s", name, fromAccount)
from := new(common.Address)
fromBytes, err := hex.DecodeString(fromAccount[2:])
if err != nil {
logger.FatalError("%s", err)
}
from.SetBytes(fromBytes)
clients[i].From = from
clients[i].Password = password
/* unlock account */
// if(ks.HasAddress(*from)) {
// account := new(accounts.Account)
// account.Address = *from
// err = ks.Unlock(*account, password)
// if err != nil {
// fmt.Println("could not unlock account")
// fmt.Println(err)
// } else {
// log.Fatal("account not found in keystore")
// }
// }
}
for _, chain := range clients {
/* dial client */
chainClient, err := ethclient.Dial(chain.Url)
if err != nil {
log.Fatal(err)
}
chain.Client = chainClient
}
/* read abi of contract in leth/build */
events := readAbi(flags["v"])
if depositCommand.Parsed() {
for _, name := range chains {
chain := client.FindChainByName(name, clients)
if chain == nil {
logger.FatalError("chain not found in config")
}
client.DepositPrompt(chain, ks)
}
return
} else if fundCommand.Parsed() {
for _, name := range chains {
chain := client.FindChainByName(name, clients)
if chain == nil {
logger.FatalError("chain not found in config")
}
client.FundPrompt(chain, ks)
}
return
} else if payCommand.Parsed() {
for _, name := range chains {
chain := client.FindChainByName(name, clients)
if chain == nil {
logger.FatalError("chain not found in config")
}
client.PayBridgePrompt(chain, ks)
}
return
} else if withdrawCommand.Parsed() {
for _, name := range chains {
chain := client.FindChainByName(name, clients)
if chain == nil {
logger.FatalError("chain not found in config")
}
client.WithdrawToPrompt(chain, ks)
}
return
} else if addAuthority.Parsed() {
for _, name := range chains {
chain := client.FindChainByName(name, clients)
if chain == nil {
logger.FatalError("chain not found in config")
}
//client.AddAuthorityPrompt(chain, ks)
}
return
}
/* channels */
doneClient := make(chan bool)
/* wait group for interrupt handling */
wg := new(sync.WaitGroup)
wg.Add(len(clients))
if !noListen {
/* listener */
logger.Info("listening for events...")
for _, chain := range clients {
go client.Listen(chain, clients, events, doneClient, ks, flags, wg)
}
<-doneClient
}
}