首頁  >  文章  >  後端開發  >  詳解php與ethereum客戶端交互php實例

詳解php與ethereum客戶端交互php實例

jacklove
jacklove原創
2018-06-26 17:02:182482瀏覽

這篇文章告訴大家了php與ethereum客戶端互動的相關知識點,對此有需要的朋友可以跟著學習下。

php與ethereum rpc server通訊

一、Json RPC

##Json RPC就是基於json的遠端過程調用,這麼解釋比較抽象。簡單來說,就是post一個json格式的資料呼叫rpc server中的方法. 而這個json格式是固定的, 總的來說有這麼幾項:

{
  "method": "",
  "params": [],
  "id": idNumber
}

  • method: 方法名稱

  • params: 參數清單

  • id: 對過程呼叫的唯一標識號碼

二、建構一個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 = &#39;&#39; : $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(&#39;Method name has no scalar value&#39;);
    }
    
    // check
    if (is_array($params)) {
      // no keys
      $params = $params[0];
    } else {
      throw new Exception(&#39;Params must be given as array&#39;);
    }
    
    // sets notification or request task
    if ($this->notification) {
      $currentId = NULL;
    } else {
      $currentId = $this->id;
    }
    
    // prepares the request
    $request = array(
            &#39;method&#39; => $method,
            &#39;params&#39; => $params,
            &#39;id&#39; => $currentId
            );
    $request = json_encode($request);
    $this->debug && $this->debug.=&#39;***** Request *****&#39;."\n".$request."\n".&#39;***** End Of request *****&#39;."\n\n";

    // performs the HTTP POST
    $opts = array (&#39;http&#39; => array (
              &#39;method&#39; => &#39;POST&#39;,
              &#39;header&#39; => &#39;Content-type: application/json&#39;,
              &#39;content&#39; => $request
              ));
    $context = stream_context_create($opts);
    if ($fp = fopen($this->url, &#39;r&#39;, false, $context)) {
      $response = &#39;&#39;;
      while($row = fgets($fp)) {
        $response.= trim($row)."\n";
      }
      $this->debug && $this->debug.=&#39;***** Server response *****&#39;."\n".$response.&#39;***** End of server response *****&#39;."\n";
      $response = json_decode($response,true);
    } else {
      throw new Exception(&#39;Unable to connect to &#39;.$this->url);
    }
    
    // debug output
    if ($this->debug) {
      echo nl2br($debug);
    }
    
    // final checks and return
    if (!$this->notification) {
      // check
      if ($response[&#39;id&#39;] != $currentId) {
        throw new Exception(&#39;Incorrect response id (request id: &#39;.$currentId.&#39;, response id: &#39;.$response[&#39;id&#39;].&#39;)&#39;);
      }
      if (!is_null($response[&#39;error&#39;])) {
        throw new Exception(&#39;Request error: &#39;. var_export($response[&#39;error&#39;], true));
      }
      
      return $response[&#39;result&#39;];
      
    } 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 = "0x38aabef4cd283ccd5091298dedc85027c5ec 則去掉前面的"0x", 並在左邊補24個零(一般地址長度為42位, 去掉'0x'後為40位),構成64位十六進位參數.

最終得到的參數為"0x70a0823100000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750"

假設我們的合約位址為我們的合約位址為"0xae40845852F .

則得到最終的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", 補零到dc88d27c5ec5750", 則去"0x", 補零到dc64


  • 二個參數假設uint256 _value = 43776, 則化為十六進位"0xab00"後, 去"0x", 補零到64位.

#連接起來

27c5ec57500000000000000000000000000000000000000000000000000000000000ab00"

建立json資料:

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

  • #from 轉出者位址

  • #to 合約位址
  • data 上述運算所得到的十六進位數

  • 把以上的步驟轉換成程式碼.
建立一個以太坊RPC client

<?php 

require &#39;./jsonRPCClient.php&#39;;

//php自带的dechex无法把大整型转换为十六进制
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 = &#39;0x38aabef4cd283ccd5091298dedc88d27c5ec5750&#39;;
  
  //合约地址
  const CONTRACT = &#39;0xaeab4084194B2a425096fb583Fbcd67385210ac3&#39;;

  public static function __callStatic($method, $params)
  {
    $params = count($params) < 1 ? [] : $params[0];

    try {
      if (is_null(self::$client)) {
        self::$client = new jsonRPCClient(&#39;http://127.0.0.1:8545&#39;, true);  
      }
    } catch (\Exception $e) {
      echo $e->getMessage();
    }

    return call_user_func([self::$client, $method], $params);

  }

  public static function getBalance($address)
  {
    $method_hash = &#39;0x70a08231&#39;;
    $method_param1_hex = str_pad(substr($address, 2), 64, &#39;0&#39;, STR_PAD_LEFT);
    $data = $method_hash . $method_param1_hex;

    $params = [&#39;from&#39; => $address, &#39;to&#39; => self::CONTRACT, &#39;data&#39; => $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 = &#39;0xa9059cbb&#39;;
    $method_param1_hex =str_pad(substr($to, 2), 64, &#39;0&#39;, STR_PAD_LEFT);  
    $method_param2_hex = str_pad(strval(bc_dechex($value)), 64, &#39;0&#39;, STR_PAD_LEFT);

    $data = $method_hash . $method_param1_hex . $method_param2_hex;
    $params = [&#39;from&#39; => self::COINBASE, &#39;to&#39; => self::CONTRACT, &#39;data&#39; => $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.################測試:#########
<?php 
var_dump(EthereumRPCClient::personal_newAccount([&#39;password&#39;]));
var_dump(EthereumRPCClient::personal_unlockAccount([EthereumRPCClient::COINBASE, "password", 3600]);
var_dump(EthereumRPCClient::getBalance("0x...."));
# ########相關推薦:#########PHP cURL取得微信公眾號access_token的實例php實例#########

PHP實作轉盤抽獎演算法分享php實例

PHP使用curl_multi實作並發請求的方法範例php技巧


#

以上是詳解php與ethereum客戶端交互php實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn