use std::{
collections::{HashSet, VecDeque},
sync::{Arc, LazyLock},
time::Duration,
};
use futures::Sink;
use tokio::{
sync::{OwnedSemaphorePermit, Semaphore},
time::{sleep, sleep_until, timeout_at, Instant, Sleep},
};
use tower::{Service, ServiceExt};
use zebra_chain::{
block::{self, Block, MAX_BLOCK_BYTES},
chain_tip::ChainTip,
serialization::{CompactSizeMessage, FakeWriter, SerializationError, ZcashSerialize},
};
use super::{Connection, Handler, InventoryResponse, State};
use crate::{
compact::{BlockTransactions, BlockTransactionsRequest, CompactBlock, Reconstruction},
constants,
peer_set::InventoryChange,
protocol::external::{InventoryHash, Message},
BoxError, PeerError, Request, Response,
};
pub(super) static SENT_SLOTS: LazyLock<Arc<Semaphore>> =
LazyLock::new(|| Arc::new(Semaphore::new(6)));
pub(super) static RECEIVED_SLOTS: LazyLock<Arc<Semaphore>> =
LazyLock::new(|| Arc::new(Semaphore::new(6)));
const RETENTION: Duration = Duration::from_secs(15);
const ANNOUNCED_BLOCKS: usize = 4;
const RECOVERY_TIMEOUT: Duration = Duration::from_secs(2);
pub(super) const MAX_RECOVERY_REPLIES: usize = 2;
struct ServingBlock {
block: Arc<Block>,
nonce: u64,
}
#[derive(Default)]
pub(super) struct CompactRelay {
pub(super) send: bool,
received: Option<(Arc<CompactBlock>, Instant, OwnedSemaphorePermit)>,
sent: Option<(ServingBlock, Option<Instant>, OwnedSemaphorePermit)>,
recovery_bytes_left: usize,
recovery_replies_left: usize,
reconstructed: Option<(Arc<Block>, Instant, OwnedSemaphorePermit)>,
last_received: Option<Instant>,
download_deadline: Option<Instant>,
announced: VecDeque<block::Hash>,
}
impl CompactRelay {
pub(super) fn clear_sent(&mut self) {
self.sent = None;
}
pub(super) fn release(&mut self) {
self.received = None;
self.sent = None;
self.reconstructed = None;
}
pub(super) fn take_download_deadline(&mut self) -> Option<Instant> {
self.download_deadline.take()
}
pub(super) fn is_cached(&self, hash: block::Hash) -> bool {
self.received
.as_ref()
.is_some_and(|(block, _, _)| block.header.hash() == hash)
|| self
.reconstructed
.as_ref()
.is_some_and(|(block, _, _)| block.hash() == hash)
}
fn note_announced(&mut self, hash: block::Hash) {
if self.announced.contains(&hash) {
return;
}
if self.announced.len() == ANNOUNCED_BLOCKS {
self.announced.pop_front();
}
self.announced.push_back(hash);
}
fn has_announced(&self, hash: block::Hash) -> bool {
self.announced.contains(&hash) || self.is_cached(hash)
}
pub(super) fn mark_sent(&mut self) {
let (_, until, _) = self
.sent
.as_mut()
.expect("a delivered compact announcement retains its serving snapshot");
*until = Some(Instant::now() + RETENTION);
self.recovery_bytes_left =
usize::try_from(MAX_BLOCK_BYTES).expect("the block byte limit fits in memory");
self.recovery_replies_left = MAX_RECOVERY_REPLIES;
}
pub(super) fn expire(&mut self) {
let now = Instant::now();
if self
.received
.as_ref()
.is_some_and(|(_, until, _)| *until <= now)
{
self.received = None;
}
if self
.sent
.as_ref()
.is_some_and(|(_, until, _)| until.is_some_and(|until| until <= now))
{
self.sent = None;
}
if self
.reconstructed
.as_ref()
.is_some_and(|(_, until, _)| *until <= now)
{
self.reconstructed = None;
}
}
pub(super) fn has_cached(&self) -> bool {
self.received.is_some() || self.sent.is_some() || self.reconstructed.is_some()
}
pub(super) fn expiry(&self) -> Instant {
self.received
.as_ref()
.map(|(_, until, _)| *until)
.into_iter()
.chain(self.sent.as_ref().and_then(|(_, until, _)| *until))
.chain(self.reconstructed.as_ref().map(|(_, until, _)| *until))
.min()
.unwrap_or_else(|| Instant::now() + RETENTION)
}
}
impl<S, Tx, C> Connection<S, Tx, C>
where
S: Service<Request, Response = Response, Error = BoxError>,
C: ChainTip,
Tx: Sink<Message, Error = SerializationError> + Unpin,
{
async fn compact_query(&mut self, request: Request) -> Option<Response> {
self.compact_query_until(request, Instant::now() + constants::REQUEST_TIMEOUT)
.await
}
async fn compact_query_until(
&mut self,
request: Request,
deadline: Instant,
) -> Option<Response> {
timeout_at(deadline, async {
self.svc.ready().await.ok()?.call(request).await.ok()
})
.await
.ok()
.flatten()
}
async fn send_compact_request(
&mut self,
message: Message,
deadline: Instant,
) -> Result<(), PeerError> {
let address = self.connection_info.connected_addr.get_transient_addr();
let version = self.connection_info.remote.version;
let minimum = &mut self.minimum_peer_version;
let bans = &self.bans_receiver;
let send = self.peer_tx.send_authorized(message, || {
if version < minimum.current()
|| address.is_some_and(|addr| bans.borrow().is_banned(addr.ip()))
{
Err(PeerError::ConnectionDropped)
} else {
Ok(())
}
});
timeout_at(deadline, send)
.await
.map_err(|_| PeerError::ConnectionSendTimeout)?
}
fn live_authorization(&mut self) -> Result<(), PeerError> {
let address = self.connection_info.connected_addr.get_transient_addr();
if self.connection_info.remote.version < self.minimum_peer_version.current()
|| address.is_some_and(|addr| self.bans_receiver.borrow().is_banned(addr.ip()))
{
Err(PeerError::ConnectionDropped)
} else {
Ok(())
}
}
async fn compact_serving_block(&mut self, hash: block::Hash) -> Option<ServingBlock> {
let Response::Blocks(blocks) = self
.compact_query(Request::BlocksByHash(HashSet::from([hash])))
.await?
else {
return None;
};
let block = blocks.into_iter().find_map(|item| match item {
InventoryResponse::Available((block, _)) if block.hash() == hash => Some(block),
_ => None,
})?;
Some(ServingBlock {
block,
nonce: rand::random(),
})
}
pub(super) async fn compact_advert(&mut self, hash: block::Hash) -> Option<Message> {
if !self.connection_info.early_block_relay || !self.compact.send {
return None;
}
self.compact.expire();
if self.compact.has_announced(hash) {
return None;
}
if self.compact.sent.is_some() {
return None;
}
let permit = SENT_SLOTS.clone().try_acquire_owned().ok()?;
let serving = self.compact_serving_block(hash).await?;
let (serving, compact, permit) = tokio::task::spawn_blocking(move || {
let compact = CompactBlock::from_block(&serving.block, serving.nonce)
.ok()
.and_then(|compact| smaller_announcement(compact, &serving.block));
(serving, compact, permit)
})
.await
.ok()?;
let compact = compact?;
self.compact.sent = Some((serving, None, permit));
Some(Message::CompactBlock(Arc::new(compact)))
}
pub(super) async fn receive_compact(&mut self, block: Arc<CompactBlock>) {
if !self.connection_info.early_block_relay {
return;
}
self.compact.expire();
let hash = block.header.hash();
self.compact.note_announced(hash);
let advertiser = self.connection_info.connected_addr.get_transient_addr();
if self.compact.received.is_none()
&& self
.compact
.last_received
.is_none_or(|last| last.elapsed() >= RETENTION)
&& matches!(
self.compact_query(Request::CheckCompactHeader(block.clone()))
.await,
Some(Response::Nil)
)
{
if let Ok(permit) = RECEIVED_SLOTS.clone().try_acquire_owned() {
self.register_compact_announcement(hash);
if matches!(
self.compact_query(Request::AdvertiseCompactBlock(hash, advertiser))
.await,
Some(Response::Nil)
) {
metrics::counter!("zebra.net.compact_block.admitted").increment(1);
self.compact.last_received = Some(Instant::now());
self.compact.received = Some((block, Instant::now() + RETENTION, permit));
}
return;
}
}
self.register_compact_announcement(hash);
self.drive_peer_request(Request::AdvertiseBlock(hash, advertiser))
.await;
}
fn register_compact_announcement(&self, hash: block::Hash) {
if let (Some(inventory), Some(advertiser)) = (
&self.compact_inventory,
self.connection_info.connected_addr.get_transient_addr(),
) {
let _ = inventory.send(InventoryChange::new_available(
InventoryHash::Block(hash),
advertiser,
));
}
}
pub(super) async fn download_block(&mut self, hash: block::Hash) -> Result<Handler, PeerError> {
let deadline = Instant::now() + constants::REQUEST_TIMEOUT;
self.compact.download_deadline = Some(deadline);
self.compact.expire();
let cached = self
.compact
.reconstructed
.as_ref()
.map(|(block, _, _)| block)
.filter(|block| block.hash() == hash)
.cloned();
if let Some(block) = cached {
return self.compact_response(block);
}
if self
.compact
.received
.as_ref()
.is_some_and(|(block, _, _)| block.header.hash() == hash)
{
let (compact, _, permit) = self
.compact
.received
.take()
.expect("the matching cached compact block exists");
if let Some(Response::CompactBlockTransactions(candidates)) = self
.compact_query_until(Request::CompactBlockTransactions(compact.clone()), deadline)
.await
{
let result =
tokio::task::spawn_blocking(move || (compact.reconstruct(candidates), permit))
.await;
if let Ok((Ok(reconstruction), permit)) = result {
let indexes = reconstruction.missing_indexes();
if indexes.is_empty() {
if let Some(block) = self
.finish_compact(
reconstruction,
BlockTransactions {
block_hash: hash,
transactions: Vec::new(),
},
permit,
deadline,
)
.await
{
return self.compact_response(block);
}
} else if indexes.len() < reconstruction.transaction_count().div_ceil(2) {
self.send_compact_request(
Message::GetBlockTransactions(BlockTransactionsRequest {
block_hash: hash,
indexes,
}),
deadline,
)
.await?;
return Ok(Handler::CompactBlock {
reconstruction,
permit,
deadline,
});
}
}
}
}
self.send_compact_request(Message::GetData(vec![hash.into()]), deadline)
.await?;
Ok(Handler::BlocksByHash {
pending_hashes: HashSet::from([hash]),
blocks: Vec::with_capacity(1),
})
}
fn compact_response(&mut self, block: Arc<Block>) -> Result<Handler, PeerError> {
self.live_authorization()?;
Ok(Handler::Finished(Ok(Response::Blocks(vec![
InventoryResponse::Available((
block,
self.connection_info.connected_addr.get_transient_addr(),
)),
]))))
}
async fn finish_compact(
&mut self,
reconstruction: Reconstruction,
response: BlockTransactions,
permit: OwnedSemaphorePermit,
deadline: Instant,
) -> Option<Arc<Block>> {
let (block, permit) =
tokio::task::spawn_blocking(move || (reconstruction.finish(response), permit))
.await
.ok()?;
let block = block.ok()?;
if !matches!(
self.compact_query_until(Request::CheckCompactBlock(block.clone()), deadline)
.await,
Some(Response::Nil)
) {
return None;
}
metrics::counter!("zebra.net.compact_block.rebuilt").increment(1);
self.compact.reconstructed = Some((block.clone(), Instant::now() + RETENTION, permit));
Some(block)
}
pub(super) async fn receive_compact_transactions(&mut self, response: BlockTransactions) {
let hash = response.block_hash;
let State::AwaitingResponse { handler, .. } = &mut self.state else {
return;
};
if !matches!(handler, Handler::CompactBlock { reconstruction, .. } if reconstruction.block_hash() == hash)
{
return;
}
if let Some(recovery) = &self.compact_recovery {
recovery.send_replace(None);
}
let Handler::CompactBlock {
reconstruction,
permit,
deadline,
} = std::mem::replace(handler, Handler::Finished(Ok(Response::Nil)))
else {
unreachable!("the matching reconstruction was checked")
};
if let Some(block) = self
.finish_compact(reconstruction, response, permit, deadline)
.await
{
match self.compact_response(block) {
Ok(response) => {
if let State::AwaitingResponse { handler, .. } = &mut self.state {
*handler = response;
}
}
Err(error) => self.fail_with(error).await,
}
} else {
self.fallback_compact(hash, deadline).await;
}
}
pub(super) async fn fallback_compact(&mut self, hash: block::Hash, deadline: Instant) {
self.clear_compact_recovery();
if let Err(error) = self
.send_compact_request(Message::GetData(vec![hash.into()]), deadline)
.await
{
self.fail_with(error).await;
return;
}
if let State::AwaitingResponse { handler, .. } = &mut self.state {
*handler = Handler::BlocksByHash {
pending_hashes: HashSet::from([hash]),
blocks: Vec::with_capacity(1),
};
self.request_timer = Some(Box::pin(sleep_until(deadline)));
}
}
pub(super) async fn serve_compact_transactions(&mut self, request: BlockTransactionsRequest) {
if !self.connection_info.early_block_relay {
return;
}
self.compact.expire();
let Some((serving, Some(_), _)) = &self.compact.sent else {
return;
};
if serving.block.hash() != request.block_hash {
return;
}
if request.indexes.is_empty()
|| request
.indexes
.last()
.is_some_and(|index| *index >= serving.block.transactions.len())
|| request.indexes.windows(2).any(|pair| pair[0] >= pair[1])
{
return;
}
let Some(replies_left) = self.compact.recovery_replies_left.checked_sub(1) else {
return;
};
self.compact.recovery_replies_left = replies_left;
let overhead = request.block_hash.zcash_serialized_size()
+ CompactSizeMessage::try_from(request.indexes.len())
.expect("recovery indexes are bounded by the advertised block")
.zcash_serialized_size();
let Some(remaining) = self
.compact
.recovery_bytes_left
.checked_sub(overhead)
.and_then(|remaining| {
request
.indexes
.iter()
.try_fold(remaining, |remaining, index| {
remaining
.checked_sub(serving.block.transactions[*index].zcash_serialized_size())
})
})
else {
return;
};
self.compact.recovery_bytes_left = remaining;
let transactions = request
.indexes
.into_iter()
.map(|index| serving.block.transactions[index].clone())
.collect();
let response = BlockTransactions {
block_hash: request.block_hash,
transactions,
};
if let Err(error) = self
.peer_tx
.send(Message::BlockTransactions(response))
.await
{
self.compact.clear_sent();
self.fail_with(error).await;
}
}
}
pub(super) fn smaller_announcement(compact: CompactBlock, block: &Block) -> Option<CompactBlock> {
(encoded_size(&compact)? < encoded_size(block)?).then_some(compact)
}
fn encoded_size(value: &impl ZcashSerialize) -> Option<usize> {
let mut writer = FakeWriter(0);
value.zcash_serialize(&mut writer).ok()?;
Some(writer.0)
}
pub(super) fn response_timer(handler: &Handler, download_deadline: Option<Instant>) -> Sleep {
match (handler, download_deadline) {
(Handler::CompactBlock { deadline, .. }, _) => {
sleep_until((Instant::now() + RECOVERY_TIMEOUT).min(*deadline))
}
(_, Some(deadline)) => sleep_until(deadline),
(_, None) => sleep(constants::REQUEST_TIMEOUT),
}
}