bitcoin-php icon indicating copy to clipboard operation
bitcoin-php copied to clipboard

How to get private key of derived address?

Open Schiocco opened this issue 3 years ago • 0 comments

I'm trying to get the private key of the derived address generated from the code below. I know I must pass my private key somewhere, but I do not know where. This problem is the function $child_key->getPrivateKey(). It returns an error: Unable to get private key, not known.

    $xpub = '...........';
    $pubkeytype = substr($xpub, 0, 4);
    $bitcoin_prefixes = new BitcoinRegistry();
    $adapter = Bitcoin::getEcAdapter();
    $slip132 = new Slip132(new KeyToScriptHelper($adapter));
    if ($pubkeytype == 'xpub') $pubPrefix = $slip132->p2pkh($bitcoin_prefixes);
    if ($pubkeytype == 'ypub') $pubPrefix = $slip132->p2shP2wpkh($bitcoin_prefixes);
    if ($pubkeytype == 'zpub') $pubPrefix = $slip132->p2wpkh($bitcoin_prefixes);
    $config = new GlobalPrefixConfig([new NetworkConfig(NetworkFactory::bitcoin(), [$pubPrefix])]);
    $serializer = new Base58ExtendedKeySerializer(new ExtendedKeySerializer($adapter, $config));
    $key = $serializer->parse(NetworkFactory::bitcoin(), $xpub);
    $child_key = $key->derivePath($path);
    return [$child_key->getPrivateKey(), $child_key->getAddress(new AddressCreator())->getAddress()];

Thank you!

Schiocco avatar Jan 12 '23 17:01 Schiocco