Skip to content

Instantly share code, notes, and snippets.

@melvincarvalho
Created April 27, 2023 08:16
Show Gist options
  • Save melvincarvalho/70c29313554ce9d1a22ce9bf954909d9 to your computer and use it in GitHub Desktop.
Save melvincarvalho/70c29313554ce9d1a22ce9bf954909d9 to your computer and use it in GitHub Desktop.
nostr-tx-broadcast.js
const WebSocket = require('ws');
const bitcoin = require('bitcoinjs-lib');
const fetch = require('node-fetch');
const base64 = require('base64-js');
const relays = [
'wss://nostr.wine',
'wss://nos.lol',
'wss://nostr.fmt.wiz.biz',
'wss://nostr.zebedee.cloud',
'wss://relay.damus.io',
];
const bitcoinTxKind = 28333;
async function main() {
const sockets = [];
for (const relay of relays) {
const socket = new WebSocket(relay);
socket.on('open', () => {
const subscribeMessage = {
id: 1,
method: 'sub',
params: {
filter: {
kind: [bitcoinTxKind],
},
},
};
socket.send(JSON.stringify(subscribeMessage));
});
socket.on('message', async (data) => {
const message = JSON.parse(data);
if (message.method === 'event' && message.params.kind === bitcoinTxKind) {
const decoded = base64.toByteArray(message.params.content);
const transaction = bitcoin.Transaction.fromBuffer(decoded);
await broadcastTx(transaction);
}
});
sockets.push(socket);
}
console.log('Listening for bitcoin txs...');
}
async function broadcastTx(tx) {
const hexTx = tx.toHex();
const response = await fetch('https://mempool.space/api/tx', {
method: 'POST',
body: hexTx,
});
if (response.ok) {
console.log(`Broadcasted tx: ${tx.getId()}`);
} else {
console.error(`Error broadcasting tx: ${tx.getId()}, status: ${response.status}`);
}
}
main().catch((error) => {
console.error('An error occurred:', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment