6

I need some PHP code to generate bitcoin addresses from a given public key.

I can only find algorithms to generate addresses from the master private key but according to https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses the private key is not required at all.

2 Answers 2

8

Use BitWasp Bitcoin-php library https://github.com/Bit-Wasp/bitcoin-php

<?php
use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Key\PrivateKeyFactory;

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

If you want to create Bitcoin address from Public key string check documentation for Factory classes

or newer versions:

<?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->getPublicKey();

$addrCreator = new AddressCreator();
$factory = new P2pkhScriptDataFactory();
$scriptPubKey = $factory->convertKey($publicKey)->getScriptPubKey();
$address = $addrCreator->fromOutputScript($scriptPubKey); // returns AddressInterface
echo $address->getAddress($network); // prints address for $network as string
2
  • This answer still uses a private key and is not purely public key based, like asked for.
    – Wouter
    Jun 24, 2018 at 12:10
  • You can do PublicKeyFactory::fromHex and avoid using a private key. For newer versions, getAddress was removed, see this example github.com/Bit-Wasp/bitcoin-php/blob/…
    – karimkorun
    May 16, 2019 at 14:46
2

Full instruction based on response of @Farghaly: Ubuntu 16

Install dependencies

sudo apt-get install php-bcmath php-gmp
composer require bitwasp/bitcoin

And then in fiel app.php

<?php
require 'vendor/autoload.php';

use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Address;
use BitWasp\Bitcoin\Key\PrivateKeyFactory;

$network = Bitcoin::getNetwork();

$privateKey = PrivateKeyFactory::create(true);
$publicKey = $privateKey->getPublicKey();
$address = $publicKey->getAddress();
2
  • vendor/autoload.php where can i find this file?
    – makasci
    Dec 11, 2021 at 21:50
  • @makasci I believe it is automatically generated by composer when you run composer install Dec 12, 2021 at 1:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.