How to use the bitcoinjs-lib.Transaction function in bitcoinjs-lib

To help you get started, we’ve selected a few bitcoinjs-lib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github blockstack / blockstack.js / tests / unitTests / src / unitTestsOperations.js View on Github external
.then(([estimatedCost, hexTX]) => {
        const tx = btc.Transaction.fromHex(hexTX)
        const txLen = hexTX.length / 2
        const outputVals = sumOutputValues(tx)
        const inputVals = getInputVals(tx)
        const fee = inputVals - outputVals

        // change address is the 3rd output usually...
        const change = tx.outs[2].value

        t.equal(btc.address.fromOutputScript(tx.outs[2].script), testAddresses[1].address,
                'Payer change should be third output')
        t.equal(inputVals - change, estimatedCost, 'Estimated cost should match actual.')
        t.equal(tx.ins.length, 2, 'Should use both payer utxos')
        t.equal(Math.floor(fee / txLen), 1000,
                `Paid fee of ${fee} for tx of length ${txLen} should equal 1k satoshi/byte`)
      })
      .catch((err) => { console.log(err.stack); throw err })
github Colored-Coins / coloredcoinsd / coluutils.js View on Github external
coluutils.createSendAssetTansaction = function createSendAssetTansaction (metadata) {
        var deferred = Q.defer();

        tx = new bitcoinjs.Transaction();
        // find inputs to cover the issuence
        addInputsForSendTransaction(tx, metadata).
        then(validateFees).
        then(function(data){
            console.log(data.tx)
            deferred.resolve(data);
        }).
        catch(function(err) {
          console.log(err)
          deferred.reject(err);
        });
          

        return deferred.promise;
    }
github blockstack / stacks-wallet / app / common / lib / transactions.js View on Github external
const broadcastTransaction = async rawTx => {
  try {
    // return Promise.resolve("txHash");
    const response = await postTransaction(rawTx);
    const text = await response.text();
    const success = text.toLowerCase().indexOf("transaction submitted") >= 0;
    if (success) {
      // generate tx hash
      return btc.Transaction.fromHex(rawTx)
        .getHash()
        .reverse()
        .toString("hex"); // big_endian
    } else {
      await Promise.reject(
        `Broadcast transaction failed with message: ${text}`
      );
    }
  } catch (e) {
    console.log(e);
    throw new Error(e.message);
  }
};
github oipwg / oip-hdmw / src / TransactionBuilderHelpers.js View on Github external
var txTmp = transaction.clone()

  // SIGHASH_NONE: ignore all outputs? (wildcard payee)
  if ((hashType & 0x1f) === bitcoin.Transaction.SIGHASH_NONE) {
    txTmp.outs = []

    // ignore sequence numbers (except at inIndex)
    txTmp.ins.forEach(function (input, i) {
      if (i === inIndex) return

      input.sequence = 0
    })

  // SIGHASH_SINGLE: ignore all outputs, except at the same index?
  } else if ((hashType & 0x1f) === bitcoin.Transaction.SIGHASH_SINGLE) {
    // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
    if (inIndex >= transaction.outs.length) { return ONE }

    // truncate outputs after
    txTmp.outs.length = inIndex + 1

    // "blank" outputs before
    for (var i = 0; i < inIndex; i++) {
      txTmp.outs[i] = BLANK_OUTPUT
    }

    // ignore sequence numbers (except at inIndex)
    txTmp.ins.forEach(function (input, y) {
      if (y === inIndex) return

      input.sequence = 0
github oipwg / oip-hdmw / src / TransactionBuilderHelpers.js View on Github external
function hashForSignature (transaction, extraBytes, inIndex, prevOutScript, hashType) {
  // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
  if (inIndex >= transaction.ins.length) { return ONE }

  // ignore OP_CODESEPARATOR
  var ourScript = bitcoin.script.compile(bitcoin.script.decompile(prevOutScript).filter(function (x) {
    return x !== 171 // OP_CODESEPARATOR
  }))

  var txTmp = transaction.clone()

  // SIGHASH_NONE: ignore all outputs? (wildcard payee)
  if ((hashType & 0x1f) === bitcoin.Transaction.SIGHASH_NONE) {
    txTmp.outs = []

    // ignore sequence numbers (except at inIndex)
    txTmp.ins.forEach(function (input, i) {
      if (i === inIndex) return

      input.sequence = 0
    })

  // SIGHASH_SINGLE: ignore all outputs, except at the same index?
  } else if ((hashType & 0x1f) === bitcoin.Transaction.SIGHASH_SINGLE) {
    // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
    if (inIndex >= transaction.outs.length) { return ONE }

    // truncate outputs after
    txTmp.outs.length = inIndex + 1
github Colored-Coins / coloredcoinsd / coluutils.js View on Github external
coluutils.createIssueTransaction = function createIssueTransaction (metadata) {
        var deferred = Q.defer();
        metadata.divisibility = metadata.divisibility || 0
        metadata.aggregationPolicy = metadata.aggregationPolicy || 'aggregatable'

        tx = new bitcoinjs.Transaction();
        // find inputs to cover the issuence
        addInputsForIssueTransaction(tx, metadata).
        then(function(args){
            var txResponse = encodeColorScheme(args);
            deferred.resolve({txHex: txResponse.tx.toHex(), assetId: args.assetId || "0", metadata: metadata, multisigOutputs: txResponse.multisigOutputs, coloredOutputIndexes: txResponse.coloredOutputIndexes});
        }).
        catch(function(err) {
            deferred.reject(err);
        });
          

        return deferred.promise;
    }
github alexbosworth / ln-service / test / chain / test_subscribe_to_chain_address.js View on Github external
const sub = subscribeToChainAddress(args);

    sub.on('confirmation', ({block, height, transaction}) => {
      equal(block, expected.block, 'Got block');
      equal(height, expected.height, 'Got height');
      equal(transaction, expected.transaction, 'Got transaction');

      return end();
    });

    emitter.emit('data', {
      conf: {
        block_hash: Buffer.alloc(32),
        block_height: 200,
        raw_tx: (new Transaction()).toBuffer(),
      },
    });

    return;
  });
});
github blockstack / stacks-wallet / blockstack-ledger / LedgerSigner.js View on Github external
.then((transaction) => {
          const hasWitness = btc.Transaction.fromHex(transaction).hasWitnesses()
          return appBtc.splitTransaction(transaction, hasWitness)
        })
        .then((preparedTx) => ([ preparedTx, outputN, undefined, input.sequence ]))
github liquality / chainabstractionlayer / src / providers / bitcoin / BitcoinJsLibSwapProvider.js View on Github external
spendSwap (address, wallet, secret, isRedeem, txfee, vout, network, expiration) {
    network = network || bitcoin.networks.bitcoin
    const hashType = bitcoin.Transaction.SIGHASH_ALL

    const txb = new bitcoin.TransactionBuilder(network)

    if (!isRedeem) txb.setLockTime(expiration)

    txb.addInput(vout.txid, vout.n, 0)
    txb.addOutput(address, vout.vSat - txfee)

    const txRaw = txb.buildIncomplete()
    const sigHash = txRaw.hashForSignature(0, vout.script, hashType)

    const redeemScriptSig = bitcoin.script.swap.input.encode(
      wallet.sign(sigHash).toScriptSignature(hashType),
      wallet.getPublicKeyBuffer(),
      isRedeem,
      isRedeem ? Buffer.from(secret, 'hex') : undefined