bitcoinjs / bitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.
MIT License
5.7k stars 2.11k forks source link

Possibly unhandled Error: No free outputs to spend #1360

Closed anjalialance closed 5 years ago

anjalialance commented 5 years ago

Hello,

I am new to bitcoin transactions. I am using bitcoinjs-lib and blockexplorer for the transaction. The thing that is happening with me is that if I am entering new address that is generated by bip32 and bip39

The address and private key are-

sender address - motCmpWMeMC6BTRUtryxMATUBCvGorAjcs private key - L1Eoyo3BN41AAxZE1wrJrHYNoxHZhNrtKtgTHVG1axiXJcs6TCkj receiver address - myQdZsy9wRd4A7deRBm88RZX9rv19NDGyB

then it is giving me error. Also, if i am entering the address which I have previously used in transaction procedures. It is generating same transaction ids again and again.

The address that i am using for this is -

sender address - mkX9cVJDWjPxxfwNvYg58fbR2vHRfuU6XJ private key - KwV364bGF83ie4wJSwzV4hccbLeyMnFSVwyPvdMEnU8cr6Nyu25U receiver address - mthGgBTX1kxibjXwXxy5jraBNtTsajpqSx

Possibly unhandled Error: No free outputs to spend at Object.ensureErrorObject (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\util.js:261:20) at Promise._rejectCallback (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:472:22) at Promise._settlePromiseFromHandler (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:516:17) at Promise._settlePromiseAt (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:584:18) at Promise._settlePromises (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:700:14) at Async._drainQueue (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\async.js:123:16) at Async._drainQueues (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\async.js:133:10) at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\async.js:15:14) at processImmediate (timers.js:632:19) Possibly unhandled Error: No free outputs to spend at Object.ensureErrorObject (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\util.js:261:20) at Promise._rejectCallback (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:472:22) at Promise._settlePromiseFromHandler (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:516:17) at Promise._settlePromiseAt (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:584:18) at Promise._settlePromises (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\promise.js:700:14) at Async._drainQueue (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\async.js:123:16) at Async._drainQueues (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\async.js:133:10) at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\ADMIN\Desktop\btc\node_modules\blockchain.info\node_modules\bluebird\js\main\async.js:15:14) at processImmediate (timers.js:632:19)

This is the error.

and Here, is the code.

var keyPair = bitcoin.ECPair.makeRandom();
var testnet = bitcoin.networks.testnet;
var mnemonic = bip39.generateMnemonic();
var seed = bip39.mnemonicToSeed(mnemonic);
var master=bip32.fromSeed(seed);
var derived = master.derivePath("m/44'/0'/0'/0/0");
var {address} = bitcoin.payments.p2pkh({pubkey : keyPair.publicKey, network: testnet});
res.send(address);
var privateKey=keyPair.toWIF();
res.send(privateKey);
algorithm = 'AES-256-CBC'; // CBC because CTR isn't possible with the current version of the Node.JS crypto library
hmac_algorithm = 'SHA256';
hash = crypto.randomBytes(32); // This key should be stored in an environment variable
hmac_key = crypto.randomBytes(32);
var encrypt = function (plain_text) {
  var iv = new Buffer(crypto.randomBytes(16)); // ensure that the IV (initialization vector) is random
    var cipher_text;
    var hmac;
    var encryptor;
    encryptor = crypto.createCipheriv(algorithm, hash, iv);
    encryptor.setEncoding('hex');
    encryptor.write(plain_text);
    encryptor.end();
    cipher_text = encryptor.read();
    hmac = crypto.createHmac(hmac_algorithm, hmac_key);
    hmac.update(cipher_text);
    hmac.update(iv.toString('hex'));
    return cipher_text + "$" + iv.toString('hex') + "$" + hmac.digest('hex') 
};
  var encrypted =encrypt('123test');
  var wallet = {
        address:'motCmpWMeMC6BTRUtryxMATUBCvGorAjcs',
        enckey: encrypted, pass:hash,
        coins:0.20657791, utxos: []
  };
 var decrypt = function (cipher_text) {
    var cipher_blob = cipher_text.split("$");
    var ct = cipher_blob[0];
    var iv = new Buffer(cipher_blob[1], 'hex');
    var hmac = cipher_blob[2];
    var decryptor;
    chmac = crypto.createHmac(hmac_algorithm, hmac_key);
    chmac.update(ct);
    chmac.update(iv.toString('hex'));
    if (!constant_time_compare(chmac.digest('hex'), hmac)) {
        console.log("Encrypted Blob has been tampered with...");
        return null;
    }
    decryptor = crypto.createDecipheriv(algorithm,hash,iv);
    // decryptor.update(ct, 'hex', 'utf-8');
    var decryptedText = decryptor.update(ct,'hex','utf8');
    return decryptedText + decryptor.final('utf-8');
};
var constant_time_compare = function (val1, val2) {
    var sentinel;
    if (val1.length !== val2.length) {
        return false;
    }
    for (var i = 0; i <= (val1.length - 1); i++) {
        sentinel |= val1.charCodeAt(i) ^ val2.charCodeAt(i);
    }
    return sentinel === 0
};
  let decrypted=decrypt(encrypted);
  const key=bitcoin.ECPair.fromWIF('L1Eoyo3BN41AAxZE1wrJrHYNoxHZhNrtKtgTHVG1axiXJcs6TCkj',bitcoin.networks.testnet);
var unspn=blockexplorer.getUnspentOutputs(wallet.address); blockexplorer.getUnspentOutputs(wallet.address).then(result => {
wallet.utxos = result.unspent_outputs;
const sending =10000;  
const txb = new bitcoin.TransactionBuilder(bitcoin.networks.testnet);
 txb.setVersion(2);
var input = 0;
       for(let utx of wallet.utxos){
        txb.addInput(utx.tx_hash_big_endian,utx.tx_output_n);
        input += utx.value;
        if (input >= sending) break;
       }
const change1=17466476-sending;   
       const fee=1000; 
       console.log(change1);
     const change = input - (sending + fee);
       console.log(change);
       txb.addOutput('myQdZsy9wRd4A7deRBm88RZX9rv19NDGyB',sending);
       if(change) txb.addOutput('motCmpWMeMC6BTRUtryxMATUBCvGorAjcs',change);
       txb.sign(0,key);
       const raw = txb.build().toHex();

Thank you in advance.!

junderw commented 5 years ago
  1. Format, please.
  2. You're mixing up addresses.
  3. Where exactly is your problem? bitcoinjs-lib doesn't use promises, so it looks like your problem is not with bitcoinjs-lib. but you just pasted a huge blob of messy un-formatted code. No clue.

Please be more precise in your question.

Thanks.

anjalialance commented 5 years ago

Hi,

Thanks for the reply I am providing you the main code for transaction-

const bitcoin = require('bitcoinjs-lib')
const blockexplorer = require('blockchain.info/blockexplorer').usingNetwork(3)

const wif = 'cRboSi32o7hRLQ2VQMfSDc3SSBayMpxaPvpvPuiX65NXZMwLw1zT'
const key = bitcoin.ECPair.fromWIF(wif, bitcoin.networks.testnet)
const wallet = bitcoin.payments.p2pkh({
  pubkey: key.publicKey,
  network: bitcoin.networks.testnet
})
// wallet.address === motCmpWMeMC6BTRUtryxMATUBCvGorAjcs

blockexplorer.getUnspentOutputs(wallet.address).then(result => {
  wallet.utxos = result.unspent_outputs
  const sending = 10000
  console.log(sending)
  const txb = new bitcoin.TransactionBuilder(bitcoin.networks.testnet)
  txb.setVersion(2)
  var input = 0
  for (let utx of wallet.utxos) {
    txb.addInput(utx.tx_hash_big_endian, utx.tx_output_n)
    input += utx.value
    if (input >= sending) break
  }
  const change1 = 17466476 - sending
  const fee = 1000
  const change = input - (sending + fee)
  txb.addOutput('myQdZsy9wRd4A7deRBm88RZX9rv19NDGyB', sending)
  if (change) txb.addOutput('motCmpWMeMC6BTRUtryxMATUBCvGorAjcs', change)
  txb.sign(0, key)
  const raw = txb.build().toHex()
  console.log(raw)
})

This is the code of transaction

and the code for wallet creation is-

var keyPair = bitcoin.ECPair.makeRandom();
var testnet = bitcoin.networks.testnet;
var {address} = bitcoin.payments.p2pkh({pubkey : keyPair.publicKey, network: testnet});
var privateKey=keyPair.toWIF();
junderw commented 5 years ago

blockchain info API is broken.

Please ask them to fix it. (This issue looks related: https://github.com/blockchain/api-v1-client-node/issues/90 )

This is irrelevant to our library, so I will close it. Thanks.

anjalialance commented 5 years ago

Okay Thanks!