php與ethereum rpc server通信
一、Json RPC
Json RPC就是基于json的遠(yuǎn)程過(guò)程調(diào)用,這么解釋比較抽象。簡(jiǎn)單來(lái)說(shuō),就是post一個(gè)json格式的數(shù)據(jù)調(diào)用rpc server中的方法. 而這個(gè)json格式是固定的, 總的來(lái)說(shuō)有這么幾項(xiàng):
{
"method": "",
"params": [],
"id": idNumber
}
- method: 方法名
- params: 參數(shù)列表
- id: 對(duì)過(guò)程調(diào)用的唯一標(biāo)識(shí)號(hào)
二、構(gòu)建一個(gè)Json RPC客戶端
?php
class jsonRPCClient {
/**
* Debug state
*
* @var boolean
*/
private $debug;
/**
* The server URL
*
* @var string
*/
private $url;
/**
* The request id
*
* @var integer
*/
private $id;
/**
* If true, notifications are performed instead of requests
*
* @var boolean
*/
private $notification = false;
/**
* Takes the connection parameters
*
* @param string $url
* @param boolean $debug
*/
public function __construct($url,$debug = false) {
// server URL
$this->url = $url;
// proxy
empty($proxy) ? $this->proxy = '' : $this->proxy = $proxy;
// debug state
empty($debug) ? $this->debug = false : $this->debug = true;
// message id
$this->id = 1;
}
/**
* Sets the notification state of the object. In this state, notifications are performed, instead of requests.
*
* @param boolean $notification
*/
public function setRPCNotification($notification) {
empty($notification) ?
$this->notification = false
:
$this->notification = true;
}
/**
* Performs a jsonRCP request and gets the results as an array
*
* @param string $method
* @param array $params
* @return array
*/
public function __call($method,$params) {
// check
if (!is_scalar($method)) {
throw new Exception('Method name has no scalar value');
}
// check
if (is_array($params)) {
// no keys
$params = $params[0];
} else {
throw new Exception('Params must be given as array');
}
// sets notification or request task
if ($this->notification) {
$currentId = NULL;
} else {
$currentId = $this->id;
}
// prepares the request
$request = array(
'method' => $method,
'params' => $params,
'id' => $currentId
);
$request = json_encode($request);
$this->debug $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n";
// performs the HTTP POST
$opts = array ('http' => array (
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $request
));
$context = stream_context_create($opts);
if ($fp = fopen($this->url, 'r', false, $context)) {
$response = '';
while($row = fgets($fp)) {
$response.= trim($row)."\n";
}
$this->debug $this->debug.='***** Server response *****'."\n".$response.'***** End of server response *****'."\n";
$response = json_decode($response,true);
} else {
throw new Exception('Unable to connect to '.$this->url);
}
// debug output
if ($this->debug) {
echo nl2br($debug);
}
// final checks and return
if (!$this->notification) {
// check
if ($response['id'] != $currentId) {
throw new Exception('Incorrect response id (request id: '.$currentId.', response id: '.$response['id'].')');
}
if (!is_null($response['error'])) {
throw new Exception('Request error: '. var_export($response['error'], true));
}
return $response['result'];
} else {
return true;
}
}
}
?>
比較簡(jiǎn)單的代碼,如果比較懶,拿過(guò)去用就行了。也可以上packagist.org自己找一個(gè)rpc client.
三、調(diào)用RPC的兩類(lèi)方法
有兩類(lèi)方法需要調(diào)用. 一類(lèi)是RPC server自帶方法,另一類(lèi)就是合約方法.
RPC server方法調(diào)用json格式
{
"method": "eth_accounts",
"params": [],
"id": 1
}
RPC Server自帶方法的列表
調(diào)用自帶方法比較簡(jiǎn)單,參考上述鏈接,大部分都有示例.
合約方法調(diào)用json格式
調(diào)用合約方法必須使用自帶方法中的eth_call. 而合約方法名稱和合約方法參數(shù)列表則使用params進(jìn)行體現(xiàn), 比如: 我們要調(diào)用合約中的balanceOf方法, 則json數(shù)據(jù)應(yīng)該如何構(gòu)造呢?
首先看看getBalanace的函數(shù)實(shí)現(xiàn):
function balanceOf(address _owner) public view returns (uint256 balance)
提煉出函數(shù)原型:
在geth控制臺(tái)下運(yùn)行命令:
web3.sha3("balanceOf(address)").substring(0, 10)
得到函數(shù)hash "0x70a08231"
假設(shè)待查詢的地址 address _owner = "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", 則去掉前面的"0x", 并在左邊補(bǔ)24個(gè)零(一般地址長(zhǎng)度為42位, 去掉'0x'后為40位),構(gòu)成64位十六進(jìn)制參數(shù).
最終得到的參數(shù)為 "0x70a0823100000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750"
假設(shè)我們的合約地址為 "0xaeab4084194B2a425096fb583Fbcd67385210ac3".
則得到最終的json數(shù)據(jù)為:
{
"method": "eth_call",
"params": [{"from": "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", "to": "0xaeab4084194B2a425096fb583Fbcd67385210ac3", "data": "0x70a0823100000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750"}, "latest"],
"id": 1
}
把以上json數(shù)據(jù)以post方式發(fā)送給服務(wù)器,就可以調(diào)用合約方法"balanceOf", 查詢給定的地址中的代幣余額.
調(diào)用合約中的其他方法也要新遵循上面的方式, 我們?cè)俜治鲆幌聇ransfer方法, 加深印象:
首先, 看看代碼中的函數(shù)實(shí)現(xiàn):
function transfer(address _to, uint256 _value) public returns (bool)
其次, 提煉出函數(shù)原型:
transfer(address,uint256) //注意逗號(hào)后面不能有空格
再次, 在控制臺(tái)運(yùn)行sha3函數(shù):
web3.sha3("transfer(address,uint256)").substring(0, 10)
得到函數(shù)hash "0xa9059cbb"
第一個(gè)參數(shù)假設(shè) address _to = "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", 則去"0x", 補(bǔ)零到64位.
第二個(gè)參數(shù)假設(shè) uint256 _value = 43776, 則化為十六進(jìn)制"0xab00"后, 去"0x", 補(bǔ)零到64位.
連接起來(lái)
"0xa9059cbb00000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750000000000000000000000000000000000000000000000000000000000000ab00"
構(gòu)建json數(shù)據(jù):
{
"method": "eth_call",
"params": [{"from": "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", "to": "0xaeab4084194B2a425096fb583Fbcd67385210ac3", "data": "0xa9059cbb00000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750000000000000000000000000000000000000000000000000000000000000ab00"}, "latest"],
"id": 1
}
- from 轉(zhuǎn)出者地址
- to 合約地址
- data 上述操作得到的十六進(jìn)制數(shù)
把以上的步驟轉(zhuǎn)化為代碼.
構(gòu)建一個(gè)以太坊RPC client
?php
require './jsonRPCClient.php';
//php自帶的dechex無(wú)法把大整型轉(zhuǎn)換為十六進(jìn)制
function bc_dechex($decimal)
{
$result = [];
while ($decimal != 0) {
$mod = $decimal % 16;
$decimal = floor($decimal / 16);
array_push($result, dechex($mod));
}
return join(array_reverse($result));
}
class EthereumRPCClient
{
public static $client = null;
//布署合約的賬戶地址
const COINBASE = '0x38aabef4cd283ccd5091298dedc88d27c5ec5750';
//合約地址
const CONTRACT = '0xaeab4084194B2a425096fb583Fbcd67385210ac3';
public static function __callStatic($method, $params)
{
$params = count($params) 1 ? [] : $params[0];
try {
if (is_null(self::$client)) {
self::$client = new jsonRPCClient('http://127.0.0.1:8545', true);
}
} catch (\Exception $e) {
echo $e->getMessage();
}
return call_user_func([self::$client, $method], $params);
}
public static function getBalance($address)
{
$method_hash = '0x70a08231';
$method_param1_hex = str_pad(substr($address, 2), 64, '0', STR_PAD_LEFT);
$data = $method_hash . $method_param1_hex;
$params = ['from' => $address, 'to' => self::CONTRACT, 'data' => $data];
$total_balance = self::eth_call([$params, "latest"]);
return hexdec($total_balance) / (pow(10, 18));
}
public static function transfer($to, $value)
{
self::personal_unlockAccount([self::COINBASE, "123456", 3600]);
$value = bcpow(10, 18) * $value;
$method_hash = '0xa9059cbb';
$method_param1_hex =str_pad(substr($to, 2), 64, '0', STR_PAD_LEFT);
$method_param2_hex = str_pad(strval(bc_dechex($value)), 64, '0', STR_PAD_LEFT);
$data = $method_hash . $method_param1_hex . $method_param2_hex;
$params = ['from' => self::COINBASE, 'to' => self::CONTRACT, 'data' => $data];
return self::eth_sendTransaction([$params]);
}
}
代碼比較簡(jiǎn)單, 要注意幾點(diǎn):
- transfer函數(shù)的value單位很小, 是 10 ^ -18, 所以如果你想轉(zhuǎn)1000個(gè),其實(shí)是要乘于 10的18次方, 這里的18是decimals.
- 由于第1點(diǎn), 應(yīng)該使用bcpow代替pow函數(shù).
- 不能使用php自帶的dechex函數(shù). 因?yàn)閐echex要求整型不能大于 PHP_INT_MAX, 而這個(gè)數(shù)在32位機(jī)上為4294967295。由于第1 點(diǎn), 所有的數(shù)都要乘于10的18次方, 所以得到的數(shù)要遠(yuǎn)遠(yuǎn)大于PHP_INT_MAX. 建議自己實(shí)現(xiàn)10進(jìn)制轉(zhuǎn)16進(jìn)制,如果你不知道如何實(shí)現(xiàn),參考上述代碼。
- 在運(yùn)行某些合約方法, 比如transfer時(shí), 要先unlock用戶.
- 發(fā)送交易之后, 一定要在服務(wù)器端啟動(dòng)挖礦, 這樣交易才會(huì)真的寫(xiě)入到區(qū)塊, 比如你調(diào)用transfer之后,卻發(fā)現(xiàn)對(duì)方?jīng)]有到賬,先別吃驚,啟動(dòng)挖礦試試。如果想啟用自動(dòng)挖碼, 在geth --rpc ...最后加上 --mine.
測(cè)試:
?php
var_dump(EthereumRPCClient::personal_newAccount(['password']));
var_dump(EthereumRPCClient::personal_unlockAccount([EthereumRPCClient::COINBASE, "password", 3600]);
var_dump(EthereumRPCClient::getBalance("0x...."));
您可能感興趣的文章:- AngularJS與后端php的數(shù)據(jù)交互方法
- vue.js過(guò)濾器+ajax實(shí)現(xiàn)事件監(jiān)聽(tīng)及后臺(tái)php數(shù)據(jù)交互實(shí)例
- 淺析PHP與Python進(jìn)行數(shù)據(jù)交互
- PHP MYSQL簡(jiǎn)易交互式站點(diǎn)開(kāi)發(fā)
- php微信公眾平臺(tái)交互與接口詳解
- 利用php做服務(wù)器和web前端的界面進(jìn)行交互
- PHP與服務(wù)器文件系統(tǒng)的簡(jiǎn)單交互
- PHP與以太坊交互詳解