bsv-p2p

Communicate on the Bitcoin P2P network with minimal overhead or dependencies
Built to follow the protocol definition here: https://en.bitcoin.it/wiki/Protocol_documentation
Methods
npm i bsv-p2p
Docs
Basic use
const BitcoinP2P = require("bsv-p2p").default;
const node = "95.217.42.32";
const ticker = "BSV";
const peer = new BitcoinP2P({ node, ticker });
const fs = require("fs");
const path = require("path");
let writeStream;
let writeDir;
peer.on("block_chunk", ({ node, chunk, blockHash, finished, started, num }) => {
if (started) {
writeDir = path.join(__dirname, `${blockHash.toString("hex")}.bin`);
writeStream = fs.createWriteStream(`${writeDir}.tmp`);
}
writeStream.write(chunk);
if (finished) {
writeStream.end();
writeStream = null;
fs.renameSync(`${writeDir}.tmp`, writeDir);
}
});
peer.on("transactions", ({ node, header, finished, transactions }) => {
for (const [index, transaction] of transactions) {
if (header) {
console.log(
`tx ${transaction
.getHash()
.toString("hex")} in index ${index} of block ${header
.getHash()
.toString("hex")}`
);
} else {
console.log(
`tx ${transaction.getHash().toString("hex")} seen in mempool`
);
}
}
});
await peer.connect();
await peer.getBlock("<block hash>");
peer.fetchMempoolTxs((txids) => txids);
peer.fetchNewBlocks((hashes) => hashes);
Other methods
const BitcoinP2P = require("bsv-p2p").default;
const node = "95.217.42.32";
const port = 8333;
const ticker = "BSV";
const segwit = false;
const validate = true;
const autoReconnect = true;
const disableExtmsg = false;
const mempoolTxs = true;
const DEBUG_LOG = false;
const peer = new BitcoinP2P({
node,
port,
ticker,
segwit,
validate,
autoReconnect,
disableExtmsg,
mempoolTxs,
DEBUG_LOG,
});
peer.on("addr", ({ addrs }) => {
for (const addr of addrs) {
console.log(addr);
}
});
peer.on("block_hashes", ({ hashes }) => {
for (const hash of hashes) {
console.log(`New block ${hash.toString("hex")} from ${node}`);
}
});
peer.on("block_chunk", ({ chunk, blockHash, finished, started, num }) => {
});
peer.on("block", ({ blockHash }) => {
});
peer.on("tx_mempool", ({ tx }) => {
});
peer.on(
"tx_block",
({
blockHash,
header,
started,
finished,
height,
blockSize,
txCount,
txs,
}) => {
}
);
peer.on("disconnected", ({ disconnects }) => {
});
peer.on("connected", () => {
});
peer.on("version", ({ version }) => {
});
peer.on("message", ({ command, payload }) => {
});
peer.on("error_message", ({ error }) => {
});
peer.on("error_socket", ({ error }) => {
});
await peer.connect();
await peer.getHeaders({ from: ["<hex header>"], to: "<stop hash>" });
peer.getMempool();
await peer.ping();
await peer.getAddr();
await peer.getBlock("<block hash>");
await peer.broadcastTx("<tx buffer>");
peer.getTxs(["<txid>..."]);
peer.fetchMempoolTxs((txids) => txids);
peer.fetchNewBlocks((hashes) => hashes);
peer.disconnect();
Tests
npm run test