forked from onrik/ethrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ethrpc.go
514 lines (408 loc) · 14.5 KB
/
ethrpc.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
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
package ethrpc
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/big"
"net/http"
"os"
)
// EthError - ethereum error
type EthError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (err EthError) Error() string {
return fmt.Sprintf("Error %d (%s)", err.Code, err.Message)
}
type ethResponse struct {
ID int `json:"id"`
JSONRPC string `json:"jsonrpc"`
Result json.RawMessage `json:"result"`
Error *EthError `json:"error"`
}
type ethRequest struct {
ID int `json:"id"`
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params []interface{} `json:"params"`
}
// EthRPC - Ethereum rpc client
type EthRPC struct {
url string
client httpClient
log logger
Debug bool
}
// New create new rpc client with given url
func New(url string, options ...func(rpc *EthRPC)) *EthRPC {
rpc := &EthRPC{
url: url,
client: http.DefaultClient,
log: log.New(os.Stderr, "", log.LstdFlags),
}
for _, option := range options {
option(rpc)
}
return rpc
}
// NewEthRPC create new rpc client with given url
func NewEthRPC(url string, options ...func(rpc *EthRPC)) *EthRPC {
return New(url, options...)
}
func (rpc *EthRPC) call(method string, target interface{}, params ...interface{}) error {
result, err := rpc.Call(method, params...)
if err != nil {
return err
}
if target == nil {
return nil
}
return json.Unmarshal(result, target)
}
// URL returns client url
func (rpc *EthRPC) URL() string {
return rpc.url
}
// Call returns raw response of method call
func (rpc *EthRPC) Call(method string, params ...interface{}) (json.RawMessage, error) {
request := ethRequest{
ID: 1,
JSONRPC: "2.0",
Method: method,
Params: params,
}
body, err := json.Marshal(request)
if err != nil {
return nil, err
}
response, err := rpc.client.Post(rpc.url, "application/json", bytes.NewBuffer(body))
if response != nil {
defer response.Body.Close()
}
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if rpc.Debug {
rpc.log.Println(fmt.Sprintf("%s\nRequest: %s\nResponse: %s\n", method, body, data))
}
resp := new(ethResponse)
if err := json.Unmarshal(data, resp); err != nil {
return nil, err
}
if resp.Error != nil {
return nil, *resp.Error
}
return resp.Result, nil
}
// RawCall returns raw response of method call (Deprecated)
func (rpc *EthRPC) RawCall(method string, params ...interface{}) (json.RawMessage, error) {
return rpc.Call(method, params...)
}
// Web3ClientVersion returns the current client version.
func (rpc *EthRPC) Web3ClientVersion() (string, error) {
var clientVersion string
err := rpc.call("web3_clientVersion", &clientVersion)
return clientVersion, err
}
// Web3Sha3 returns Keccak-256 (not the standardized SHA3-256) of the given data.
func (rpc *EthRPC) Web3Sha3(data []byte) (string, error) {
var hash string
err := rpc.call("web3_sha3", &hash, fmt.Sprintf("0x%x", data))
return hash, err
}
// NetVersion returns the current network protocol version.
func (rpc *EthRPC) NetVersion() (string, error) {
var version string
err := rpc.call("net_version", &version)
return version, err
}
// NetListening returns true if client is actively listening for network connections.
func (rpc *EthRPC) NetListening() (bool, error) {
var listening bool
err := rpc.call("net_listening", &listening)
return listening, err
}
// NetPeerCount returns number of peers currently connected to the client.
func (rpc *EthRPC) NetPeerCount() (int, error) {
var response string
if err := rpc.call("net_peerCount", &response); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthProtocolVersion returns the current ethereum protocol version.
func (rpc *EthRPC) EthProtocolVersion() (string, error) {
var protocolVersion string
err := rpc.call("eth_protocolVersion", &protocolVersion)
return protocolVersion, err
}
// EthSyncing returns an object with data about the sync status or false.
func (rpc *EthRPC) EthSyncing() (*Syncing, error) {
result, err := rpc.RawCall("eth_syncing")
if err != nil {
return nil, err
}
syncing := new(Syncing)
if bytes.Equal(result, []byte("false")) {
return syncing, nil
}
err = json.Unmarshal(result, syncing)
return syncing, err
}
// EthCoinbase returns the client coinbase address
func (rpc *EthRPC) EthCoinbase() (string, error) {
var address string
err := rpc.call("eth_coinbase", &address)
return address, err
}
// EthMining returns true if client is actively mining new blocks.
func (rpc *EthRPC) EthMining() (bool, error) {
var mining bool
err := rpc.call("eth_mining", &mining)
return mining, err
}
// EthHashrate returns the number of hashes per second that the node is mining with.
func (rpc *EthRPC) EthHashrate() (int, error) {
var response string
if err := rpc.call("eth_hashrate", &response); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthGasPrice returns the current price per gas in wei.
func (rpc *EthRPC) EthGasPrice() (big.Int, error) {
var response string
if err := rpc.call("eth_gasPrice", &response); err != nil {
return big.Int{}, err
}
return ParseBigInt(response)
}
// EthAccounts returns a list of addresses owned by client.
func (rpc *EthRPC) EthAccounts() ([]string, error) {
accounts := []string{}
err := rpc.call("eth_accounts", &accounts)
return accounts, err
}
// EthBlockNumber returns the number of most recent block.
func (rpc *EthRPC) EthBlockNumber() (int, error) {
var response string
if err := rpc.call("eth_blockNumber", &response); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthGetBalance returns the balance of the account of given address in wei.
func (rpc *EthRPC) EthGetBalance(address, block string) (big.Int, error) {
var response string
if err := rpc.call("eth_getBalance", &response, address, block); err != nil {
return big.Int{}, err
}
return ParseBigInt(response)
}
// EthGetStorageAt returns the value from a storage position at a given address.
func (rpc *EthRPC) EthGetStorageAt(data string, position int, tag string) (string, error) {
var result string
err := rpc.call("eth_getStorageAt", &result, data, IntToHex(position), tag)
return result, err
}
// EthGetTransactionCount returns the number of transactions sent from an address.
func (rpc *EthRPC) EthGetTransactionCount(address, block string) (int, error) {
var response string
if err := rpc.call("eth_getTransactionCount", &response, address, block); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthGetBlockTransactionCountByHash returns the number of transactions in a block from a block matching the given block hash.
func (rpc *EthRPC) EthGetBlockTransactionCountByHash(hash string) (int, error) {
var response string
if err := rpc.call("eth_getBlockTransactionCountByHash", &response, hash); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthGetBlockTransactionCountByNumber returns the number of transactions in a block from a block matching the given block
func (rpc *EthRPC) EthGetBlockTransactionCountByNumber(number int) (int, error) {
var response string
if err := rpc.call("eth_getBlockTransactionCountByNumber", &response, IntToHex(number)); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthGetUncleCountByBlockHash returns the number of uncles in a block from a block matching the given block hash.
func (rpc *EthRPC) EthGetUncleCountByBlockHash(hash string) (int, error) {
var response string
if err := rpc.call("eth_getUncleCountByBlockHash", &response, hash); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthGetUncleCountByBlockNumber returns the number of uncles in a block from a block matching the given block number.
func (rpc *EthRPC) EthGetUncleCountByBlockNumber(number int) (int, error) {
var response string
if err := rpc.call("eth_getUncleCountByBlockNumber", &response, IntToHex(number)); err != nil {
return 0, err
}
return ParseInt(response)
}
// EthGetCode returns code at a given address.
func (rpc *EthRPC) EthGetCode(address, block string) (string, error) {
var code string
err := rpc.call("eth_getCode", &code, address, block)
return code, err
}
// EthSign signs data with a given address.
// Calculates an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)))
func (rpc *EthRPC) EthSign(address, data string) (string, error) {
var signature string
err := rpc.call("eth_sign", &signature, address, data)
return signature, err
}
// EthSendTransaction creates new message call transaction or a contract creation, if the data field contains code.
func (rpc *EthRPC) EthSendTransaction(transaction T) (string, error) {
var hash string
err := rpc.call("eth_sendTransaction", &hash, transaction)
return hash, err
}
// EthSendRawTransaction creates new message call transaction or a contract creation for signed transactions.
func (rpc *EthRPC) EthSendRawTransaction(data string) (string, error) {
var hash string
err := rpc.call("eth_sendRawTransaction", &hash, data)
return hash, err
}
// EthCall executes a new message call immediately without creating a transaction on the block chain.
func (rpc *EthRPC) EthCall(transaction T, tag string) (string, error) {
var data string
err := rpc.call("eth_call", &data, transaction, tag)
return data, err
}
// EthEstimateGas makes a call or transaction, which won't be added to the blockchain and returns the used gas, which can be used for estimating the used gas.
func (rpc *EthRPC) EthEstimateGas(transaction T) (int, error) {
var response string
err := rpc.call("eth_estimateGas", &response, transaction)
if err != nil {
return 0, err
}
return ParseInt(response)
}
func (rpc *EthRPC) getBlock(method string, withTransactions bool, params ...interface{}) (*Block, error) {
result, err := rpc.RawCall(method, params...)
if err != nil {
return nil, err
}
if bytes.Equal(result, []byte("null")) {
return nil, nil
}
var response proxyBlock
if withTransactions {
response = new(proxyBlockWithTransactions)
} else {
response = new(proxyBlockWithoutTransactions)
}
err = json.Unmarshal(result, response)
if err != nil {
return nil, err
}
block := response.toBlock()
return &block, nil
}
// EthGetBlockByHash returns information about a block by hash.
func (rpc *EthRPC) EthGetBlockByHash(hash string, withTransactions bool) (*Block, error) {
return rpc.getBlock("eth_getBlockByHash", withTransactions, hash, withTransactions)
}
// EthGetBlockByNumber returns information about a block by block number.
func (rpc *EthRPC) EthGetBlockByNumber(number int, withTransactions bool) (*Block, error) {
return rpc.getBlock("eth_getBlockByNumber", withTransactions, IntToHex(number), withTransactions)
}
func (rpc *EthRPC) getTransaction(method string, params ...interface{}) (*Transaction, error) {
transaction := new(Transaction)
err := rpc.call(method, transaction, params...)
return transaction, err
}
// EthGetTransactionByHash returns the information about a transaction requested by transaction hash.
func (rpc *EthRPC) EthGetTransactionByHash(hash string) (*Transaction, error) {
return rpc.getTransaction("eth_getTransactionByHash", hash)
}
// EthGetTransactionByBlockHashAndIndex returns information about a transaction by block hash and transaction index position.
func (rpc *EthRPC) EthGetTransactionByBlockHashAndIndex(blockHash string, transactionIndex int) (*Transaction, error) {
return rpc.getTransaction("eth_getTransactionByBlockHashAndIndex", blockHash, IntToHex(transactionIndex))
}
// EthGetTransactionByBlockNumberAndIndex returns information about a transaction by block number and transaction index position.
func (rpc *EthRPC) EthGetTransactionByBlockNumberAndIndex(blockNumber, transactionIndex int) (*Transaction, error) {
return rpc.getTransaction("eth_getTransactionByBlockNumberAndIndex", IntToHex(blockNumber), IntToHex(transactionIndex))
}
// EthGetTransactionReceipt returns the receipt of a transaction by transaction hash.
// Note That the receipt is not available for pending transactions.
func (rpc *EthRPC) EthGetTransactionReceipt(hash string) (*TransactionReceipt, error) {
transactionReceipt := new(TransactionReceipt)
err := rpc.call("eth_getTransactionReceipt", transactionReceipt, hash)
if err != nil {
return nil, err
}
return transactionReceipt, nil
}
// EthGetCompilers returns a list of available compilers in the client.
func (rpc *EthRPC) EthGetCompilers() ([]string, error) {
compilers := []string{}
err := rpc.call("eth_getCompilers", &compilers)
return compilers, err
}
// EthNewFilter creates a new filter object.
func (rpc *EthRPC) EthNewFilter(params FilterParams) (string, error) {
var filterID string
err := rpc.call("eth_newFilter", &filterID, params)
return filterID, err
}
// EthNewBlockFilter creates a filter in the node, to notify when a new block arrives.
// To check if the state has changed, call EthGetFilterChanges.
func (rpc *EthRPC) EthNewBlockFilter() (string, error) {
var filterID string
err := rpc.call("eth_newBlockFilter", &filterID)
return filterID, err
}
// EthNewPendingTransactionFilter creates a filter in the node, to notify when new pending transactions arrive.
// To check if the state has changed, call EthGetFilterChanges.
func (rpc *EthRPC) EthNewPendingTransactionFilter() (string, error) {
var filterID string
err := rpc.call("eth_newPendingTransactionFilter", &filterID)
return filterID, err
}
// EthUninstallFilter uninstalls a filter with given id.
func (rpc *EthRPC) EthUninstallFilter(filterID string) (bool, error) {
var res bool
err := rpc.call("eth_uninstallFilter", &res, filterID)
return res, err
}
// EthGetFilterChanges polling method for a filter, which returns an array of logs which occurred since last poll.
func (rpc *EthRPC) EthGetFilterChanges(filterID string) ([]Log, error) {
var logs = []Log{}
err := rpc.call("eth_getFilterChanges", &logs, filterID)
return logs, err
}
// EthGetFilterLogs returns an array of all logs matching filter with given id.
func (rpc *EthRPC) EthGetFilterLogs(filterID string) ([]Log, error) {
var logs = []Log{}
err := rpc.call("eth_getFilterLogs", &logs, filterID)
return logs, err
}
// EthGetLogs returns an array of all logs matching a given filter object.
func (rpc *EthRPC) EthGetLogs(params FilterParams) ([]Log, error) {
var logs = []Log{}
err := rpc.call("eth_getLogs", &logs, params)
return logs, err
}
// Eth1 returns 1 ethereum value (10^18 wei)
func (rpc *EthRPC) Eth1() *big.Int {
return Eth1()
}
// Eth1 returns 1 ethereum value (10^18 wei)
func Eth1() *big.Int {
return big.NewInt(1000000000000000000)
}