Call Ethereum RPC

>![eth](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/169726/dbc62e41-7483-9231-a472-a93d7b3c924f.jpeg)

## 运行 geth

```shell
geth --datadir /mnt/eth/data --http

# --http 默认在 http://localhost:8545 开启 rpc
```

## curl

```bash
curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"net_version","params":[],"id":1}'

curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"eth_chainId","params":[],"id":0}'

curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"eth_syncing","params":[],"id":0}'

curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"eth_blockNumber","params":[],"id":1}'
# {"jsonrpc":"2.0","id":1,"result":"0x509e24"}


curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"eth_getBlockByNumber","params":["0x1", true],"id":1}'
# true  返回transactions的详细信息
# false 只返回transactions的hash

curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"eth_getBalance","params":["0xe89943ec20d856f064a87349a00ef6ab00aed042", "latest"],"id":1}'
#{"jsonrpc":"2.0","id":1,"result":"0x740414b151bf7e0ba2"}

curl http://127.0.0.1:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"eth_getTransactionByHash","params":["0x4ee29e4d3c07a461d7378fa29c74884b5d1e297d9f45324eb7be51ec7780bb3e"],"id":1}'

curl http://127.0.0.1:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"eth_getTransactionByBlockNumberAndIndex","params":["0x18d522", "0x5"],"id":1}'
```

```shell
curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"txpool_content","params":[],"id":0}'
```

## debug 模块

开启 debug 模块
`geth --http --http.addr 0.0.0.0 --http.api debug`

```shell
curl http://localhost:8545 -H 'content-type:application/json;' -X POST \
--data '{"method":"debug_traceBlockByNumber","params":["0xcdc", {"tracer": "callTracer"}],"id":1,"jsonrpc":"2.0"}'
```

## personal 模块

开启 personal 模块
`geth --http --http.addr 0.0.0.0 --http.api personal`

### example

```py
# python

import json
import requests

url = "http://localhost:8545"
headers = {'content-type': 'application/json'}
payload = json.dumps({"method": 'personal_newAccount', "params": ["zqw"], "id": '1' })
# 产生新地址

response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
```

## python code

```py
import json
import requests

url = "http://localhost:8545"
headers = {'content-type': 'application/json'}
payload = json.dumps({"method": 'eth_blockNumber', "params": [], "id": '1' })

response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
```

## golang code

```go
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/big"
	"net/http"
	"strings"
)

type rpcData struct {
	Jsonrpc string `json:"jsonrpc"`
	ID      int    `json:"id"`
	Result  string `json:"result"`
}

func main() {

	url := "http://localhost:8545/"

	payload := strings.NewReader("{\"method\":\"eth_getBalance\",\"params\":[\"0x6cafe7473925998db07a497ac3fd10405637a46d\", \"latest\"],\"id\":0}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("content-type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(string(body))

	var obj rpcData
	json.Unmarshal([]byte(body), &obj)

	balance := obj.Result // 0x29d669390feebf072 超过 20 位，是 bigInt 类型

	n := new(big.Int)

	n, err := n.SetString(balance[2:], 16)

	if !err {
		fmt.Println("SetString: error")
		return
	}

	fmt.Printf("balance 十六进制: %s, 十进制: %d \n", balance, n)

}
```

---

参考：

https://qiita.com/shooter/items/61da974b3ffe8620ac95

https://geth.ethereum.org/docs/rpc/ns-debug

https://infura.io/

https://blog.linux-mac.com/2018/06/01/33.html

https://github.com/ethereum/wiki/wiki/JSON-RPC

https://tokenmarket.net/blog/protecting-ethereum-json-rpc-api-with-password/

https://www.quicknode.com/guides/defi/how-to-access-ethereum-mempool