-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlib.go
More file actions
638 lines (566 loc) · 17.2 KB
/
lib.go
File metadata and controls
638 lines (566 loc) · 17.2 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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
package main
import (
"context"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"math/big"
"os"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/usbwallet"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/shopspring/decimal"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/reserve-protocol/trezor"
)
var defaultKeys = []string{
"f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d",
"5d862464fe9303452126c8bc94274b8c5f9874cbd219789b3eb2128075a76f72",
"df02719c4df8b9b8ac7f551fcb5d9ef48fa27eef7a66453879f4d8fdc6e78fb1",
"ff12e391b79415e941a94de3bf3a9aee577aed0731e297d5cfa0b8a1e02fa1d0",
"752dd9cf65e68cfaba7d60225cbdbc1f4729dd5e5507def72815ed0d8abc6249",
"efb595a0178eb79a8df953f87c5148402a224cdf725e88c0146727c6aceadccd",
"83c6d2cc5ddcf9711a6d59b417dc20eb48afd58d45290099e5987e3d768f328f",
"bb2d3f7c9583780a7d3904a2f55d792707c345f21de1bacb2d389934d82796b2",
"b2fd4d29c1390b71b8795ae81196bfd60293adf99f9d32a0aff06288fcdac55f",
"23cb7121166b9a2f93ae0b7c05bde02eae50d64449b2cbb42bc84e9d38d6cc89",
}
var exitFuncs []func()
func atExit(f func()) {
exitFuncs = append(exitFuncs, f)
}
func runExitFuncs() {
for _, f := range exitFuncs {
f()
}
}
func exit(code int) {
runExitFuncs()
os.Exit(code)
}
func fatal(a ...interface{}) {
fmt.Fprintln(os.Stderr, a...)
exit(1)
}
func fatalf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
exit(1)
}
var client *ethclient.Client
func getNode() *ethclient.Client {
if client == nil {
var err error
nodeAddr := viper.GetString("node")
client, err = ethclient.Dial(nodeAddr)
check(err, fmt.Sprintf("Failed to connect to Ethereum node (is there a node running at %q?)", nodeAddr))
}
return client
}
var (
singletonAccount accounts.Account
singletonWallet accounts.Wallet
)
func openHardwareWallet() (accounts.Wallet, accounts.Account) {
if singletonWallet != nil {
return singletonWallet, singletonAccount
}
// Open hardware wallet.
{
// Check for connected Ledgers and Trezors.
ledgerHub, err := usbwallet.NewLedgerHub()
check(err, "calling usbwallet.NewLedgerHub()")
trezorHub, err := usbwallet.NewTrezorHub()
check(err, "calling usbwallet.NewTrezorHub()")
// Collect them into a single list.
wallets := accounts.NewManager(nil, ledgerHub, trezorHub).Wallets()
// Don't proceed unless there is exactly one hardware wallet available.
if len(wallets) == 0 {
fatal("No hardware wallets found. Is a hardware wallet plugged in? If it's a Ledger, is it unlocked?")
}
if len(wallets) > 1 {
fatalf("%v hardware wallets found, I don't know which to use", len(wallets))
}
wallet := wallets[0]
// "Open" the wallet.
// This exchanges initial handshake messages with the wallet.
// On a Trezor, this may require PIN entry.
err = wallet.Open("")
if err == usbwallet.ErrTrezorPINNeeded {
pin, pinErr := trezor.GetPIN("enter PIN")
check(pinErr, "getting PIN input")
err = wallet.Open(pin)
}
check(err, "opening hardware wallet")
// Notify the wallet when the program exits.
atExit(func() {
wallet.Close()
})
singletonWallet = wallet
}
// Open account.
{
path := viper.GetString("derivation-path")
if path == "" {
fatal("`derivation-path` flag is empty, but `from` is set to \"hardware\". I can't use a hardware wallet without a derivation path.")
}
if !strings.HasPrefix(path, "m/") {
fatalf("got invalid derivation-path: %q. Derivation path must start with \"m/\".", path)
}
parsed, err := accounts.ParseDerivationPath(path)
if err != nil {
fatalf("got invalid derivation-path: %q. %v", path, err)
}
singletonAccount, err = singletonWallet.Derive(
parsed,
true, // "pin" this account -- needed for the wallet object to recognize it later in "wallet.SignTx"
)
if err != nil && err.Error() == "reply lacks public key entry" {
fatal("Failed to get public key. Is the Ethereum app open on the Ledger?")
}
check(err, "deriving account")
}
return singletonWallet, singletonAccount
}
func getNetID() *big.Int {
netID, err := getNode().NetworkID(context.Background())
check(err, "Failed to get Ethereum network id")
return netID
}
func getGasPrice() *big.Int {
gasPriceFlag := viper.GetInt64("gasPrice")
if gasPriceFlag == 0 {
price, err := getNode().SuggestGasPrice(context.Background())
check(err, "retrieving gas price suggestion")
return price
}
price := big.NewInt(gasPriceFlag)
price.Mul(price, big.NewInt(1e9))
return price
}
func getOptimizeRuns() string {
optimizeRunsFlag := viper.GetString("optimize-runs")
if optimizeRunsFlag == "" {
optimizeRunsFlag = "1"
}
return optimizeRunsFlag
}
func getTxnOpts() *bind.TransactOpts {
from := viper.GetString("from")
var txnOpts *bind.TransactOpts
if from != "hardware" {
txnOpts = bind.NewKeyedTransactor(parseKey(from))
} else {
wallet, account := openHardwareWallet()
txnOpts = &bind.TransactOpts{
From: account.Address,
Signer: func(
protocolSigner types.Signer,
from common.Address,
tx *types.Transaction,
) (*types.Transaction, error) {
if from != account.Address {
fatalf(
"unexpected `from` address. from=%v account=%v",
from.Hex(),
account.Address.Hex(),
)
}
fmt.Println("Waiting for you to confirm on the hardware wallet...")
return wallet.SignTx(account, tx, getNetID())
},
}
}
txnOpts.GasPrice = getGasPrice()
// TODO: options for bumping or setting the gas limit, maybe the eth value, and maybe even the nonce.
return txnOpts
}
var deployment *bind.BoundContract
func getDeployment(abi abi.ABI) *bind.BoundContract {
if deployment == nil {
address := viper.GetString("address")
if address == "" {
fmt.Fprintln(os.Stderr, "No address specified for the contract.")
fmt.Fprintln(os.Stderr, "To specify an address, set the --address flag or the POKE_ADDRESS environment variable.")
exit(1)
}
deployment = bind.NewBoundContract(hexToAddress(address), abi, getNode(), getNode(), getNode())
}
return deployment
}
// TODO (issue #13): It'd be cleaner for the addresses currently named
// "@0" through "@9" on the command line to just be name "0" through
// "9" -- and then this setting (and the later parseKey) need not go
// through os.Getenv.
func init() {
for i, key := range defaultKeys {
envVar := "POKE_" + strconv.Itoa(i)
if os.Getenv(envVar) == "" {
os.Setenv(envVar, key)
}
}
}
// parseKey parses a hex-encoded private key from s.
// Alternatively, if s begins with "@", parseKey parses
// a hex-encoded private key from the environment variable
// named "POKE_<s[1:]>".
func parseKey(s string) *ecdsa.PrivateKey {
origS := s
if strings.HasPrefix(s, "@") {
env := os.Getenv("POKE_" + s[1:])
if s == "" {
fatalf(
"To use a shorthand argument like %q, there should be a non-empty corresponding environment variable called %q\n",
s,
"POKE_"+s[1:],
)
}
s = env
}
keyBytes, err1 := hex.DecodeString(s)
key, err2 := crypto.ToECDSA(keyBytes)
if err1 != nil || err2 != nil {
fmt.Fprintln(os.Stderr, "Failed to parse private key:", s)
if strings.HasPrefix(origS, "@") {
fatalf(
"(From argument %q, which I expanded using the env var %v)\n",
origS,
"POKE_"+origS[1:],
)
}
}
return key
}
// HexToAddress parses s into a common.Address.
// Unlike go-ethereum's common.HexToAddress, this version
// exits if s is not a valid address encoding.
// This is copied and lightly modifed from:
// https://github.com/reserve-protocol/reserve/tree/686b03e/pkg/eth
func hexToAddress(s string) common.Address {
b, err := hex.DecodeString(strings.TrimPrefix(s, "0x"))
check(err, fmt.Sprintf("invalid hex string %q", s))
var address common.Address
if len(b) != len(address) {
fatalf("invalid address length: %v", len(b))
}
address.SetBytes(b)
return address
}
// parseAddress parses a hex-encoded address from s.
// Alternatively, if s begins with "@", parseAddress parses
// a hex-encoded private key from the environment variable
// named "POKE_<s[1:]>", then returns the address corresponding
// to that key.
func parseAddress(s string) common.Address {
if strings.HasPrefix(s, "@") {
return toAddress(parseKey(s))
}
return hexToAddress(s)
}
// parseAddressArray parses an array of hex addresses into common.Address's.
// All arrays are assumed to start with "[" and end with "]", and are comma-separated.
func parseAddressArray(s string) []common.Address {
parts := parseArray(s)
asAddresses := make([]common.Address, len(parts))
for i, part := range parts {
asAddresses[i] = parseAddress(part)
}
return asAddresses
}
// parseUint256 parses an atto number of tokens, parsing scientific notation if necessary.
// For example, ".33e4" -> 3300. However, "3300" is perfectly acceptable as well.
// It also requires that long numbers use commas.
func parseUint256(s string) *big.Int {
exp := 0
var err error
index := strings.Index(s, "e")
if index != -1 {
assert(index+1 < len(s), "integers must follow `e` in scientific notation")
exp, err = strconv.Atoi(s[index+1:])
check(err, "scientific notation exponent must be a natural number")
s = s[:index]
}
index = strings.Index(s, ".")
if index != -1 {
assert(index+1 < len(s), "no hanging decimals points")
assertUnderscoreSeparated(s[0:index])
assertUnderscoreSeparated(reverse(s[index+1:])) // .123_4 not .1_234
} else {
assertUnderscoreSeparated(s)
}
base, err := decimal.NewFromString(strings.ReplaceAll(s, "_", ""))
check(err, fmt.Sprintf("Expected a decimal number, but got %q instead.\n", s))
return truncateDecimal(base.Shift(int32(exp)))
}
// parseUint256Array parses an array of Uint256's according to `parseUint256`.
// All arrays are assumed to start with "[" and end with "]", and are comma-separated.
func parseUint256Array(s string) []*big.Int {
parts := parseArray(s)
asBigs := make([]*big.Int, len(parts))
for i, part := range parts {
asBigs[i] = parseUint256(part)
}
return asBigs
}
func parseBool(s string) bool {
b, err := strconv.ParseBool(s)
check(err, fmt.Sprintf("failed to parse %q as bool due to %v", s, err))
return b
}
func parseBoolArray(s string) []bool {
parts := parseArray(s)
asBools := make([]bool, len(parts))
for i, part := range parts {
asBools[i] = parseBool(part)
}
return asBools
}
// truncateDecimal truncates d to an integer and returns it as a *big.Int.
func truncateDecimal(d decimal.Decimal) *big.Int {
coeff := d.Coefficient()
exp := d.Exponent()
z := new(big.Int)
if exp >= 0 {
// coeff * 10 ** exp
return coeff.Mul(coeff, z.Exp(big.NewInt(10), big.NewInt(int64(exp)), nil))
}
// coeff / 10 ** -exp
return coeff.Div(coeff, z.Exp(big.NewInt(10), big.NewInt(int64(-exp)), nil))
}
// displayBigInt does not modify the atto amount, yielding a display in atto.
// It outputs in scientific notation when possible.
func displayBigInt(i *big.Int) string {
i_str := decimal.NewFromBigInt(i, 0).String()
if i_str == "0" {
return i_str
}
index := len(i_str) - 1
for ; index >= 0; index-- {
if i_str[index] != '0' {
break
}
}
sci := i_str[0 : index+1]
zeros := len(i_str) - 1 - index
if zeros > 0 {
sci += "e" + strconv.Itoa(zeros)
}
return sci
}
func displayBigIntArray(arr *[]*big.Int) string {
strArr := make([]string, len(*arr))
for i, a := range *arr {
strArr[i] = displayBigInt(a)
}
return "[" + strings.Join(strArr, ", ") + "]"
}
func displayAddressArray(arr *[]common.Address) string {
strArr := make([]string, len(*arr))
for i, a := range *arr {
strArr[i] = a.Hex()
}
return "[" + strings.Join(strArr, ", ") + "]"
}
func displayBoolArray(arr *[]bool) string {
strArr := make([]string, len(*arr))
for i, a := range *arr {
strArr[i] = strconv.FormatBool(a)
}
return "[" + strings.Join(strArr, ", ") + "]"
}
func toAddress(key *ecdsa.PrivateKey) common.Address {
return crypto.PubkeyToAddress(key.PublicKey)
}
func keyToHex(key *ecdsa.PrivateKey) string {
return hex.EncodeToString(crypto.FromECDSA(key))
}
func parseArray(s string) []string {
s = strings.ReplaceAll(s, "[", "")
s = strings.ReplaceAll(s, "]", "")
s = strings.ReplaceAll(s, " ", "")
parts := strings.Split(s, ",")
return parts
}
// log logs the result of a mutator txn to stdout, including that txn's events.
func log(name string, tx *types.Transaction, abi abi.ABI, err error) {
check(err, name+" failed")
receipt, err := bind.WaitMined(context.Background(), getNode(), tx)
check(err, "waiting for "+name+" to be mined")
if receipt.Status != types.ReceiptStatusSuccessful {
fatal("transaction reverted")
}
fmt.Printf("Gas Used: %v\n", receipt.GasUsed)
deployment := getDeployment(abi)
if len(receipt.Logs) > 0 {
fmt.Println("Done. Events:")
for _, log := range receipt.Logs {
// TODO: handle logs from dependencies
for name, event := range abi.Events {
if log.Topics[0] == event.Id() {
m := make(map[string]interface{})
err := deployment.UnpackLogIntoMap(m, name, *log)
if err == nil {
fmt.Println("\t" + name)
for key, value := range m {
if addr, ok := value.(common.Address); ok {
value = addr.Hex()
}
fmt.Printf("\t\t%v: %v\n", key, value)
}
} else {
fmt.Println("\t" + err.Error())
}
break
}
}
}
} else {
fmt.Println("< Done. No events generated >")
}
}
func getAddress() common.Address {
from := viper.GetString("from")
if from == "hardware" {
_, account := openHardwareWallet()
return account.Address
}
return toAddress(parseKey(from))
}
func deployCmd(name string, abi abi.ABI, bytecode []byte) *cobra.Command {
parts := []string{"deploy"}
for _, input := range abi.Constructor.Inputs {
if input.Name == "" {
parts = append(parts, "<"+input.Type.String()+">")
} else {
parts = append(parts, "<"+input.Name+">")
}
}
return &cobra.Command{
Use: strings.Join(parts, " "),
Short: "Deploy a new copy of " + name,
Args: cobra.ExactArgs(len(abi.Constructor.Inputs)),
Run: func(cmd *cobra.Command, args []string) {
inputs := make([]interface{}, len(args))
for i, arg := range args {
inputs[i] = solTypes[abi.Constructor.Inputs[i].Type.String()].parser(arg)
}
address, tx, _, err := bind.DeployContract(
getTxnOpts(),
abi,
bytecode,
getNode(),
inputs...,
)
viper.Set("address", address.Hex())
log("deployment", tx, abi, err)
fmt.Println("export POKE_ADDRESS=" + address.Hex())
},
}
}
var addressCmd = &cobra.Command{
Use: "address",
Short: "Get the address corresponding to the `from` account",
Example: " poke address\n poke address -F @1",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(getAddress().Hex())
},
}
var showGasCmd = &cobra.Command{
Use: "show-gas",
Short: "Show the current gas price estimate.",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
gasPrice, err := getNode().SuggestGasPrice(ctx)
check(err, "retrieving gas price suggestion")
fmt.Println(gasPrice)
},
}
var showWeiCmd = &cobra.Command{
Use: "show-wei <address>",
Short: "Show WEI balance.",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
address := parseAddress(args[0])
wei, err := getNode().BalanceAt(ctx, address, nil)
check(err, "retrieving wei balance")
fmt.Printf("%v wei\n", wei)
},
}
var sendWeiCmd = &cobra.Command{
Use: "send-wei <address> <value>",
Short: "Send WEI (1e18 WEI = 1 ETH) to an address.",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
nonce, err := getNode().PendingNonceAt(ctx, getAddress())
check(err, "retrieving nonce")
address := parseAddress(args[0])
attoTokens := parseUint256(args[1])
tx, err := getTxnOpts().Signer(
types.NewEIP155Signer(getNetID()),
getAddress(),
types.NewTransaction(
nonce,
address,
attoTokens,
21000,
getGasPrice(),
nil,
),
)
check(err, "signing transaction")
check(getNode().SendTransaction(ctx, tx), "sending transaction")
fmt.Printf("Sent %v WEI to %v.\n", attoTokens, address.Hex())
},
}
var codeAtCmd = &cobra.Command{
Use: "code-at <address>",
Short: "Get contract code at an address",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
code, err := getNode().CodeAt(
context.Background(),
parseAddress(args[0]),
nil,
)
check(err, "retrieving code")
fmt.Println(hex.EncodeToString(code))
},
}
func assert(val bool, msg string) {
if !val {
fatal(msg + ":")
}
}
func check(err error, msg string) {
if err != nil {
fatal(msg+":", err)
}
}
func assertUnderscoreSeparated(s string) {
rev := reverse(s)
for i, val := range rev {
if i%4 == 3 {
assert(val == '_', "long inputs must contain underscores exactly every three digits, both on the left and right of the decimal")
} else {
assert(val != '_', "long inputs must contain underscores exactly every three digits, both on the left and right of the decimal")
}
}
}
func reverse(orig string) string {
var c []string = strings.Split(orig, "")
for i, j := 0, len(c)-1; i < j; i, j = i+1, j-1 {
c[i], c[j] = c[j], c[i]
}
return strings.Join(c, "")
}