From 87f0260fe482fbbb2e3a2e891bc5bdc2ad000194 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 18 Oct 2022 04:43:53 +0530 Subject: [PATCH] btcOperator v1.0.11 - Added createSignedTx: creates a signed tx (same as sendTx, but doesnt broadcast) - Added transactionID: returns the txid of the tx_hex (or tx-object) --- btcOperator.js | 29 +++++++++++++++++++++++------ index.html | 1 + 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 9fc39d2..ce8b09d 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.10b +(function (EXPORTS) { //btcOperator v1.0.11 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -39,7 +39,7 @@ "tx_hex": rawTxHex }, dataType: "json", - error: e => reject(e.responseJSON), + error: e => reject((e.responseJSON && e.responseJSON.status === "fail") ? null : e.responseJSON), success: r => r.status === "success" ? resolve(r.data.txid) : reject(r) }) }); @@ -451,6 +451,17 @@ */ btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) { + return new Promise((resolve, reject) => { + createSignedTx(senders, privkeys, receivers, amounts, fee, change_addr).then(result => { + debugger; + broadcastTx(result.transaction.serialize()) + .then(txid => resolve(txid)) + .catch(error => reject(error)); + }).catch(error => reject(error)) + }) + } + + const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) { return new Promise((resolve, reject) => { try { ({ @@ -484,10 +495,7 @@ console.debug("Unsigned:", tx.serialize()); new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/))); //Sign the tx using private key WIF console.debug("Signed:", tx.serialize()); - debugger; - broadcastTx(tx.serialize()) - .then(txid => resolve(txid)) - .catch(error => reject(error)); + resolve(result); }).catch(error => reject(error)); }) } @@ -664,6 +672,15 @@ }) } + btcOperator.transactionID = function (tx) { + tx = deserializeTx(tx); + let clone = coinjs.clone(tx); + clone.witness = null; + let raw_bytes = Crypto.util.hexToBytes(clone.serialize()); + let txid = Crypto.SHA256(Crypto.SHA256(raw_bytes, { asBytes: true }), { asBytes: true }).reverse(); + return Crypto.util.bytesToHex(txid); + } + btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`tx/BTC/${txid}`) .then(result => resolve(result.data)) diff --git a/index.html b/index.html index 2b60d9d..7ec9496 100644 --- a/index.html +++ b/index.html @@ -13,6 +13,7 @@ +