Skip to content

Commit 771655e

Browse files
authored
Merge pull request bnb-chain#2808 from fjl/rpc-client-3
rpc: add new client, use it everywhere
2 parents 60cd5bf + 91b7690 commit 771655e

30 files changed

Lines changed: 2021 additions & 769 deletions

‎accounts/abi/bind/backends/remote.go‎

Lines changed: 18 additions & 142 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,7 @@
1717
package backends
1818

1919
import (
20-
"encoding/json"
21-
"fmt"
2220
"math/big"
23-
"sync"
24-
"sync/atomic"
2521

2622
"github.com/ethereum/go-ethereum/accounts/abi/bind"
2723
"github.com/ethereum/go-ethereum/common"
@@ -37,183 +33,78 @@ var _ bind.ContractBackend = (*rpcBackend)(nil)
3733
// rpcBackend implements bind.ContractBackend, and acts as the data provider to
3834
// Ethereum contracts bound to Go structs. It uses an RPC connection to delegate
3935
// all its functionality.
40-
//
41-
// Note: The current implementation is a blocking one. This should be replaced
42-
// by a proper async version when a real RPC client is created.
4336
type rpcBackend struct {
44-
client rpc.Client // RPC client connection to interact with an API server
45-
autoid uint32 // ID number to use for the next API request
46-
lock sync.Mutex // Singleton access until we get to request multiplexing
37+
client *rpc.Client // RPC client connection to interact with an API server
4738
}
4839

4940
// NewRPCBackend creates a new binding backend to an RPC provider that can be
5041
// used to interact with remote contracts.
51-
func NewRPCBackend(client rpc.Client) bind.ContractBackend {
52-
return &rpcBackend{
53-
client: client,
54-
}
55-
}
56-
57-
// request is a JSON RPC request package assembled internally from the client
58-
// method calls.
59-
type request struct {
60-
JSONRPC string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
61-
ID int `json:"id"` // Auto incrementing ID number for this request
62-
Method string `json:"method"` // Remote procedure name to invoke on the server
63-
Params []interface{} `json:"params"` // List of parameters to pass through (keep types simple)
64-
}
65-
66-
// response is a JSON RPC response package sent back from the API server.
67-
type response struct {
68-
JSONRPC string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
69-
ID int `json:"id"` // Auto incrementing ID number for this request
70-
Error *failure `json:"error"` // Any error returned by the remote side
71-
Result json.RawMessage `json:"result"` // Whatever the remote side sends us in reply
72-
}
73-
74-
// failure is a JSON RPC response error field sent back from the API server.
75-
type failure struct {
76-
Code int `json:"code"` // JSON RPC error code associated with the failure
77-
Message string `json:"message"` // Specific error message of the failure
78-
}
79-
80-
// request forwards an API request to the RPC server, and parses the response.
81-
//
82-
// This is currently painfully non-concurrent, but it will have to do until we
83-
// find the time for niceties like this :P
84-
func (b *rpcBackend) request(ctx context.Context, method string, params []interface{}) (json.RawMessage, error) {
85-
b.lock.Lock()
86-
defer b.lock.Unlock()
87-
88-
if ctx == nil {
89-
ctx = context.Background()
90-
}
91-
92-
// Ugly hack to serialize an empty list properly
93-
if params == nil {
94-
params = []interface{}{}
95-
}
96-
// Assemble the request object
97-
reqID := int(atomic.AddUint32(&b.autoid, 1))
98-
req := &request{
99-
JSONRPC: "2.0",
100-
ID: reqID,
101-
Method: method,
102-
Params: params,
103-
}
104-
if err := b.client.Send(req); err != nil {
105-
return nil, err
106-
}
107-
res := new(response)
108-
errc := make(chan error, 1)
109-
go func() {
110-
errc <- b.client.Recv(res)
111-
}()
112-
select {
113-
case err := <-errc:
114-
if err != nil {
115-
return nil, err
116-
}
117-
case <-ctx.Done():
118-
return nil, ctx.Err()
119-
}
120-
if res.Error != nil {
121-
if res.Error.Message == bind.ErrNoCode.Error() {
122-
return nil, bind.ErrNoCode
123-
}
124-
return nil, fmt.Errorf("remote error: %s", res.Error.Message)
125-
}
126-
return res.Result, nil
42+
func NewRPCBackend(client *rpc.Client) bind.ContractBackend {
43+
return &rpcBackend{client: client}
12744
}
12845

12946
// HasCode implements ContractVerifier.HasCode by retrieving any code associated
13047
// with the contract from the remote node, and checking its size.
13148
func (b *rpcBackend) HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error) {
132-
// Execute the RPC code retrieval
13349
block := "latest"
13450
if pending {
13551
block = "pending"
13652
}
137-
res, err := b.request(ctx, "eth_getCode", []interface{}{contract.Hex(), block})
138-
if err != nil {
139-
return false, err
140-
}
14153
var hex string
142-
if err := json.Unmarshal(res, &hex); err != nil {
54+
err := b.client.CallContext(ctx, &hex, "eth_getCode", contract, block)
55+
if err != nil {
14356
return false, err
14457
}
145-
// Convert the response back to a Go byte slice and return
14658
return len(common.FromHex(hex)) > 0, nil
14759
}
14860

14961
// ContractCall implements ContractCaller.ContractCall, delegating the execution of
15062
// a contract call to the remote node, returning the reply to for local processing.
15163
func (b *rpcBackend) ContractCall(ctx context.Context, contract common.Address, data []byte, pending bool) ([]byte, error) {
152-
// Pack up the request into an RPC argument
15364
args := struct {
15465
To common.Address `json:"to"`
15566
Data string `json:"data"`
15667
}{
15768
To: contract,
15869
Data: common.ToHex(data),
15970
}
160-
// Execute the RPC call and retrieve the response
16171
block := "latest"
16272
if pending {
16373
block = "pending"
16474
}
165-
res, err := b.request(ctx, "eth_call", []interface{}{args, block})
166-
if err != nil {
167-
return nil, err
168-
}
16975
var hex string
170-
if err := json.Unmarshal(res, &hex); err != nil {
76+
err := b.client.CallContext(ctx, &hex, "eth_call", args, block)
77+
if err != nil {
17178
return nil, err
17279
}
173-
// Convert the response back to a Go byte slice and return
17480
return common.FromHex(hex), nil
81+
17582
}
17683

17784
// PendingAccountNonce implements ContractTransactor.PendingAccountNonce, delegating
17885
// the current account nonce retrieval to the remote node.
17986
func (b *rpcBackend) PendingAccountNonce(ctx context.Context, account common.Address) (uint64, error) {
180-
res, err := b.request(ctx, "eth_getTransactionCount", []interface{}{account.Hex(), "pending"})
87+
var hex rpc.HexNumber
88+
err := b.client.CallContext(ctx, &hex, "eth_getTransactionCount", account.Hex(), "pending")
18189
if err != nil {
18290
return 0, err
18391
}
184-
var hex string
185-
if err := json.Unmarshal(res, &hex); err != nil {
186-
return 0, err
187-
}
188-
nonce, ok := new(big.Int).SetString(hex, 0)
189-
if !ok {
190-
return 0, fmt.Errorf("invalid nonce hex: %s", hex)
191-
}
192-
return nonce.Uint64(), nil
92+
return hex.Uint64(), nil
19393
}
19494

19595
// SuggestGasPrice implements ContractTransactor.SuggestGasPrice, delegating the
19696
// gas price oracle request to the remote node.
19797
func (b *rpcBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
198-
res, err := b.request(ctx, "eth_gasPrice", nil)
199-
if err != nil {
200-
return nil, err
201-
}
202-
var hex string
203-
if err := json.Unmarshal(res, &hex); err != nil {
98+
var hex rpc.HexNumber
99+
if err := b.client.CallContext(ctx, &hex, "eth_gasPrice"); err != nil {
204100
return nil, err
205101
}
206-
price, ok := new(big.Int).SetString(hex, 0)
207-
if !ok {
208-
return nil, fmt.Errorf("invalid price hex: %s", hex)
209-
}
210-
return price, nil
102+
return (*big.Int)(&hex), nil
211103
}
212104

213105
// EstimateGasLimit implements ContractTransactor.EstimateGasLimit, delegating
214106
// the gas estimation to the remote node.
215107
func (b *rpcBackend) EstimateGasLimit(ctx context.Context, sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
216-
// Pack up the request into an RPC argument
217108
args := struct {
218109
From common.Address `json:"from"`
219110
To *common.Address `json:"to"`
@@ -226,19 +117,12 @@ func (b *rpcBackend) EstimateGasLimit(ctx context.Context, sender common.Address
226117
Value: rpc.NewHexNumber(value),
227118
}
228119
// Execute the RPC call and retrieve the response
229-
res, err := b.request(ctx, "eth_estimateGas", []interface{}{args})
120+
var hex rpc.HexNumber
121+
err := b.client.CallContext(ctx, &hex, "eth_estimateGas", args)
230122
if err != nil {
231123
return nil, err
232124
}
233-
var hex string
234-
if err := json.Unmarshal(res, &hex); err != nil {
235-
return nil, err
236-
}
237-
estimate, ok := new(big.Int).SetString(hex, 0)
238-
if !ok {
239-
return nil, fmt.Errorf("invalid estimate hex: %s", hex)
240-
}
241-
return estimate, nil
125+
return (*big.Int)(&hex), nil
242126
}
243127

244128
// SendTransaction implements ContractTransactor.SendTransaction, delegating the
@@ -248,13 +132,5 @@ func (b *rpcBackend) SendTransaction(ctx context.Context, tx *types.Transaction)
248132
if err != nil {
249133
return err
250134
}
251-
res, err := b.request(ctx, "eth_sendRawTransaction", []interface{}{common.ToHex(data)})
252-
if err != nil {
253-
return err
254-
}
255-
var hex string
256-
if err := json.Unmarshal(res, &hex); err != nil {
257-
return err
258-
}
259-
return nil
135+
return b.client.CallContext(ctx, nil, "eth_sendRawTransaction", common.ToHex(data))
260136
}

‎cmd/geth/consolecmd.go‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@ package main
1919
import (
2020
"os"
2121
"os/signal"
22+
"strings"
2223

2324
"github.com/ethereum/go-ethereum/cmd/utils"
2425
"github.com/ethereum/go-ethereum/console"
26+
"github.com/ethereum/go-ethereum/node"
27+
"github.com/ethereum/go-ethereum/rpc"
2528
"gopkg.in/urfave/cli.v1"
2629
)
2730

@@ -99,7 +102,7 @@ func localConsole(ctx *cli.Context) error {
99102
// console to it.
100103
func remoteConsole(ctx *cli.Context) error {
101104
// Attach to a remotely running geth instance and start the JavaScript console
102-
client, err := utils.NewRemoteRPCClient(ctx)
105+
client, err := dialRPC(ctx.Args().First())
103106
if err != nil {
104107
utils.Fatalf("Unable to attach to remote geth: %v", err)
105108
}
@@ -127,6 +130,20 @@ func remoteConsole(ctx *cli.Context) error {
127130
return nil
128131
}
129132

133+
// dialRPC returns a RPC client which connects to the given endpoint.
134+
// The check for empty endpoint implements the defaulting logic
135+
// for "geth attach" and "geth monitor" with no argument.
136+
func dialRPC(endpoint string) (*rpc.Client, error) {
137+
if endpoint == "" {
138+
endpoint = node.DefaultIPCEndpoint()
139+
} else if strings.HasPrefix(endpoint, "rpc:") || strings.HasPrefix(endpoint, "ipc:") {
140+
// Backwards compatibility with geth < 1.5 which required
141+
// these prefixes.
142+
endpoint = endpoint[4:]
143+
}
144+
return rpc.Dial(endpoint)
145+
}
146+
130147
// ephemeralConsole starts a new geth node, attaches an ephemeral JavaScript
131148
// console to it, and each of the files specified as arguments and tears the
132149
// everything down.

‎cmd/geth/monitorcmd.go‎

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,10 @@ import (
2121
"math"
2222
"reflect"
2323
"runtime"
24+
"sort"
2425
"strings"
2526
"time"
2627

27-
"sort"
28-
2928
"github.com/ethereum/go-ethereum/cmd/utils"
3029
"github.com/ethereum/go-ethereum/node"
3130
"github.com/ethereum/go-ethereum/rpc"
@@ -36,7 +35,7 @@ import (
3635
var (
3736
monitorCommandAttachFlag = cli.StringFlag{
3837
Name: "attach",
39-
Value: "ipc:" + node.DefaultIPCEndpoint(),
38+
Value: node.DefaultIPCEndpoint(),
4039
Usage: "API endpoint to attach to",
4140
}
4241
monitorCommandRowsFlag = cli.IntFlag{
@@ -69,12 +68,12 @@ to display multiple metrics simultaneously.
6968
// monitor starts a terminal UI based monitoring tool for the requested metrics.
7069
func monitor(ctx *cli.Context) error {
7170
var (
72-
client rpc.Client
71+
client *rpc.Client
7372
err error
7473
)
7574
// Attach to an Ethereum node over IPC or RPC
7675
endpoint := ctx.String(monitorCommandAttachFlag.Name)
77-
if client, err = utils.NewRemoteRPCClientFromString(endpoint); err != nil {
76+
if client, err = dialRPC(endpoint); err != nil {
7877
utils.Fatalf("Unable to attach to geth node: %v", err)
7978
}
8079
defer client.Close()
@@ -159,30 +158,10 @@ func monitor(ctx *cli.Context) error {
159158

160159
// retrieveMetrics contacts the attached geth node and retrieves the entire set
161160
// of collected system metrics.
162-
func retrieveMetrics(client rpc.Client) (map[string]interface{}, error) {
163-
req := map[string]interface{}{
164-
"id": new(int64),
165-
"method": "debug_metrics",
166-
"jsonrpc": "2.0",
167-
"params": []interface{}{true},
168-
}
169-
170-
if err := client.Send(req); err != nil {
171-
return nil, err
172-
}
173-
174-
var res rpc.JSONSuccessResponse
175-
if err := client.Recv(&res); err != nil {
176-
return nil, err
177-
}
178-
179-
if res.Result != nil {
180-
if mets, ok := res.Result.(map[string]interface{}); ok {
181-
return mets, nil
182-
}
183-
}
184-
185-
return nil, fmt.Errorf("unable to retrieve metrics")
161+
func retrieveMetrics(client *rpc.Client) (map[string]interface{}, error) {
162+
var metrics map[string]interface{}
163+
err := client.Call(&metrics, "debug_metrics", true)
164+
return metrics, err
186165
}
187166

188167
// resolveMetrics takes a list of input metric patterns, and resolves each to one
@@ -270,7 +249,7 @@ func fetchMetric(metrics map[string]interface{}, metric string) float64 {
270249

271250
// refreshCharts retrieves a next batch of metrics, and inserts all the new
272251
// values into the active datasets and charts
273-
func refreshCharts(client rpc.Client, metrics []string, data [][]float64, units []int, charts []*termui.LineChart, ctx *cli.Context, footer *termui.Par) (realign bool) {
252+
func refreshCharts(client *rpc.Client, metrics []string, data [][]float64, units []int, charts []*termui.LineChart, ctx *cli.Context, footer *termui.Par) (realign bool) {
274253
values, err := retrieveMetrics(client)
275254
for i, metric := range metrics {
276255
if len(data) < 512 {

0 commit comments

Comments
 (0)