blockcypher api メモ


環境

言語:php

BlockcypherAPIを通じて、HDウォレットでアドレス発行をするまで

(1)BlockcypherライブラリをComposerダウンロード

$composer require "blockcypher/php-client:*"

(2)(後々のことも考え)BlockCypherクラスを作る


//ライブラリの場所を指定
use blockcypher 

class BlockCypher{

  private $token = BLOCKCYPHER_TOKEN;
  private $apiContext;

  function __construct($network,$coin){

    $this->apiContext = new \BlockCypher\Rest\ApiContext(
                        new \BlockCypher\Auth\SimpleTokenCredential($this->token),
                        $network,
                        $coin
                      );

   $this->apiContext->setConfig(
                          array(
                            'mode' => 'sandbox',
                           'log.LogEnabled' => true,
                           'log.FileName' => 'BlockCypher.log',
                           'log.LogLevel' => 'DEBUG'
                        )
                      );
  }
}

(3)HDWalletを登録するメソッドを作成


public function createHDWallet($name,$xPub,$subChainIndex=array()){

 $wallet = new \BlockCypher\Api\HDWallet();
 $wallet -> setName($name);
 $wallet -> setExtendedPublicKey($xPub);

  if(!empty($subChainIndex)){
   $wallet -> setSubchainIndexes($subChainIndex);
  }

  $walletClient = new \BlockCypher\Client\HDWalletClient($this->apiContext);
  $createWallet = $walletClient -> create($wallet);

  return $createWallet;
}

(4)拡張公開鍵の取得

Electrum,TREZOR、Copay、bcwalletなどで拡張公開鍵を取得。
ちなみにBIP39に従ったHDウォレットを用意すること。

大抵のHDウォレット階層は、
m/44'/1'/0 になっている。

(5)登録する

$network = 'test3'; // メインネット: 'main' , テストネット: 'test3'
$coin    = 'btc' ;
$blockcypher = new BlockCypher($network,$coin);

//(5)で取得した拡張公開鍵
$xpub = 'tpub123456789....';

//HDウォレットの階層を示すindex
$subchainIndex = array(0,0); // m/44'/1'/0'の場合

echo $blockcypher->createHDWallet('walletName',$xpub,$subchainIndex);

(6)アドレスを発行するメソッドを作る

public function generateAddress(){

 $addressClient = new \BlockCypher\Client\AddressClient($this->apiContext);

 try {
  $addressKeyChain = $addressClient->generateAddress();
 } catch (Exception $ex) {
  throw new InternalErrorException();
 }
 return $addressKeyChain;
}

(7)アドレスを発行する

$newAddrInfo = [];
$new = json_decode($blockcypher-> deriveHDAddress(BLOCKCYPHER_WALLET))->chains[0];

$chain_address = $new->chain_addresses[0];
$newAddrInfo["btc_addr"] = $chain_address->address;
$newAddrInfo["pubkey"] = $chain_address->public;
$newAddrInfo["path"] = $chain_address->path;

var_dump($newAddrInfo); 
//array(3) { ["btc_addr"]=> string(34) "n1JAkBPeVdnZsj5QAMU2Zh4BMmNALZTQKb" ["pubkey"]=> string(66) "03a5e87c89c43e154083ca9e438db6d5bcb1b160bb4103ed043f67db5e1b3886de" ["path"]=> string(5) "m/0/0" } 

最後の表示されるアドレスが、(4)で用意したウォレットの受信アドレスと同一のものであればOK。