Bit-Wasp / bitcoin-php

Bitcoin implementation in PHP
The Unlicense
1.05k stars 419 forks source link

InvalidArgumentException: HD key magic bytes do not match network magic bytes on Laravel 8 #901

Open latehLarry opened 2 years ago

latehLarry commented 2 years ago

I'm trying to generate wallet addresses from Master Public Key using the bitwasp/bitcoin package on laravel 8. I'm getting the issue below

InvalidArgumentException
HD key magic bytes do not match network magic bytes on
BitWasp\Bitcoin\Serializer\Key\HierarchicalKey\ExtendedKeySerializer::fromParser
C:\.........\vendor\bitwasp\bitcoin\src\Serializer\Key\HierarchicalKey\ExtendedKeySerializer.php:121

My code is as follows;

class ApiController extends Controller
{
    private $network = NULL;

    public function __construct($network = 'bitcoin')
    {
        if (version_compare(PHP_VERSION, '7.3') >= 0) {
            $this->network = NetworkFactory::$network();
          } elseif (version_compare(PHP_VERSION, '7.2.3') >= 0) {
            $this->network = call_user_func("NetworkFactory::$network");
          } else {
            $this->network = call_user_func('NetworkFactory', $network);
          }
    }
 public function createBTC()
    {

        // Bip39
        $xpub = 'MY_XPUB_KEY';
        $hdFactory = new HierarchicalKeyFactory();
        $key = $hdFactory->fromExtended($xpub, $this->network);
        $hardened = $key->derivePath("0/0");
        $privateKey =  $hardened->getPrivateKey()->toWif($this->network);
        $address = new PayToPubKeyHashAddress($hardened->getPublicKey()->getPubKeyHash($this->network));
        $address = $address->getAddress($this->network);

        $cred = new stdClass();
        $cred->balance = 0;
        $cred->address = $address;
        $cred->privateKey = $privateKey;

        return $json = json_encode($cred);
    }

}

Can't figure out what I'm doing wrong! Any help would be much appreciated.