天天看点

区块链,以太坊 Ethereum JSON-Api 的调用说明 官网翻译版

Ethereum的API接口类型

Ethereum官方提供了Go、python、C++和Parity四种语言的版本。四种语言都提供了JSON-RPC API,供使用者调用,可以通过geth RPC终端开启。

在开启

geth

的时候可以增加 

--${interface}api

新选项来选择开启哪一个api。

${interface}

的类型可以为 

rpc

开启HTTP, 

ws

开启Web Scocket, 

ipc

开启Unix socket(Unix)或者named pipe(Windows)。

例如,

geth --ipcapi admin, eth, miner --rpcapi eth,web3 --rpc

表示:开启了

admin

,

eth

miner

功能的

ipc

API,开启

eth

web3

功能的HTTP API。

其中HTTP RPC功能需要加上

--rpc

来激活。

Ethereum JSON RPC的使用

开启JSON RPC

默认的JSON-RPC端口

Cliet 1 Url 2
C++ http://localhost:8545
Go
Py http://localhost:4000
Parity

以go-ethereum为例,开启JSON-RPC服务

开启默认接口:

geth --rpc

自定义监听端口和地址

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

如果需要从浏览器访问RPC,则需要用适当的域名配置CORS。[这个好像是说跨域的。。。。]

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

同时,在geth consle里面也可以通过输入命令来开启RPC服务 

>startRPC(addr,port)

调用Ethereum JSON RPC

接口类型

除了DApp Api的命名空间(

eth

shh

web3

)之外,

geth

还提供了如下API命名空间

Namespace Usage

admin

Geth node management

debug

Geth node debugging

miner

Miner and DAG management

personal

Account management

txpool

Transaction pool inspection

调用格式

cur addr:port -X POST --data '{"jsonrpc":"2.0","id":id, "method":"${method}","params":"${params}"}'

ethereum-php

下载lib

git clone https://github.com/btelle/ethereum-php.git

deamon

// include the class filerequire 'ethereum.php';// create a new object$ethereum = new Ethereum('127.0.0.1', 8545);// do your thingecho $ethereum->net_version();12345678      

常用操作

新建account

Ethereum的Account长度为20字节,40个16进制数字。

  • curl
cur -X POST --data {"id":${id}, "jsonrpc":"2.0","method":"personal_newAccount", "params":[${passphrase}]}1      
  • php

通过自己添加函数

echo $ethereum->personal_newAccount('passphrase');1      
查询账号
curl addr:port -X POST --data '{"id":${id},"jsonrpc":"2.0","method":"eth_accounts", "params":[]}'1      

或者

curl addr:port -X POST --data '{"id":${id},"jsonrpc":"2.0","method":"personal_listAccounts", "params":[]}'1      
echo json_encode($ethereum->eth_accounts());1      
echo json_encode($thereum->personal_listAccounts());1      
查询余额

params:

@DATA

, 20 bytes, address to check for balance

@Qutantity|TAG

, int of block number, or “

latest

earliest

pending

curl -X POST --data    '{"id":${id},"jsonrpc":"2.0","method":"eth_getBalance", "params":["0xb75b32047b7a9018964867a8bc6ef294659859c3","latest"]}' addr:port 1      
echo $ethereum->eth_getBalance('0xb75b32047b7a9018964867a8bc6ef294659859c3','latest',True);1      

发送ETH 

- [x] tx: Transaction 

- [x] from: 发出的Account 

- [x] to: 接收的Account 

- [x] amount: 数量 

- [x] passphrase: tx.from的passphrase

curl -X POST --data '{"id":${id}, "jsonrpc":"2.0", "method": "personal_sendTransaction", "params": [tx, string]}'1      
可用资源 第二个是官网

https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sendtransaction

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