Skip to content

Instantly share code, notes, and snippets.

@xhliu
Created May 15, 2024 22:52
Show Gist options
  • Save xhliu/44a73982e2d024cbe1af18e7b3b7da3b to your computer and use it in GitHub Desktop.
Save xhliu/44a73982e2d024cbe1af18e7b3b7da3b to your computer and use it in GitHub Desktop.
listen to mempool txs using zmq
extern crate zmq;
extern crate bitcoin;
use bitcoin::consensus::encode::deserialize;
use bitcoin::Transaction;
fn main() {
// Initialize a new ZeroMQ context
let context = zmq::Context::new();
// Create a subscriber socket
let subscriber = context.socket(zmq::SUB).expect("Failed to create subscriber socket");
// Connect to the ZMQ publisher
subscriber.connect("tcp://127.0.0.1:28332").expect("Failed to connect to the ZMQ publisher");
// Subscribe to the raw transaction topic
subscriber.set_subscribe(b"rawtx").expect("Failed to subscribe to the rawtx topic");
println!("Listening for raw transactions...");
// Infinite loop to continuously listen for new messages
loop {
// Receive the topic
let topic = subscriber.recv_string(0).expect("Failed to receive topic").unwrap();
// Ensure we are processing the correct topic
if topic != "rawtx" {
continue;
}
// Receive the message from the publisher
let msg = subscriber.recv_bytes(0).expect("Failed to receive message");
// Deserialize the raw transaction bytes
match deserialize::<Transaction>(&msg) {
Ok(tx) => {
// println!("Received raw transaction: {:#?}", tx);
// Print transaction details
print_transaction(&tx);
}
Err(e) => {
println!("Failed to deserialize transaction: {}", e);
}
}
}
}
fn print_transaction(tx: &Transaction) {
println!("Transaction ID: {}", tx.txid());
// println!("Version: {}", tx.version);
// println!("Lock Time: {}", tx.lock_time);
// println!("Inputs:");
// for input in &tx.input {
// println!(" Previous Output: {}", input.previous_output);
// println!(" Script Sig: {:?}", input.script_sig);
// println!(" Sequence: {}", input.sequence);
// }
// println!("Outputs:");
// for output in &tx.output {
// println!(" Value: {}", output.value);
// println!(" Script PubKey: {:?}", output.script_pubkey);
// }
}
@xhliu
Copy link
Author

xhliu commented May 15, 2024

Cargo.toml

[dependencies]
zmq = "0.9"
bitcoin = "0.28.0"

bitcoin.conf

zmqpubrawtx=tcp://127.0.0.1:28332

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment