Skip to content

Commit

Permalink
Answer the peer's transaction request
Browse files Browse the repository at this point in the history
  • Loading branch information
liuchengxu committed Aug 4, 2024
1 parent a630594 commit fe623cf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
17 changes: 12 additions & 5 deletions crates/subcoin-network/src/transaction_manager.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::PeerId;
use bitcoin::consensus::deserialize;
use bitcoin::p2p::message::NetworkMessage;
use bitcoin::p2p::message_blockdata::Inventory;
use bitcoin::{Transaction, Txid};
use indexmap::map::Entry;
use indexmap::IndexMap;
Expand Down Expand Up @@ -40,14 +38,17 @@ impl TransactionManager {
}
}

/// Broadcast known transaction IDs to the connected peers.
///
/// If the timeout period has passed for a transaction ID, it is broadcasted again.
/// If the transaction has not been broadcasted, the transaction ID is broadcasted.
pub fn on_tick<'a>(
&mut self,
peers: impl Iterator<Item = &'a PeerId>,
connected_peers: impl Iterator<Item = &'a PeerId>,
) -> Vec<(PeerId, Vec<Txid>)> {
// Remove timeout transactions.

// Broadcast transactions to peers.
peers
connected_peers
.filter_map(|address| {
let mut to_advertise = vec![];

Expand All @@ -67,6 +68,12 @@ impl TransactionManager {
.collect()
}

pub fn get_transaction(&self, txid: &Txid) -> Option<Transaction> {
self.transactions
.get(txid)
.map(|tx_info| tx_info.transaction.clone())
}

pub fn add_transaction(&mut self, raw_tx: &[u8]) {
if let Ok(transaction) = deserialize::<Transaction>(raw_tx) {
let txid = transaction.compute_txid();
Expand Down
11 changes: 10 additions & 1 deletion crates/subcoin-network/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,16 @@ where
return Ok(SyncAction::Disconnect(from, Error::TooManyInventoryItems));
}

// TODO: handle getdata tx
// Send transactions to the requesting node.
inv.iter().for_each(|inv| {
if let Inventory::Transaction(txid) = inv {
if let Some(transaction) = self.transaction_manager.get_transaction(&txid) {
if let Err(err) = self.send(from, NetworkMessage::Tx(transaction)) {
tracing::error!(?err, "Failed to send transaction {txid}");
}
}
}
});

Ok(self.chain_sync.on_inv(inv, from))
}
Expand Down

0 comments on commit fe623cf

Please sign in to comment.