Segregated-Witness

使用 bitcoinjs-lib 從 base58 rootKey 生成 zprv

  • May 14, 2021
var bitcoin = require('bitcoinjs-lib');
let bip32 = require('bip32');

let rootKey = 'xprv9s21ZrQH143K32CfqoCQHtbKiEb5BqFazXX6jCtNCnuty3gUjxS4CsXWi9rcNyHdjDVPiC6P1bnyEZr2ioouRq56h6HAdwejeTty1BsSEtL'
const node = bip32.fromBase58(rootKey, bitcoin.networks.bitcoin);

//legacy account extended private key
console.log("LEGACY: " + node.derivePath("m/44'/0'/0").toBase58())
//xprv9y7nL2k2diLdA9bmop94K8Pec2WdL998PLdvTraxj5jiQ36gnLmhVJG4bY8FzgqZPaBM5HDBi9sgRK1ZCi14n5j4Pk1o6d3j4Y6T9NS4nA6
(works as expected)


//segwit account extended private key
//trying to get a segwit extended private key (zprv) using the same inputs as above.

我想使用與上述相同的根密鑰獲得一個 segwit/bech32 擴展私鑰。如何使用 bitcoinjs-lib 做到這一點?BIP84 僅適用於助記符 IIRC。

xprv已經擁有“烘焙”的派生路徑,因此即使您只是轉換為zprv它,仍將位於舊的 m44/派生路徑下。您也不能從 xprv 轉到 HD 種子。因此,要從 xprv 更改為 zprv 或 yprv,您需要從 HD 種子開始,然後聲明您的 derivedPath(“m84’/…”,“m49/’/… etc),然後您可以創建一個擴展公鑰。然後您必須轉換為 yprv、zprv、ypub 等…

範例使用 bitcoinjs-lib v3.3.2

function seedToXpub(seed, deriv, account){
  var root = bitcoin.HDNode.fromSeedHex(seed);
  var acct = root.derivePath("m/"+deriv+"'/0'/"+account+"'");
  var xpub = acct.neutered().toBase58();
  return{
      xpub
  }
}

function seedToXprv(seed, deriv, account){
  var root = bitcoin.HDNode.fromSeedHex(seed);
  var acct = root.derivePath("m/"+deriv+"'/0'/"+account+"'");
  var xprv = acct.toBase58();
  return{
      xprv
  }
}

function convertXpub(xpub,target){
   //source script for converter https://github.com/jlopp/xpub-converter/blob/master/js/xpubConvert.js
   const prefixes = new Map(
 [
   ['xpub', '0488b21e'],
   ['ypub', '049d7cb2'],
   ['Ypub', '0295b43f'],
   ['zpub', '04b24746'],
   ['Zpub', '02aa7ed3'],
     ['xprv', '0488ade4'],
     ['yprv', '049d7878'],
     ['zprv', '04b2430c']
 ]
 );
   
 xpub = xpub.trim();

 try {
   var data = b58.decode(xpub);
   data = data.slice(4);
   data = Buffer.concat([Buffer.from(prefixes.get(target),'hex'), data]);
   return b58.encode(data);
 } catch (err) {
   return "Invalid extended public key! Please double check that you didn't accidentally paste extra data.";
 }    
}

var mySeed = "114259550292e14ca462e5202875f987fa3c93300306417c8b62de591710e4b34340a9bcdf8241ebbe83cf3cdf428c2f32973c9db68e247ce623fd73b9bd1fb2";
var extPriv = seedToXprv(mySeed,84,0);
var zprv = convertXpub(extPriv,"zprv"); 

//zprvAcihK1ERNzUfX6zh3v8weMVw5s8Y2xkmjdEfeFF3v9X2jbDf9iJ4vS5t4Po6Jhwsjkzjz1TddTENc5dPVsVFyMZPzWz8Kskci6wkYSmuhup

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