Created
May 15, 2024 22:52
-
-
Save xhliu/44a73982e2d024cbe1af18e7b3b7da3b to your computer and use it in GitHub Desktop.
listen to mempool txs using zmq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cargo.toml
bitcoin.conf