Skip to content

Instantly share code, notes, and snippets.

@nmarley
Last active December 15, 2016 02:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmarley/e18d961ef0d557031d11 to your computer and use it in GitHub Desktop.
Save nmarley/e18d961ef0d557031d11 to your computer and use it in GitHub Desktop.
BIP32 serialization version byte swap using BitWasp's bitcoin-php library
<?php
use BitWasp\Bitcoin\Base58;
use BitWasp\Buffertools\Buffer;
use BitWasp\Buffertools\BufferInterface;
use BitWasp\Buffertools\Buffertools;
require "./vendor/autoload.php";
class XKeyUtil {
private static $VERSION_PREFIXES = [
'drkv' => '02fe52f8',
'drkp' => '02fe52cc',
'DRKV' => '3a8061a0',
'DRKP' => '3a805837',
'xpub' => '0488b21e',
'xprv' => '0488ade4',
'tpub' => '043587cf',
'tprv' => '04358394',
];
static public function swap_prefix($xkey, $prefix) {
$hex;
try {
$hex = Base58::decodeCheck($xkey)->getHex();
}
catch (\Exception $e) {
$hex = 'Invalid base58 data';
}
$nh = self::$VERSION_PREFIXES[$prefix] . substr($hex, 8, 156);
$new_xkey = Base58::encodeCheck(Buffer::hex($nh));
return $new_xkey;
}
}
// Convert this 'tpub' xkey (Bitcoin testnet extended public key) into a
// Dash testnet public key (should be DRKV...)
//
$xpub = 'tpubD6NzVbkrYhZ4XaR63SeDvZ4M8FVvK7Lm1YKn88N1Zbv8JQhKJdESyXpNJX6uSmZKeDKsVCXyJ57rsUi7VtPbdEMApmBuJidFAuFg7xRohCZ';
$hex;
try {
$hex = Base58::decodeCheck($xpub)->getHex();
}
catch (\Exception $e) {
$hex = 'Invalid base58 data';
}
$nk = XKeyUtil::swap_prefix($xpub, 'DRKV');
echo $nk . PHP_EOL;
// Result should be:
//
// DRKVrRjogj3bNiLD8U7tZnDNvmKhJD4Jb6CKF61rFBo5rCg5JnWFaySgX4u6q7brLyEMPr6TSnNSRwg42HBSgEwjR4Lss9cbuThGz3qEqdKmfSKf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment