Skip to content

Instantly share code, notes, and snippets.

@pinheadmz
Last active March 8, 2022 04:07
Show Gist options
  • Save pinheadmz/39132338d2be36b5d5e6cd477cd38372 to your computer and use it in GitHub Desktop.
Save pinheadmz/39132338d2be36b5d5e6cd477cd38372 to your computer and use it in GitHub Desktop.
// USAGE: hsd --log-console=false --plugins=/path/to/this/file/addr-bal.js
'use strict';
const {CoinEntry} = require('hsd');
const layout = require('hsd/lib/blockchain/layout');
const plugin = exports;
class Plugin {
constructor(node) {
this.chain = node.chain;
this.db = node.chain.db.db;
this.chain.once('tip', async (entry) => {
await this.run(entry.height);
});
this.map = new Map();
this.totalCoins = 0;
}
async run(height) {
const start = Date.now();
const iter = this.db.iterator({
gte: layout.c.min(),
lte: layout.c.max(),
values: true
});
await iter.each((key, value) => {
const {output} = CoinEntry.decode(value);
const {address, value: amount, covenant} = output;
const addr = address.toString('main');
// Ignore 0-value UTXO (OPENs, mostly)
if (amount === 0)
return;
// Ignore covenants that lock coins like REGISTER (unspendable)
if (covenant.isNonspendable())
return;
this.totalCoins++;
if (!this.map.get(addr))
this.map.set(addr, amount);
else
this.map.set(addr, this.map.get(addr) + amount);
console.log(this.map.size);
});
const sorted = new Map([...this.map.entries()].sort((a, b) => a[1] - b[1]));
console.log(sorted);
console.log('DONE');
console.log(`elapsed: ${Date.now() - start}`);
console.log(`Addresses: ${this.map.size}`);
console.log(`UTXO: ${this.totalCoins}`);
}
}
plugin.id = 'addr-bal';
plugin.init = function init(node) {
return new Plugin(node);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment