/
eth_helpers.go
309 lines (272 loc) · 7.09 KB
/
eth_helpers.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
package onchain
import (
"context"
"fmt"
"io/ioutil"
"math"
"math/big"
"runtime/debug"
"sync"
"time"
errors "golang.org/x/xerrors"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/light"
)
const (
checkSyncInterval = 15
syncBlockDiff = 3
)
type DialResult struct {
Client *ethclient.Client
Url string
Err error
}
func first(ctx context.Context, source <-chan interface{}) <-chan interface{} {
out := make(chan interface{})
go func() {
defer close(out)
first := true
for val := range source {
if first {
if val != nil {
first = false
select {
case <-ctx.Done():
return
case out <- val:
}
return
}
}
}
}()
return out
}
func merge(ctx context.Context, cs ...chan interface{}) chan interface{} {
var wg sync.WaitGroup
out := make(chan interface{})
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan interface{}) {
for n := range c {
select {
case <-ctx.Done():
return
case out <- n:
}
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
// Start a goroutine to close out once all the output goroutines are
// done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}
func mergeError(ctx context.Context, cs ...chan error) chan error {
var wg sync.WaitGroup
out := make(chan error)
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan error) {
for n := range c {
select {
case <-ctx.Done():
return
case out <- n:
}
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
// Start a goroutine to close out once all the output goroutines are
// done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}
func GenEthkey(credentialPath, passPhrase string) (err error) {
debug.FreeOSMemory()
newKeyStore := keystore.NewKeyStore(credentialPath, keystore.StandardScryptN, keystore.StandardScryptP)
if len(newKeyStore.Accounts()) >= 1 {
fmt.Println("", newKeyStore.Accounts()[0].URL.Path)
err = errors.New("Found an existing key in " + credentialPath)
return
}
_, err = newKeyStore.NewAccount(passPhrase)
debug.FreeOSMemory()
return
}
func NumOfAccounts(credentialPath string) (n int) {
newKeyStore := keystore.NewKeyStore(credentialPath, keystore.StandardScryptN, keystore.StandardScryptP)
if newKeyStore != nil {
n = len(newKeyStore.Accounts())
}
return
}
//ReadEthKey is a utility function to read a keystore file
func ReadEthKey(credentialPath, passphrase string) (key *keystore.Key, err error) {
newKeyStore := keystore.NewKeyStore(credentialPath, keystore.StandardScryptN, keystore.StandardScryptP)
if len(newKeyStore.Accounts()) < 1 {
return nil, errors.New("No Account")
}
usrKeyPath := newKeyStore.Accounts()[0].URL.Path
keyJson, err := ioutil.ReadFile(usrKeyPath)
if err != nil {
return
}
key, err = keystore.DecryptKey(keyJson, passphrase)
return
}
func reporeResult(ctx context.Context, out chan DialResult, result DialResult) {
select {
case <-ctx.Done():
case out <- result:
}
}
//DialToEth is a utility function to dial to Ethereum
func DialToEth(ctx context.Context, urlPool []string) (out chan DialResult) {
out = make(chan DialResult)
var wg sync.WaitGroup
multiplex := func(url string) {
r := DialResult{}
var err error
defer wg.Done()
client, err := ethclient.Dial(url)
if err != nil {
//ws connect: connection timed out
r.Err = errors.Errorf(": %w", err)
reporeResult(ctx, out, r)
return
}
if _, err := client.NetworkID(ctx); err != nil {
fmt.Println("NetworkID err ", err)
//Post http i/o timeout
r.Err = errors.Errorf(": %w", err)
reporeResult(ctx, out, r)
client.Close()
return
}
progress, err := client.SyncProgress(ctx)
if err != nil {
fmt.Println("SyncProgress err ", err, url)
return
}
if progress != nil {
fmt.Println("progress ", progress)
}
fmt.Println(url, "DialToEthr got a client ")
r.Client = client
r.Url = url
reporeResult(ctx, out, r)
}
// Select from all the channels
wg.Add(len(urlPool))
go func() {
for i := 0; i < len(urlPool); i++ {
go multiplex(urlPool[i])
}
}()
// Wait for all the reads to complete
go func() {
wg.Wait()
close(out)
}()
return
}
//CheckSync is a utility function to check sync state
func CheckSync(ctx context.Context, cs chan *ethclient.Client) chan *ethclient.Client {
out := make(chan *ethclient.Client)
var wg sync.WaitGroup
size := 0
for client := range cs {
size++
go func(client *ethclient.Client) {
defer wg.Done()
var blk *types.Block
var progress *ethereum.SyncProgress
var err error
if blk, err = client.BlockByNumber(ctx, nil); err != nil {
fmt.Println("CheckSync error ", err)
if err.Error() == light.ErrNoPeers.Error() {
fmt.Println("CheckSync error ErrNoPeers ", err)
}
return
}
highestBlkN := blk.NumberU64()
fmt.Println("highestBlkN ", highestBlkN)
if progress, err = client.SyncProgress(ctx); err != nil {
fmt.Println("SyncProgress err ", err)
return
}
fmt.Println("progress ", progress)
}(client)
}
wg.Add(size)
// Wait for all the reads to complete
go func() {
wg.Wait()
close(out)
}()
return out
}
// GetCurrentBlock returns a block number of latest known header from the
// current canonical chain.
func GetCurrentBlock(client *ethclient.Client) (blknum uint64, err error) {
var header *types.Header
header, err = client.HeaderByNumber(context.Background(), nil)
if err == nil {
blknum = header.Number.Uint64()
}
return
}
// CheckTransaction return an error if the transaction is failed
func CheckTransaction(client *ethclient.Client, tx *types.Transaction) (err error) {
start := time.Now()
receipt, err := client.TransactionReceipt(context.Background(), tx.Hash())
for err == ethereum.NotFound {
if time.Since(start).Minutes() > 30 {
err = errors.New("transaction not found")
fmt.Println("transaction failed. tx ", fmt.Sprintf("%x", tx.Hash()))
return
}
time.Sleep(15 * time.Second)
receipt, err = client.TransactionReceipt(context.Background(), tx.Hash())
}
if err != nil {
fmt.Println("CheckTransaction ", err)
return
}
if receipt.Status == 1 {
fmt.Println("transaction confirmed. tx ", fmt.Sprintf("%x", tx.Hash()))
} else {
err = errors.New("transaction failed")
fmt.Println("transaction Status != 0 . tx ", fmt.Sprintf("%x", tx.Hash()))
}
return
}
// GetBalance returns the wei balance of the given account.
func GetBalance(client *ethclient.Client, key *keystore.Key) (balance *big.Float, err error) {
wei, err := client.BalanceAt(context.Background(), key.Address, nil)
if err != nil {
return
}
balance = new(big.Float)
balance.SetString(wei.String())
balance = balance.Quo(balance, big.NewFloat(math.Pow10(18)))
return
}