Ethereum RPC mechanism and API instance

Source: Internet
Author: User

The previous article introduced the basics of ethereum, and we learned that Web3.js is called via Ethereum RPC technology, and this article aims to explore how to develop, compile, run, and use the Ethereum RPC interface.

Keywords: ethereum, rpc,json-rpc,client,server,api,web3.js,api instances, Postman

Ethereum JSON RPC apigeth command API related

As described previously, these APIs can be called in the Geth console, and in real-world applications, the pure and complete RPC call method,

geth --rpc --rpcapi "db,eth,net,web3,personal"

This command can start the HTTP RPC service, of course, they are all under the Geth command, still can be stitched into a multi-functional command string, you can learn about the use of the previous introduction of the Geth. Here are the API-related options parameters:

API AND CONSOLE OPTIONS:  --rpc                  启动HTTP-RPC服务(基于HTTP的)  --rpcaddr value        HTTP-RPC服务器监听地址(default: "localhost")  --rpcport value        HTTP-RPC服务器监听端口(default: 8545)  --rpcapi value         指定需要调用的HTTP-RPC API接口,默认只有eth,net,web3  --ws                   启动WS-RPC服务(基于WebService的)  --wsaddr value         WS-RPC服务器监听地址(default: "localhost")  --wsport value         WS-RPC服务器监听端口(default: 8546)  --wsapi value          指定需要调用的WS-RPC API接口,默认只有eth,net,web3  --wsorigins value      指定接收websocket请求的来源  --ipcdisable           禁掉IPC-RPC服务  --ipcpath              指定IPC socket/pipe文件目录(明确指定路径)  --rpccorsdomain value  指定一个可以接收请求来源的以逗号间隔的域名列表(浏览器访问的话,要强制指定该选项)  --jspath loadScript    JavaScript根目录用来加载脚本 (default: ".")  --exec value           执行JavaScript声明  --preload value        指定一个可以预加载到控制台的JavaScript文件,其中包含一个以逗号分隔的列表

We can specify the network at the same time when executing the RPC command above, specifying the node, specifying the port, specifying the acceptable domain name, or even opening a console at the same time, which does not create a conflict.

geth --rpc --rpcaddr <ip> --rpcport <portnumber>

We can specify the listening address and port, if not rpcaddr and Rpcport, is the default http://localhost:8545.

geth --rpc --rpccorsdomain "http://localhost:3000"

If you want to use the browser to access, it is mandatory to specify the Rpccorsdomain option, otherwise the request will fail due to the same origin limit as the JavaScript call.

admin.startRPC(addr, port)

If you have entered Geth console, you can also add addresses and ports via this command.

Postman,http Request API

Postman is a client tool that can be used to test various HTTP requests, and it has many other uses, but it is used only to test the HTTP-RPC service above.

Looking at the diagram, we specify the request address port, specify the HTTP POST request method, set the request as the original JSON text, the request content is:

{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}

is used to request the current WEB3 client version of the server, and then click "Send" to get the requested result:

{    "jsonrpc": "2.0",    "id": 67,    "result": "Geth/v0.0.1-stable-930fa051/linux-amd64/go1.9.2"}
Ethereum go source Calls RPC

Let's take the most commonly used api:eth_getbalance as an example, its parameter requirements are:

Parameters- DATA, 20 Bytes - address to check for balance.- QUANTITY|TAG - integer block number, or the string "latest", "earliest" or "pending", see the default block parameter

The parameters required by the API:

    • The first parameter is the address where you want to check the balance
    • The second argument is an integer block number, or the string "latest", "earliest" and "pending" refer to a particular chunk.

Find the use location Ethclient/ethclient.go in the Go-ethereum project:

func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {    var result hexutil.Big    err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, toBlockNumArg(blockNumber))    return (*big.Int)(&result), err}
func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) {    var result hexutil.Big    err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, "pending")    return (*big.Int)(&result), err}

