当前位置:首页 > PHP教程 > php高级应用 > 列表

详解php与ethereum客户端交互

发布:smiling 来源: PHP粉丝网  添加日期:2021-09-15 10:38:17 浏览: 评论:0 

本篇文章给大家讲述了php与ethereum客户端交互的相关知识点,对此有需要的朋友可以跟着学习下。

php与ethereum rpc server通信

一、Json RPC

Json RPC就是基于json的远程过程调用,这么解释比较抽象。简单来说,就是post一个json格式的数据调用rpc server中的方法. 而这个json格式是固定的, 总的来说有这么几项:

  1. { 
  2.   "method": "", 
  3.   "params": [], 
  4.   "id": idNumber 
  5. } 

method: 方法名

params: 参数列表

id: 对过程调用的唯一标识号

二、构建一个Json RPC客户端

  1. <?php 
  2.  
  3. class jsonRPCClient { 
  4.     
  5.   /** 
  6.    * Debug state 
  7.    * 
  8.    * @var boolean 
  9.    */ 
  10.   private $debug; 
  11.     
  12.   /** 
  13.    * The server URL 
  14.    * 
  15.    * @var string 
  16.    */ 
  17.   private $url; 
  18.   /** 
  19.    * The request id 
  20.    * 
  21.    * @var integer 
  22.    */ 
  23.   private $id; 
  24.   /** 
  25.    * If true, notifications are performed instead of requests 
  26.    * 
  27.    * @var boolean 
  28.    */ 
  29.   private $notification = false; 
  30.     
  31.   /** 
  32.    * Takes the connection parameters 
  33.    * 
  34.    * @param string $url 
  35.    * @param boolean $debug 
  36.    */ 
  37.   public function __construct($url,$debug = false) { 
  38.     // server URL 
  39.     $this->url = $url; 
  40.     // proxy 
  41.     emptyempty($proxy) ? $this->proxy = '' : $this->proxy = $proxy; 
  42.     // debug state 
  43.     emptyempty($debug) ? $this->debug = false : $this->debug = true; 
  44.     // message id 
  45.     $this->id = 1; 
  46.   } 
  47.     
  48.   /** 
  49.    * Sets the notification state of the object. In this state, notifications are performed, instead of requests. 
  50.    * 
  51.    * @param boolean $notification 
  52.    */ 
  53.   public function setRPCNotification($notification) { 
  54.     emptyempty($notification) ? 
  55.               $this->notification = false 
  56.               : 
  57.               $this->notification = true; 
  58.   } 
  59.     
  60.   /** 
  61.    * Performs a jsonRCP request and gets the results as an array 
  62.    * 
  63.    * @param string $method 
  64.    * @param array $params 
  65.    * @return array 
  66.    */ 
  67.   public function __call($method,$params) { 
  68.       
  69.     // check 
  70.     if (!is_scalar($method)) { 
  71.       throw new Exception('Method name has no scalar value'); 
  72.     } 
  73.       
  74.     // check 
  75.     if (is_array($params)) { 
  76.       // no keys 
  77.       $params = $params[0]; 
  78.     } else { 
  79.       throw new Exception('Params must be given as array'); 
  80.     } 
  81.       
  82.     // sets notification or request task 
  83.     if ($this->notification) { 
  84.       $currentId = NULL; 
  85.     } else { 
  86.       $currentId = $this->id; 
  87.     } 
  88.       
  89.     // prepares the request 
  90.     $request = array( 
  91.             'method' => $method, 
  92.             'params' => $params, 
  93.             'id' => $currentId 
  94.             ); 
  95.     $request = json_encode($request); 
  96.     $this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n"; 
  97.  
  98.     // performs the HTTP POST 
  99.     $opts = array ('http' => array ( 
  100.               'method' => 'POST', 
  101.               'header' => 'Content-type: application/json', 
  102.               'content' => $request 
  103.               )); 
  104.     $context = stream_context_create($opts); 
  105.     if ($fp = fopen($this->url, 'r', false, $context)) { 
  106.       $response = ''; 
  107.       while($row = fgets($fp)) { 
  108.         $response.= trim($row)."\n"; 
  109.       } 
  110.       $this->debug && $this->debug.='***** Server response *****'."\n".$response.'***** End of server response *****'."\n"; 
  111.       $response = json_decode($response,true); 
  112.     } else { 
  113.       throw new Exception('Unable to connect to '.$this->url); 
  114.     } 
  115.       
  116.     // debug output 
  117.     if ($this->debug) { 
  118.       echo nl2br($debug); 
  119.     } 
  120.       
  121.     // final checks and return 
  122.     if (!$this->notification) { 
  123.       // check 
  124.       if ($response['id'] != $currentId) { 
  125.         throw new Exception('Incorrect response id (request id: '.$currentId.', response id: '.$response['id'].')'); 
  126.       } 
  127.       if (!is_null($response['error'])) { 
  128.         throw new Exception('Request error: '. var_export($response['error'], true)); 
  129.       } 
  130.         
  131.       return $response['result']; 
  132.         
  133.     } else { 
  134.       return true; 
  135.     } 
  136.   } 
  137. } 
  138. ?> 

