bitpay / bitcore-lib

A pure and powerful JavaScript Bitcoin library
https://bitcore.io/
Other
613 stars 1.03k forks source link

How to sign transaction using HD Key. #183

Closed ghost closed 6 years ago

ghost commented 6 years ago

I created a wallet with HD keys and created the transaction. I am able to sign and broadcast transaction using normal keys but how should I sign the transaction using HD Keys?

My code is:

var DEBUG = true;
function sendTransactionfromUtxosTestnet(addressOutpoint, sendAddress, changeAddress, amount, fee, privatekey) {
DEBUG && console.log("sendTransactionfromUtxosTestnet: Starting");
var sendAdd = bitcore.Address.fromString(sendAddress);
var changeAdd = bitcore.Address.fromString(changeAddress);
return new Promise(function(resolve, reject) {
insightTestnet.getUnspentUtxos(addressOutpoint, function(err, utxos){
    if (err)  {
      //Handle the errors
      DEBUG && console.log("sendTransactionfromUtxosTestnet: Error - ");
      DEBUG && console.log(err);
      return reject(err);
    }
    else  {
      //create transaction with utxo
      DEBUG && console.log("sendTransactionfromUtxosTestnet: The unspent output is - ");
      DEBUG && console.log(utxos);
      var tx = bitcore.Transaction();
      tx.from(utxos);
      tx.to(sendAdd, amount);
      tx.change(changeAdd);
      tx.fee(fee);
      DEBUG && console.log("sendTransactionfromUtxosTestnet: The created transaction is - ");
      DEBUG && console.log(tx);
      var HDPrivateKey = bitcore.HDPrivateKey;
      var hdprivatekey = new HDPrivateKey(privatekey);
      var signingKey = new bitcore.PrivateKey(hdprivatekey.toObject().privateKey);
      tx.sign(signingKey);
      DEBUG && console.log("sendTransactionfromUtxosTestnet: The signed transaction is - ");
      DEBUG && console.log(tx);
      insightTestnet.broadcast(tx.serialize(), function(err, returnedTxId) {
      if (err) {
              // Handle the errors here
      }
      else {
              DEBUG && console.log("Transaction broadcast successfull: ", returnedTxId);
      }
      });
      DEBUG && console.log("getTransactionfromUtxosTestnet: Ending");
      resolve(tx);
      }
  });
});
}

If I directly pass the HD key to sign function, it gives me invalid argument and in this code it throws ErrorTransactionMissingSignatures: Some inputs have not been fully signed.

Can I use the Master Private Key to sign the transaction or do I need to use individual keys corresponding to addresses?

I am using browser libraries. Much help appreciated. Thanks

ghost commented 6 years ago

I can broadcast if I use all the child private keys to sign the transaction. Closing it. Thanks