Combined with the above RPC API and the following go source call, you can see the way in the Go language: To use the client pointer type variable to invoke the context call method, passing in the first parameter is the context instance, the second parameter is a hexutil. The result of the big type receives a pointer to the variable, the third parameter is the API interface name of the calling RPC, and the fourth and fifth parameters for the API, as described above.

    • The trace to Ec.c.callcontext,callcontext method is a Ec.c object.
// Client defines typed wrappers for the Ethereum RPC API.type Client struct {    c *rpc.Client}

You can see that the original RPC/CLIENT.GO client structure is wrapped in a ethclient/ethclient.go file, so that you can differentiate between the methods that belong to Ethclient and the underlying rpc/client. The following is a definition of the structure of the original rpc.client:

Client represents a connection to an RPC server.type client struct {idcounter UInt32 connectfunc func (CTX CONT Ext. Context) (NET. Conn, error) ishttp bool//Writeconn is a safe to access outside dispatch, with the//write lock held.    The write lock is taken by sending on//Requestop and released by sending on Senddone. Writeconn Net. Conn/Dispatch Close Chan struct{} didquit chan struct{}//closed when client Q Uits reconnected Chan net. Conn//Where Write/reconnect sends the new connection Readerr Chan error//E                Rrors from Read Readresp chan []*jsonrpcmessage//valid messages from Read Requestop Chan *requestop For registering response IDs Senddone chan error//signals write completion, R Eleases Write lock respwait map[string]*requestop//Active requests Subs MAP[STRING]*CLIentsubscription//Active Subscriptions} 

After the

Ethclient has been wrapped, you can call its CallContext method by calling Rpc.client's pointer variable c using the local client variable:

Func (c *client) CallContext (CTX context. Context, Result interface{}, method string, args ... interface{}) error {msg, err: = C.newmessage (method, args ...)//See    To CallContext is not the end, TODO: Go into the Newmessage method and look inside. Result processing if err! = Nil {return err}//Requestop another struct, encapsulating the response parameters, including the original request message, response information jsonrpcmessage,jsonrpcmessage is also a structure that encapsulates the response message standard content structure, including version, ID, method, parameter, error, return value, where rawmessage in Go source location Json/stream.go is also a custom type, belonging to the go itself encapsulated, type is byte array []byte    , but also have their own methods of various functions. OP: = &requestop{ids: []json.    Rawmessage{msg.id}, Resp:make (Chan *jsonrpcmessage, 1)}//sends a response message via RPC different channels: These channels have been introduced in the above command section, there are http,webservice and so on.        If c.ishttp {err = C.sendhttp (ctx, OP, msg)} else {err = C.send (ctx, OP, msg)} if Err! = Nil { return err}//TODO: The study of the Wait method//The processing of the return result of the wait method switch resp, err: = Op.wait (CTX); {Case Err! = Nil:return Err Case resp. Error! = Nil:return resp. Error case Len (resp.    Result) = = 0:return Errnoresult default:    Return JSON. Unmarshal (resp. result, &result)//successfully compiled the resulting data}}

Look at the wait method first, which is still in Rpc/client.go:

func (op *requestOp) wait(ctx context.Context) (*jsonrpcMessage, error) {    select {    case <-ctx.Done():        return nil, ctx.Err()    case resp := <-op.resp:        return resp, op.err    }}

For the use of Select, please refer to here. Continue to the subject and enter CTX. Done (), done belongs to go source context/context.go:

// See https://blog.golang.org/pipelines for more examples of how to use// a Done channel for cancelation.Done() <-chan struct{}

To find out what happened, please go to another post I wrote go concurrency mode: Pipeline and Cancel, where this section is carefully analyzed.

From the above source analysis I feel that the go language is a network structure, from a structure to jump into another structure, between them who do not belong to who, who call who can use, do not explicitly inherit extends and explicit implementation Implements,go is the continuous encapsulation structure, Then increase the structure of the method, and sometimes you even forget the structure of your own program and go source package structure of the boundary between the body. This is similar to the object-oriented parsing class, which defines a class, defines its member properties, and writes its member methods.

The relationship between WEB3 and RPC

Here is a more verbose, reiterate the relationship between WEB3 and RPC:

To make your app for Ethereum, you can use the Web3 object provided by the Web3.js library. Under the hood it communicates to a local node through RPC calls. Web3.js works with any Ethereum node, which exposes an RPC layer.

To make your API work in Ethereum, you can use the Web3 object provided by the Web3.js library. The underlying communication is called on the local node via RPC. Web3.js can communicate with any of the Ethereum nodes, which is an exposed RPC layer.

Develop your own API

Set a small requirement: the value of the balance is multiplied by the specified multiplier, which is specified by the parameters of the other interface.

Join in the ETHAPI

var rateFlag uint64 = 1// Start forking command.// Rate is the fork coin‘s exchange rate.func (s *PublicBlockChainAPI) Forking(ctx context.Context, rate uint64) (uint64) {    // attempt: store the rate info in context.    // context.WithValue(ctx, "rate", rate)    rateFlag = rate    rate = rate + 1    return rate}

And then join in the ethclient.

// Forking tool‘s client for the Ethereum RPC APIfunc (ec *Client) ForkingAt(ctx context.Context, account common.Address, rate uint64)(uint64, error){    var result hexutil.Uint64    err := ec.c.CallContext(ctx, &result, "eth_forking", account, rate)    return uint64(result), err}

Save, make Geth compile, and then start in the node directory

geth --testnet --rpc console --datadir node0

Then go to the postman test and you can see

The multiplier has been changed to 3 (output 4 is for testing and has actually saved a multiplier of 3 in the local variable Rateflag)
Then we send the request balance test,

You can see that the return value is a string of 16 binary numbers, by the result of the conversion: 417093750000000000000, our original balance is: 139031250000000000000, exactly three times times.

RPC Client

We have increased the API on the RPC server above, and the client invocation is using postman to send a POST request. There are actually two types of RPC clients in Ethereum: one that we just experimented with, a call to Json-rpc in a Web page, and a geth console form, and in this form, I haven't really figured out the process of deploying it, but I just saw it in the source code root directory Build/_ Workspace will be in every make Geth be copied into all the source code as a post-compilation environment, and I modified the source file, _workspace file, are not effective, there may be a layer of running environment, I did not modify to. But this does not matter, because in practice, we seldom go to the contents of the console, directly modify the Web3.js introduced to the Web page. Here's how to modify the Web3.js file with your own API:

Above the structure of the web3.js, is a node. JS module structure, so we first decided to put this API under the ETH object, check the ETH ID 38, find the object body, in the methods to add the corresponding API call operation,

var forking = new Method({    name: ‘forking‘,    call: ‘eth_forking‘,    params: 1,    inputFormatter: [null],    outputFormatter: formatters.outputBigNumberFormatter});

Then add our newly constructed method to the object body return value section,

return [    forking,    ...

After the change, we refer the file to the page and we can call it through Web3.eth.forking (3).

Summarize

This article describes the concept of RPC, the popular framework for RPC, and the RPC framework used by Ethereum for JSON-RPC. It then describes how to start the JSON-RPC server and then use postman to request the JSON-RPC service-side API. Through this process, we carefully analyzed and followed the implementation of the source code, cobwebs, from the outermost JSON-RPC call specification to the source of foreign-layer encapsulation of the reference, to the internal implementation, during a variety of custom structure tracking research, until the Go Source library structure, The process of receiving client requests to sending responses from a server is studied. Finally, we looked at the structure of the Web3.js file and made a small experiment, adding a custom API from the server to the client imitators. I hope this article will be of some help to you.

For more articles, go to the wake-up blog Park.

Ethereum RPC mechanism and API instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.