比较简单的代码,如果比较懒,拿过去用就行了,也可以上packagist.org自己找一个rpc client.

三、调用RPC的两类方法

有两类方法需要调用. 一类是RPC server自带方法,另一类就是合约方法.

RPC server方法调用json格式

  1. { 
  2.   "method": "eth_accounts", 
  3.   "params": [], 
  4.   "id": 1 
  5. } 

RPC Server自带方法的列表

调用自带方法比较简单,参考上述链接,大部分都有示例.

合约方法调用json格式

调用合约方法必须使用自带方法中的eth_call. 而合约方法名称和合约方法参数列表则使用params进行体现, 比如: 我们要调用合约中的balanceOf方法, 则json数据应该如何构造呢?

首先看看getBalanace的函数实现:

function balanceOf(address _owner) public view returns (uint256 balance)

提炼出函数原型:

balanceOf(address)

在geth控制台下运行命令:

web3.sha3("balanceOf(address)").substring(0, 10)

得到函数hash "0x70a08231"

假设待查询的地址 address _owner = "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", 则去掉前面的"0x", 并在左边补24个零(一般地址长度为42位, 去掉'0x'后为40位),构成64位十六进制参数.

最终得到的参数为 "0x70a0823100000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750"

假设我们的合约地址为 "0xaeab4084194B2a425096fb583Fbcd67385210ac3".

则得到最终的json数据为:

  1. { 
  2.   "method": "eth_call", 
  3.   "params": [{"from": "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", "to": "0xaeab4084194B2a425096fb583Fbcd67385210ac3", "data": "0x70a0823100000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750"}, "latest"], 
  4.   "id": 1 
  5. } 

把以上json数据以post方式发送给服务器,就可以调用合约方法"balanceOf", 查询给定的地址中的代币余额.

调用合约中的其他方法也要新遵循上面的方式, 我们再分析一下transfer方法, 加深印象:

首先, 看看代码中的函数实现:

function transfer(address _to, uint256 _value) public returns (bool)

其次, 提炼出函数原型:

transfer(address,uint256) //注意逗号后面不能有空格

再次, 在控制台运行sha3函数:

web3.sha3("transfer(address,uint256)").substring(0, 10)

得到函数hash "0xa9059cbb"

第一个参数假设 address _to = "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", 则去"0x", 补零到64位.

第二个参数假设 uint256 _value = 43776, 则化为十六进制"0xab00"后, 去"0x", 补零到64位.

连接起来

"0xa9059cbb00000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750000000000000000000000000000000000000000000000000000000000000ab00"

构建json数据:

  1. { 
  2.   "method": "eth_call", 
  3.   "params": [{"from": "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", "to": "0xaeab4084194B2a425096fb583Fbcd67385210ac3", "data": "0xa9059cbb00000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750000000000000000000000000000000000000000000000000000000000000ab00"}, "latest"], 
  4.   "id": 1 
  5. } 

from 转出者地址

to 合约地址

data 上述操作得到的十六进制数

把以上的步骤转化为代码.

