zebrad/components/sync/gossip.rs
1//! A task that gossips newly verified [`block::Hash`]es to peers.
2//!
3//! [`block::Hash`]: zebra_chain::block::Hash
4
5use std::time::Duration;
6
7use futures::TryFutureExt;
8use thiserror::Error;
9use tokio::sync::{mpsc, watch};
10use tower::{timeout::Timeout, Service, ServiceExt};
11use tracing::Instrument;
12
13use zebra_chain::{block, chain_tip::ChainTip};
14use zebra_network as zn;
15use zebra_state::ChainTipChange;
16
17use crate::{
18 components::sync::{SyncStatus, TIPS_RESPONSE_TIMEOUT},
19 BoxError,
20};
21
22use BlockGossipError::*;
23
24/// Errors that can occur when gossiping committed blocks
25#[derive(Error, Debug)]
26pub enum BlockGossipError {
27 #[error("chain tip sender was dropped")]
28 TipChange(watch::error::RecvError),
29
30 #[error("sync status sender was dropped")]
31 SyncStatus(watch::error::RecvError),
32
33 #[error("permanent peer set failure")]
34 PeerSetReadiness(zn::BoxError),
35}
36
37/// Run continuously, gossiping newly verified [`block::Hash`]es to peers.
38///
39/// Once the state has reached the chain tip, broadcast the [`block::Hash`]es
40/// of newly verified blocks to eligible connected peers, including busy peers.
41///
42/// Blocks are only gossiped if they are:
43/// - on the best chain, and
44/// - the most recent block verified since the last gossip.
45///
46/// In particular, if a lot of blocks are committed at the same time,
47/// gossips will be disabled or skipped until the state reaches the latest tip.
48///
49/// [`block::Hash`]: zebra_chain::block::Hash
50pub async fn gossip_best_tip_block_hashes<ZN>(
51 sync_status: SyncStatus,
52 mut chain_state: ChainTipChange,
53 broadcast_network: ZN,
54 mut mined_block_receiver: Option<mpsc::Receiver<(block::Hash, block::Height)>>,
55) -> Result<(), BlockGossipError>
56where
57 ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
58 ZN::Future: Send,
59{
60 info!("initializing block gossip task");
61
62 // use the same timeout as tips requests,
63 // so broadcasts don't delay the syncer too long
64 let mut broadcast_network = Timeout::new(broadcast_network, TIPS_RESPONSE_TIMEOUT);
65
66 loop {
67 // TODO: Refactor this into a struct and move the contents of this loop into its own method.
68 let mut sync_status = sync_status.clone();
69 let mut chain_tip = chain_state.clone();
70
71 // TODO: Move the contents of this async block to its own method
72 let tip_change_close_to_network_tip_fut = async move {
73 /// A brief duration to wait after a tip change for a new message in the mined block channel.
74 // TODO: Add a test to check that Zebra does not advertise mined blocks to peers twice.
75 const WAIT_FOR_BLOCK_SUBMISSION_DELAY: Duration = Duration::from_micros(100);
76
77 // wait for at least one tip change, to make sure we have a new block hash to broadcast
78 let tip_action = chain_tip.wait_for_tip_change().await.map_err(TipChange)?;
79
80 // wait for block submissions to be received through the `mined_block_receiver` if the tip
81 // change is from a block submission.
82 tokio::time::sleep(WAIT_FOR_BLOCK_SUBMISSION_DELAY).await;
83
84 // wait until we're close to the tip, because broadcasts are only useful for nodes near the tip
85 // (if they're a long way from the tip, they use the syncer and block locators), unless a mined block
86 // hash is received before `wait_until_close_to_tip()` is ready.
87 sync_status
88 .wait_until_close_to_tip()
89 .map_err(SyncStatus)
90 .await?;
91
92 // get the latest tip change when close to tip - it might be different to the change we awaited,
93 // because the syncer might take a long time to reach the tip
94 let best_tip = chain_tip
95 .last_tip_change()
96 .unwrap_or(tip_action)
97 .best_tip_hash_and_height();
98
99 Ok((best_tip, "sending committed block broadcast", chain_tip))
100 }
101 .in_current_span();
102
103 // TODO: Move this logic for selecting the first ready future and updating `chain_state` to its own method.
104 let (((mut hash, mut height), log_msg, updated_chain_state), mut is_block_submission) =
105 if let Some(mined_block_receiver) = mined_block_receiver.as_mut() {
106 tokio::select! {
107 tip_change_close_to_network_tip = tip_change_close_to_network_tip_fut => {
108 (tip_change_close_to_network_tip?, false)
109 },
110
111 Some(tip_change) = mined_block_receiver.recv() => {
112 ((tip_change, "sending mined block broadcast", chain_state), true)
113 }
114 }
115 } else {
116 (tip_change_close_to_network_tip_fut.await?, false)
117 };
118
119 chain_state = updated_chain_state;
120 let mut accepted_at = tokio::time::Instant::now();
121
122 // TODO: Move logic for calling the peer set to its own method.
123
124 info!(?height, ?hash, is_block_submission, log_msg);
125
126 // `tower::timeout::Timeout` only bounds the response future, not `poll_ready()`.
127 // If there are no eligible peers, only waiting for readiness would stop this task from
128 // consuming the mined block channel, and `submitblock` would eventually fail with a full
129 // channel even though the block was committed.
130 //
131 // So we keep receiving mined blocks while we wait, and only broadcast the latest one.
132 // The pending broadcast is kept until an eligible peer connects, even if it is busy with
133 // an ordinary request.
134 //
135 // A chain tip broadcast that is replaced by a mined block is sent after the mined block,
136 // unless the mined block is the new best tip. Mined blocks can be on side chains, and the
137 // tip change for the replaced broadcast has already been consumed from `chain_state`.
138 let mut displaced_tip = None;
139
140 loop {
141 let mut superseded_blocks: usize = 0;
142 let ready_result = loop {
143 tokio::select! {
144 biased;
145
146 // Dropping an unfinished `Ready` future doesn't affect the service's
147 // readiness, and we call the service straight after it becomes ready.
148 ready_result = broadcast_network.ready() => break ready_result.map(|_| ()),
149
150 Some(mined_block) = recv_mined_block(&mut mined_block_receiver) => {
151 if is_block_submission {
152 superseded_blocks = superseded_blocks.saturating_add(1);
153 } else {
154 displaced_tip = Some((hash, height));
155 }
156
157 (hash, height) = mined_block;
158 is_block_submission = true;
159 accepted_at = tokio::time::Instant::now();
160 }
161 }
162 };
163
164 ready_result.map_err(PeerSetReadiness)?;
165
166 if superseded_blocks > 0 {
167 info!(
168 ?height,
169 ?hash,
170 superseded_blocks,
171 "peers were not ready for block broadcasts, only sending the latest mined block",
172 );
173 }
174
175 // block broadcasts inform other nodes about new blocks,
176 // so our internal Grow or Reset state doesn't matter to them
177 let request = if is_block_submission {
178 zn::Request::AdvertiseBlockToAll(hash)
179 } else {
180 zn::Request::AdvertiseBlock(hash, None)
181 };
182
183 let broadcast_fut = broadcast_network.call(request);
184
185 // Await bounded local writes in a spawned task so they don't delay later broadcasts.
186 // Errors can represent partial delivery; don't retry and duplicate successful writes.
187 tokio::spawn(async move {
188 let result = broadcast_fut.await;
189 if is_block_submission {
190 let outcome = if result.is_ok() {
191 "completed"
192 } else {
193 "failed"
194 };
195 metrics::counter!(
196 "sync.mined.block.announcement.outcomes.total",
197 "outcome" => outcome,
198 )
199 .increment(1);
200 if result.is_ok() {
201 metrics::histogram!("sync.mined.block.announcement.duration_seconds")
202 .record(accepted_at.elapsed().as_secs_f64());
203 }
204 }
205 });
206
207 // TODO: Move this logic for marking the last change hash as seen to its own method.
208
209 let is_best_tip = chain_state.latest_chain_tip().best_tip_hash() == Some(hash);
210
211 // Mark the last change hash of `chain_state` as the last block submission hash to avoid
212 // advertising a block hash to some peers twice.
213 if is_block_submission
214 && mined_block_receiver
215 .as_ref()
216 .is_some_and(|rx| rx.is_empty())
217 && is_best_tip
218 {
219 chain_state.mark_last_change_hash(hash);
220 }
221
222 match displaced_tip.take() {
223 Some(tip) if !is_best_tip => {
224 (hash, height) = tip;
225 is_block_submission = false;
226 }
227 _ => break,
228 }
229 }
230 }
231}
232
233/// Receives the next mined block from `mined_block_receiver`.
234///
235/// Never resolves if there is no receiver, so it can be used in a `select!` with other futures.
236async fn recv_mined_block(
237 mined_block_receiver: &mut Option<mpsc::Receiver<(block::Hash, block::Height)>>,
238) -> Option<(block::Hash, block::Height)> {
239 match mined_block_receiver {
240 Some(mined_block_receiver) => mined_block_receiver.recv().await,
241 None => std::future::pending().await,
242 }
243}