Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional revalidation of hash/txid for unspent balances #8

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ DESTINATION_ADDR=
NETWORK=
DERIVATION_PATH=
N=
BLOCKCYPHER_API_KEY=
BLOCKCYPHER_API_KEY=
ASSERT_UNSPENT_TRANSACTION_HASH_CONFIRMATION_IS_VALID=False
24 changes: 20 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ const privkey2 = process.env.PRIVATE_KEY2;
const toAddr = process.env.DESTINATION_ADDR;
const network = process.env.NETWORK;
const derivationPath = process.env.DERIVATION_PATH;
const ASSERT_UNSPENT_TRANSACTION_HASH_CONFIRMATION_IS_VALID =
`${process.env.ASSERT_UNSPENT_TRANSACTION_HASH_CONFIRMATION_IS_VALID}`.toUpperCase() ==
"TRUE";

console.log({ n });

Expand All @@ -19,15 +22,28 @@ if (!n || !bip32 || !privkey2 || !toAddr || !network || !derivationPath) {

let sweep;

if (network == constants.NETWORKS.BTC || network == constants.NETWORKS.BTCTEST) {
sweep = new Sweeper(network, bip32, privkey2, toAddr, n, derivationPath);
if (
network == constants.NETWORKS.BTC ||
network == constants.NETWORKS.BTCTEST
) {
sweep = new Sweeper(network, bip32, privkey2, toAddr, n, derivationPath, {
revalidate_txhash_status:
ASSERT_UNSPENT_TRANSACTION_HASH_CONFIRMATION_IS_VALID,
});
} else {
/** ASSERTS THAT BLOCKCYPHER API KEY/TOKEN IS AVAILABLE */
if (!process.env.BLOCKCYPHER_API_KEY) {
console.error("Consider adding 'BLOCKCYPHER_API_KEY' to your .env file. visit: https://accounts.blockcypher.com/signup");
console.error(
"Consider adding 'BLOCKCYPHER_API_KEY' to your .env file. visit: https://accounts.blockcypher.com/signup"
);
process.exit(0);
}
sweep = new Sweeper(network, bip32, privkey2, toAddr, n, derivationPath, { provider: constants.PROVIDERS.BLOCKCYPHER, key: process.env.BLOCKCYPHER_API_KEY });
sweep = new Sweeper(network, bip32, privkey2, toAddr, n, derivationPath, {
provider: constants.PROVIDERS.BLOCKCYPHER,
key: process.env.BLOCKCYPHER_API_KEY,
revalidate_txhash_status:
ASSERT_UNSPENT_TRANSACTION_HASH_CONFIRMATION_IS_VALID,
});
}

Sweep();
Expand Down
164 changes: 148 additions & 16 deletions src/services/ProviderService.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ const constants = require("../constants");
const fetch = require("node-fetch");
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const ProviderService = function (provider, network, apiKey = null) {
const ProviderService = function (
provider,
network,
apiKey = null,
revalidate_txhash_status = false
) {
const providerIndex = Object.values(constants.PROVIDERS).indexOf(provider);
if (providerIndex < 0) {
throw new Error("Blockchain provider not supported");
Expand All @@ -14,13 +19,19 @@ const ProviderService = function (provider, network, apiKey = null) {
this.network = network;
this.provider = provider;
this.apiKey = apiKey;
this.revalidate_txhash_status = revalidate_txhash_status;
};

ProviderService.prototype.getTxHex = async function (txId) {
try {
switch (this.provider) {
case constants.PROVIDERS.SOCHAIN: {
const apiUrl = [constants.PROVIDER_URLS.SOCHAIN.URL, "get_tx", this.network, txId].join("/");
const apiUrl = [
constants.PROVIDER_URLS.SOCHAIN.URL,
"get_tx",
this.network,
txId,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (json.status === "fail") {
Expand All @@ -29,8 +40,15 @@ ProviderService.prototype.getTxHex = async function (txId) {
return json.data.tx_hex;
}
case constants.PROVIDERS.MEMPOOLSPACE: {
const networkType = this.network === constants.NETWORKS.BTC ? "api" : "testnet/api";
const apiUrl = [constants.PROVIDER_URLS.MEMPOOLSPACE.URL, networkType, "tx", txId, "hex"].join("/");
const networkType =
this.network === constants.NETWORKS.BTC ? "api" : "testnet/api";
const apiUrl = [
constants.PROVIDER_URLS.MEMPOOLSPACE.URL,
networkType,
"tx",
txId,
"hex",
].join("/");
const res = await fetchUrl(apiUrl);
const hex = await res.text();
if (res.status !== 200) {
Expand All @@ -39,7 +57,12 @@ ProviderService.prototype.getTxHex = async function (txId) {
return hex;
}
case constants.PROVIDERS.BLOCKCHAINCOM: {
const apiUrl = [constants.PROVIDER_URLS.BLOCKCHAINCOM.URL, "rawtx", txId, "?format=hex"].join("/");
const apiUrl = [
constants.PROVIDER_URLS.BLOCKCHAINCOM.URL,
"rawtx",
txId,
"?format=hex",
].join("/");
const res = await fetchUrl(apiUrl);
const hex = await res.text();
if (res.status !== 200) {
Expand All @@ -49,7 +72,13 @@ ProviderService.prototype.getTxHex = async function (txId) {
}

case constants.PROVIDERS.BLOCKCYPHER: {
const apiUrl = [constants.PROVIDER_URLS.BLOCKCYPHER.URL, this.network.toLowerCase(), "main/txs", txId, `?includeHex=true&token=${this.apiKey}`].join("/");
const apiUrl = [
constants.PROVIDER_URLS.BLOCKCYPHER.URL,
this.network.toLowerCase(),
"main/txs",
txId,
`?includeHex=true&token=${this.apiKey}`,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (!json.hex) {
Expand All @@ -71,7 +100,12 @@ ProviderService.prototype.getUtxo = async function (addr) {
try {
switch (this.provider) {
case constants.PROVIDERS.SOCHAIN: {
const apiUrl = [constants.PROVIDER_URLS.SOCHAIN.URL, "get_tx_unspent", this.network, addr].join("/");
const apiUrl = [
constants.PROVIDER_URLS.SOCHAIN.URL,
"get_tx_unspent",
this.network,
addr,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (json.status === "fail") {
Expand All @@ -80,7 +114,10 @@ ProviderService.prototype.getUtxo = async function (addr) {
return json.data.txs;
}
case constants.PROVIDERS.BLOCKCHAINCOM: {
const apiUrl = [constants.PROVIDER_URLS.BLOCKCHAINCOM.URL, "unspent?active=" + addr].join("/");
const apiUrl = [
constants.PROVIDER_URLS.BLOCKCHAINCOM.URL,
"unspent?active=" + addr,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (json.error) {
Expand All @@ -89,9 +126,12 @@ ProviderService.prototype.getUtxo = async function (addr) {
return json.unspent_outputs;
}
case constants.PROVIDERS.BLOCKCYPHER: {
const apiUrl = [constants.PROVIDER_URLS.BLOCKCYPHER.URL, this.network.toLowerCase(), "main/addrs", addr + `?unspentOnly=true&includeScript=true&token=${this.apiKey}`].join(
"/"
);
const apiUrl = [
constants.PROVIDER_URLS.BLOCKCYPHER.URL,
this.network.toLowerCase(),
"main/addrs",
addr + `?unspentOnly=true&includeScript=true&token=${this.apiKey}`,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (json.error) {
Expand All @@ -108,19 +148,100 @@ ProviderService.prototype.getUtxo = async function (addr) {
}
};

ProviderService.prototype.getTransactionComfirmationStatus = async function (
txHash
) {
const MINIMUM_CONFIRMATIONS_REQUIRED = 3;
try {
switch (this.provider) {
case constants.PROVIDERS.BLOCKCHAINCOM: {
const apiUrl = [
constants.PROVIDER_URLS.BLOCKCHAINCOM.URL,
"rawtx",
txHash,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (json.error) {
throw new Error(json.message);
}
return json.block_height && json.block_index
? { confirmations: MINIMUM_CONFIRMATIONS_REQUIRED }
: { confirmations: 0 };
}

case constants.PROVIDERS.MEMPOOLSPACE: {
const apiUrl = [
constants.PROVIDER_URLS.MEMPOOLSPACE.URL,
"api/tx",
txHash,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (json.error) {
throw new Error(json.message);
}
return json?.status.confirmed &&
json?.status.block_height &&
json?.status.block_hash
? { confirmations: MINIMUM_CONFIRMATIONS_REQUIRED }
: { confirmations: 0 };
}
case constants.PROVIDERS.BLOCKCYPHER: {
const apiUrl = [
constants.PROVIDER_URLS.BLOCKCYPHER.URL,
this.network.toLowerCase(),
"main/txs",
txHash + `?token=${this.apiKey}`,
].join("/");
const res = await fetchUrl(apiUrl);
const json = await res.json();
if (json.error) {
throw new Error(json.message);
}
return json.confirmations
? { confirmations: json.confirmations }
: { confirmations: 0 };
}
default: {
throw new Error(
"Error getting transaction status with provider: " + this.provider
);
}
}
} catch (err) {
throw new Error(err);
}
};

ProviderService.prototype.sendTx = async function (txHex) {
try {
switch (this.provider) {
case constants.PROVIDERS.SOCHAIN: {
const apiUrl = [constants.PROVIDER_URLS.SOCHAIN.URL, "send_tx", this.network].join("/");
const apiUrl = [
constants.PROVIDER_URLS.SOCHAIN.URL,
"send_tx",
this.network,
].join("/");
await broadcastTx(apiUrl, this.network.toLowerCase(), txHex);
return;
}

case constants.PROVIDERS.BLOCKCHAINCOM:
case constants.PROVIDERS.BLOCKCYPHER: {
const apiUrl = [constants.PROVIDER_URLS.BLOCKCYPHER.URL, this.network.toLowerCase(), "main", "txs", `push?token=${this.apiKey}`].join("/");
await broadcastTx(apiUrl, this.network.toLowerCase(), txHex, this.apiKey);
const apiUrl = [
constants.PROVIDER_URLS.BLOCKCYPHER.URL,
this.network.toLowerCase(),
"main",
"txs",
`push?token=${this.apiKey}`,
].join("/");
await broadcastTx(
apiUrl,
this.network.toLowerCase(),
txHex,
this.apiKey
);
return;
}
default: {
Expand All @@ -140,7 +261,9 @@ async function fetchUrl(url) {
if (response.ok) {
return response;
} else {
console.log(" -- retrying in 10 seconds due to status = " + response.status);
console.log(
" -- retrying in 10 seconds due to status = " + response.status
);
await delay(10000);
return await fetchUrl(url);
}
Expand All @@ -152,7 +275,16 @@ async function fetchUrl(url) {
async function broadcastTx(apiUrl, network, txHex, apiKey = null) {
try {
let res;
if (apiUrl == [constants.PROVIDER_URLS.BLOCKCYPHER.URL, network, "main", "txs", `push?token=${apiKey}`].join("/")) {
if (
apiUrl ==
[
constants.PROVIDER_URLS.BLOCKCYPHER.URL,
network,
"main",
"txs",
`push?token=${apiKey}`,
].join("/")
) {
res = await fetch(apiUrl, {
method: "POST",
body: JSON.stringify({ tx: txHex }),
Expand Down
Loading