-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
375 lines (330 loc) · 11 KB
/
Copy pathmain.go
File metadata and controls
375 lines (330 loc) · 11 KB
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
package main
import (
"bytes"
"context"
"crypto/ecdsa"
"fmt"
"log"
"math/big"
"os"
"os/signal"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
cli "github.com/jawher/mow.cli"
ZapCommon "github.com/zapproject/pythia/common"
config "github.com/zapproject/pythia/config"
"github.com/zapproject/pythia/contracts"
"github.com/zapproject/pythia/contracts1"
"github.com/zapproject/pythia/contracts2"
db "github.com/zapproject/pythia/db"
"github.com/zapproject/pythia/ops"
"github.com/zapproject/pythia/rpc"
token "github.com/zapproject/pythia/token"
"github.com/zapproject/pythia/util"
"github.com/zapproject/pythia/vault"
)
var ctx context.Context
func ErrorHandler(err error, operation string) {
if err != nil {
fmt.Fprintf(os.Stderr, "%s failed: %s\n", operation, err.Error())
cli.Exit(-1)
}
}
func buildContext() error {
cfg := config.GetConfig()
if !cfg.EnablePoolWorker {
//create an rpc client
client, err := rpc.NewClient(cfg.NodeURL)
if err != nil {
log.Fatal(err)
}
//create an instance of the Zap master contract for on-chain interactions
tokenAddress := common.HexToAddress(cfg.TokenAddress)
contractAddress := common.HexToAddress(cfg.ContractAddress)
vaultAddress := common.HexToAddress(cfg.VaultAddress)
masterInstance, _ := contracts.NewZapMaster(contractAddress, client)
transactorInstance, _ := contracts1.NewZapTransactor(contractAddress, client)
newZapInstance, _ := contracts2.NewZap(contractAddress, client)
newTransactorInstance, _ := contracts2.NewZapTransactor(contractAddress, client)
tokenInstance, _ := token.NewZapTokenBSCTransactor(tokenAddress, client)
vaultInstance, _ := vault.NewVaultTransactor(vaultAddress, client)
ctx = context.WithValue(context.Background(), ZapCommon.ClientContextKey, client)
ctx = context.WithValue(ctx, ZapCommon.ContractAddress, contractAddress)
ctx = context.WithValue(ctx, ZapCommon.MasterContractContextKey, masterInstance)
ctx = context.WithValue(ctx, ZapCommon.TransactorContractContextKey, transactorInstance)
ctx = context.WithValue(ctx, ZapCommon.TokenTransactorContractContextKey, tokenInstance)
ctx = context.WithValue(ctx, ZapCommon.NewZapContractContextKey, newZapInstance)
ctx = context.WithValue(ctx, ZapCommon.NewTransactorContractContextKey, newTransactorInstance)
ctx = context.WithValue(ctx, ZapCommon.VaultTransactorContractContextKey, vaultInstance)
privateKey, err := crypto.HexToECDSA(cfg.PrivateKey)
if err != nil {
return fmt.Errorf("problem getting private key: %s", err.Error())
}
ctx = context.WithValue(ctx, ZapCommon.PrivateKey, privateKey)
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return fmt.Errorf("error casting public key to ECDSA")
}
publicAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
ctx = context.WithValue(ctx, ZapCommon.PublicAddress, publicAddress)
s, err := client.IsSyncing(ctx)
if err != nil {
return fmt.Errorf("could not determine if Ethereum client is syncing: %v\n", err)
}
if s {
return fmt.Errorf("ethereum node is still sycning with the network")
}
}
return nil
}
func AddDBToCtx(remote bool) error {
cfg := config.GetConfig()
//create a db instance
os.RemoveAll(cfg.DBFile)
DB, err := db.Open(cfg.DBFile)
if err != nil {
return err
}
var dataProxy db.DataServerProxy
if remote {
proxy, err := db.OpenRemoteDB(DB)
if err != nil {
log.Fatal(err)
}
dataProxy = proxy
} else {
proxy, err := db.OpenLocalProxy(DB)
if err != nil {
log.Fatal(err)
}
dataProxy = proxy
}
ctx = context.WithValue(ctx, ZapCommon.DataProxyKey, dataProxy)
ctx = context.WithValue(ctx, ZapCommon.DBContextKey, DB)
return nil
}
var GitTag string
var GitHash string
const versionMessage = `
The official Pythia %s (%s)
-----------------------------------------
Website: https://Zap.org
Github: https://github.com/zapproject/pythia
`
func App() *cli.Cli {
app := cli.App("Pythia", "The Zap.org official miner")
//app wide config options
configPath := app.StringOpt("config", "config.json", "Path to the primary JSON config file")
logPath := app.StringOpt("logConfig", "loggingConfig.json", "Path to a JSON logging config file")
//this will get run before any of the commands
app.Before = func() {
ErrorHandler(config.ParseConfig(*configPath), "parsing config file")
ErrorHandler(util.ParseLoggingConfig(*logPath), "parsing log file")
ErrorHandler(buildContext(), "building context")
}
versionMessage := fmt.Sprintf(versionMessage, GitTag, GitHash)
app.Version("version", versionMessage)
app.Command("stake", "\U0001F510 staking operations", stakeCmd)
app.Command("transfer", "\U0001F381 send ZAP to address", moveCmd(ops.Transfer))
app.Command("approve", "\U00002705 approve ZAP to address", moveCmd(ops.Approve))
app.Command("balance", "\U0001F440 check balance of address", balanceCmd)
app.Command("dispute", "\U00002696 dispute operations", disputeCmd)
app.Command("mine", "\U000026CF mine for ZAP", mineCmd)
app.Command("dataserver", "\U0001F5C4 start an independent dataserver", dataserverCmd)
return app
}
func stakeCmd(cmd *cli.Cmd) {
cmd.Command("deposit", "\U0001F512 deposit ZAP stake", simpleCmd(ops.Deposit))
cmd.Command("withdraw", "\U0001F511 withdraw ZAP stake", simpleCmd(ops.WithdrawStake))
cmd.Command("request", "\U000023F2 request to withdraw ZAP stake", simpleCmd(ops.RequestStakingWithdraw))
cmd.Command("status", "\U0001F52E show current staking status", simpleCmd(ops.ShowStatus))
}
func simpleCmd(f func(context.Context) error) func(*cli.Cmd) {
return func(cmd *cli.Cmd) {
cmd.Action = func() {
ErrorHandler(f(ctx), "")
}
}
}
func moveCmd(f func(common.Address, *big.Int, context.Context) error) func(*cli.Cmd) {
return func(cmd *cli.Cmd) {
amt := ZAPAmount{}
addr := ETHAddress{}
cmd.VarArg("AMOUNT", &amt, "amount to transfer")
cmd.VarArg("ADDRESS", &addr, "ethereum public address")
cmd.Action = func() {
ErrorHandler(f(addr.addr, amt.Int, ctx), "move")
}
}
}
func balanceCmd(cmd *cli.Cmd) {
addr := ETHAddress{}
cmd.VarArg("ADDRESS", &addr, "binance public address")
cmd.Spec = "[ADDRESS]"
cmd.Action = func() {
var zero [20]byte
if bytes.Compare(addr.addr.Bytes(), zero[:]) == 0 {
addr.addr = ctx.Value(ZapCommon.PublicAddress).(common.Address)
}
ErrorHandler(ops.Balance(ctx, addr.addr), "checking balance")
}
}
func disputeCmd(cmd *cli.Cmd) {
cmd.Command("vote", "\U00002696 vote on an active dispute", voteCmd)
cmd.Command("new", "\U0001F4C4 start a new dispute", newDisputeCmd)
cmd.Command("show", "\U0001F4CA show existing disputes", simpleCmd(ops.List))
}
func voteCmd(cmd *cli.Cmd) {
disputeID := EthereumInt{}
cmd.VarArg("DISPUTE_ID", &disputeID, "dispute id")
supports := cmd.BoolArg("SUPPORT", false, "do you support the dispute? (true|false)")
cmd.Action = func() {
ErrorHandler(ops.Vote(disputeID.Int, *supports, ctx), "vote")
}
}
func newDisputeCmd(cmd *cli.Cmd) {
requestID := EthereumInt{}
timestamp := EthereumInt{}
minerIndex := EthereumInt{}
cmd.VarArg("REQUEST_ID", &requestID, "request id")
cmd.VarArg("TIMESTAMP", ×tamp, "timestamp")
cmd.VarArg("MINER_INDEX", &minerIndex, "miner to dispute (0-4)")
cmd.Action = func() {
ErrorHandler(ops.Dispute(requestID.Int, timestamp.Int, minerIndex.Int, ctx), "new dispute")
}
}
func mineCmd(cmd *cli.Cmd) {
remoteDS := cmd.BoolOpt("remote r", false, "connect to remote dataserver")
cmd.Action = func() {
//create os kill sig listener
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
exitChannels := make([]*chan os.Signal, 0)
cfg := config.GetConfig()
var ds *ops.DataServerOps
if !cfg.EnablePoolWorker {
ErrorHandler(AddDBToCtx(*remoteDS), "\U0001F5C4 initializing database \U0001F5C4")
if !*remoteDS {
ch := make(chan os.Signal)
exitChannels = append(exitChannels, &ch)
var err error
ds, err = ops.CreateDataServerOps(ctx, ch)
if err != nil {
log.Fatal(err)
}
//start and wait for it to be ready
ds.Start(ctx)
<-ds.Ready()
}
}
//start miner
ch := make(chan os.Signal)
exitChannels = append(exitChannels, &ch)
miner, err := ops.CreateMiningManager(ctx, ch, ops.NewSubmitter())
if err != nil {
log.Fatal(err)
}
miner.Start(ctx)
//now we wait for kill sig
<-c
//and then notify exit channels
for _, ch := range exitChannels {
*ch <- os.Interrupt
}
cnt := 0
start := time.Now()
for {
cnt++
dsStopped := false
minerStopped := false
if ds != nil {
dsStopped = !ds.Running
} else {
dsStopped = true
}
if miner != nil {
minerStopped = !miner.Running
} else {
minerStopped = true
}
if !dsStopped && !minerStopped && cnt > 60 {
fmt.Printf("\U000026A0 Taking longer than expected to stop operations. Waited %v so far\n", time.Now().Sub(start))
} else if dsStopped && minerStopped {
break
}
time.Sleep(500 * time.Millisecond)
}
fmt.Printf("Main shutdown complete \U00002622\n")
}
}
func dataserverCmd(cmd *cli.Cmd) {
cmd.Action = func() {
//create os kill sig listener
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
var ds *ops.DataServerOps
ErrorHandler(AddDBToCtx(true), "\U0001F5C4 initializing database \U0001F5C4")
ch := make(chan os.Signal)
var err error
ds, err = ops.CreateDataServerOps(ctx, ch)
if err != nil {
log.Fatal(err)
}
//start and wait for it to be ready
ds.Start(ctx)
<-ds.Ready()
//now we wait for kill sig
<-c
//and then notify exit channels
ch <- os.Interrupt
cnt := 0
start := time.Now()
for {
cnt++
dsStopped := false
if ds != nil {
dsStopped = !ds.Running
} else {
dsStopped = true
}
if !dsStopped && cnt > 60 {
fmt.Printf("\U000026A0 Taking longer than expected to stop operations. Waited %v so far\n", time.Now().Sub(start))
} else if dsStopped {
break
}
time.Sleep(500 * time.Millisecond)
}
fmt.Printf("Main shutdown complete \U00002622\n")
}
}
func listenTransfers(client rpc.ETHClient, cfg *config.Config) {
tokenAddress := common.HexToAddress(cfg.TokenAddress)
query := ethereum.FilterQuery{
Addresses: []common.Address{tokenAddress},
}
logs := make(chan types.Log)
sub, err := client.SubscribeFilterLogs(context.Background(), query, logs)
if err != nil {
log.Fatal(err)
}
for {
select {
case err := <-sub.Err():
log.Fatal(err)
case vLog := <-logs:
fmt.Println(vLog)
}
}
}
func main() {
//see, programming is easy. Just create an App() and run it!!!!!
app := App()
err := app.Run(os.Args)
if err != nil {
fmt.Fprintf(os.Stderr, "\U0001F6AB app.Run failed: %v\n", err)
}
}