Skip to content

Instantly share code, notes, and snippets.

@st3b1t
Created July 25, 2023 00:29
Show Gist options
  • Save st3b1t/3e96196fe81ff0f295e7336dfd737b49 to your computer and use it in GitHub Desktop.
Save st3b1t/3e96196fe81ff0f295e7336dfd737b49 to your computer and use it in GitHub Desktop.
get amount of certain address in nodejs with bitcoinjs-lib
/*
Usage:
$ node electrum-client.js <servername>:<port> 3Eh99S957RnRrKmiU6DPAphwvjYB8UkeQb
Output:
address:3Eh99S957RnRrKmiU6DPAphwvjYB8UkeQb amount:0.0158 btc
*/
const net = require('net')
, bitcoin = require('bitcoinjs-lib');
const toScripthash = addr => {
const script = bitcoin.address.toOutputScript(addr)
, hash = bitcoin.crypto.sha256(script)
, reversedHash = Buffer.from(hash.reverse());
return reversedHash.toString('hex');
}
const [host, port] = process.argv[2].split(':')
, address = process.argv[3];
const client = new net.Socket();
client.on('data', chunk => {
const response = JSON.parse(chunk.toString())
, address = response.id
, amount = Number(response.result.confirmed)/100000000;
client.destroy();
console.log(`address:${address} amount:${amount} btc`);
})
.connect(Number(port), host, err => {
const scripthash = toScripthash(address)
, body = JSON.stringify({
jsonrpc: '2.0',
method: 'blockchain.scripthash.get_balance',
id: address,
params: [ scripthash ]
});
client.write(body +'\n');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment