Address

如何在 PHP 中生成地址

  • December 11, 2021

我需要一些 PHP 程式碼從給定的公鑰生成比特幣地址。

我只能找到從主私鑰生成地址的算法,但根據<https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses> 根本不需要私鑰。

使用 BitWasp Bitcoin-php 庫 <https://github.com/Bit-Wasp/bitcoin-php>

&lt;?php
use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Key\PrivateKeyFactory;

$network = Bitcoin::getNetwork();
$privateKey = PrivateKeyFactory::create(true);
$publicKey = $privateKey-&gt;getPublicKey();
$address = $publicKey-&gt;getAddress(); // returns AddressInterface
echo $address-&gt;getAddress($network); // prints address for $network as string

如果您想從公鑰字元串創建比特幣地址,請查看Factory 類的文件

或更新版本:

&lt;?php
use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Address\AddressCreator;
use BitWasp\Bitcoin\Key\PrivateKeyFactory;
use BitWasp\Bitcoin\Key\KeyToScript\Factory\P2pkhScriptDataFactory; 

$network = Bitcoin::getNetwork();
$privateKey = PrivateKeyFactory::create(true);
$publicKey = $privateKey-&gt;getPublicKey();

$addrCreator = new AddressCreator();
$factory = new P2pkhScriptDataFactory();
$scriptPubKey = $factory-&gt;convertKey($publicKey)-&gt;getScriptPubKey();
$address = $addrCreator-&gt;fromOutputScript($scriptPubKey); // returns AddressInterface
echo $address-&gt;getAddress($network); // prints address for $network as string

引用自:https://bitcoin.stackexchange.com/questions/48023