构建一个以太坊RPC client

  1. <?php  
  2.  
  3. require './jsonRPCClient.php'; 
  4.  
  5. //php自带的dechex无法把大整型转换为十六进制 
  6. function bc_dechex($decimal) 
  7. { 
  8.   $result = []; 
  9.  
  10.   while ($decimal != 0) { 
  11.     $mod = $decimal % 16; 
  12.     $decimal = floor($decimal / 16); 
  13.     array_push($result, dechex($mod));     
  14.   } 
  15.  
  16.   return join(array_reverse($result)); 
  17. } 
  18.  
  19. class EthereumRPCClient 
  20. { 
  21.   public static $client = null; 
  22.     
  23.   //布署合约的账户地址 
  24.   const COINBASE = '0x38aabef4cd283ccd5091298dedc88d27c5ec5750'; 
  25.     
  26.   //合约地址 
  27.   const CONTRACT = '0xaeab4084194B2a425096fb583Fbcd67385210ac3'; 
  28.  
  29.   public static function __callStatic($method, $params) 
  30.   { 
  31.     $params = count($params) < 1 ? [] : $params[0]; 
  32.  
  33.     try { 
  34.       if (is_null(self::$client)) { 
  35.         self::$client = new jsonRPCClient('http://127.0.0.1:8545', true);   
  36.       } 
  37.     } catch (\Exception $e) { 
  38.       echo $e->getMessage(); 
  39.     } 
  40.  
  41.     return call_user_func([self::$client, $method], $params); 
  42.  
  43.   } 
  44.  
  45.   public static function getBalance($address) 
  46.   { 
  47.     $method_hash = '0x70a08231'; 
  48.     $method_param1_hex = str_pad(substr($address, 2), 64, '0', STR_PAD_LEFT); 
  49.     $data = $method_hash . $method_param1_hex; 
  50.  
  51.     $params = ['from' => $address, 'to' => self::CONTRACT, 'data' => $data]; 
  52.  
  53.     $total_balance = self::eth_call([$params, "latest"]); 
  54.  
  55.     return hexdec($total_balance) / (pow(10, 18)); 
  56.   } 
  57.  
  58.   public static function transfer($to, $value) 
  59.   { 
  60.     self::personal_unlockAccount([self::COINBASE, "123456", 3600]); 
  61.  
  62.     $value = bcpow(10, 18) * $value; 
  63.  
  64.     $method_hash = '0xa9059cbb'; 
  65.     $method_param1_hex =str_pad(substr($to, 2), 64, '0', STR_PAD_LEFT);   
  66.     $method_param2_hex = str_pad(strval(bc_dechex($value)), 64, '0', STR_PAD_LEFT); 
  67.  
  68.     $data = $method_hash . $method_param1_hex . $method_param2_hex; 
  69.     $params = ['from' => self::COINBASE, 'to' => self::CONTRACT, 'data' => $data]; 
  70.  
  71.     return self::eth_sendTransaction([$params]); 
  72.  
  73.   } 
  74.  
  75. } 

代码比较简单, 要注意几点:

transfer函数的value单位很小, 是 10 ^ -18, 所以如果你想转1000个,其实是要乘于 10的18次方, 这里的18是decimals.

由于第1点, 应该使用bcpow代替pow函数.

不能使用php自带的dechex函数. 因为dechex要求整型不能大于 PHP_INT_MAX, 而这个数在32位机上为4294967295。由于第1 点, 所有的数都要乘于10的18次方, 所以得到的数要远远大于PHP_INT_MAX. 建议自己实现10进制转16进制,如果你不知道如何实现,参考上述代码。

在运行某些合约方法, 比如transfer时, 要先unlock用户.

发送交易之后, 一定要在服务器端启动挖矿, 这样交易才会真的写入到区块, 比如你调用transfer之后,却发现对方没有到账,先别吃惊,启动挖矿试试,如果想启用自动挖码, 在geth --rpc ...最后加上 --mine.

测试:

  1. <?php  
  2. var_dump(EthereumRPCClient::personal_newAccount(['password'])); 
  3. var_dump(EthereumRPCClient::personal_unlockAccount([EthereumRPCClient::COINBASE, "password", 3600]); 
  4. var_dump(EthereumRPCClient::getBalance("0x...."));

Tags: php客户端交互 ethereum

分享到: