侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

详解php与ethereum客户端交互

php  /  管理员 发布于 7年前   137

php与ethereum rpc server通信

一、Json RPC

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

{  "method": "",  "params": [],  "id": idNumber}
  • method: 方法名
  • params: 参数列表
  • id: 对过程调用的唯一标识号

二、构建一个Json RPC客户端

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;    }  }}?>

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

三、调用RPC的两类方法

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

RPC server方法调用json格式

{  "method": "eth_accounts",  "params": [],  "id": 1}

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数据为:

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

把以上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数据:

{  "method": "eth_call",  "params": [{"from": "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", "to": "0xaeab4084194B2a425096fb583Fbcd67385210ac3", "data": "0xa9059cbb00000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750000000000000000000000000000000000000000000000000000000000000ab00"}, "latest"],  "id": 1}
  • from 转出者地址
  • to 合约地址
  • data 上述操作得到的十六进制数

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

构建一个以太坊RPC client

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]);  }}

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

  • 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.

测试:

您可能感兴趣的文章:

  • AngularJS与后端php的数据交互方法
  • vue.js过滤器+ajax实现事件监听及后台php数据交互实例
  • 浅析PHP与Python进行数据交互
  • PHP MYSQL简易交互式站点开发
  • php微信公众平台交互与接口详解
  • 利用php做服务器和web前端的界面进行交互
  • PHP与服务器文件系统的简单交互
  • PHP与以太坊交互详解


  • 上一条:
    PHP实现转盘抽奖算法分享
    下一条:
    360搜索引擎自动收录php改写方案
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客