use ton_net_lite::{BlockIdExt, PartialBlockProof};
use crate::Error;
const MAX_LINKS_PER_REPLY: usize = 64;
const MAX_LINKS_PER_SYNC: usize = 4096;
const MAX_ROUNDS: usize = 512;
const MAX_PROOF_BYTES: usize = 1 << 20;
const MAX_SIGNATURES: usize = 1024;
const MAX_CLOCK_SKEW: u64 = 300;
pub fn within_bounds(reply: &PartialBlockProof) -> Result<(), Error> {
use ton_net_lite::BlockLink;
if reply.steps.len() > MAX_LINKS_PER_REPLY {
return Err(Error::Sync(format!(
"a reply with {} links, past the {MAX_LINKS_PER_REPLY} a reply may carry",
reply.steps.len()
)));
}
for step in &reply.steps {
let (dest_proof, other, signatures) = match step {
BlockLink::Forward {
dest_proof,
config_proof,
signatures,
..
} => (dest_proof, config_proof, Some(signatures)),
BlockLink::Back {
dest_proof,
state_proof,
..
} => (dest_proof, state_proof, None),
_ => continue,
};
for proof in [dest_proof, other] {
if proof.len() > MAX_PROOF_BYTES {
return Err(Error::Sync(format!(
"a {} byte proof, past the {MAX_PROOF_BYTES} byte bound",
proof.len()
)));
}
}
if let Some(set) = signatures {
let count = set.signatures().len();
if count > MAX_SIGNATURES {
return Err(Error::Sync(format!(
"a set of {count} signatures, past the {MAX_SIGNATURES} bound"
)));
}
}
}
Ok(())
}
pub struct Walk {
rounds: usize,
links: usize,
}
impl Walk {
pub(crate) fn new() -> Self {
Self {
rounds: 0,
links: 0,
}
}
pub(crate) fn round(&mut self, links: usize) -> Result<(), Error> {
self.rounds += 1;
if self.rounds > MAX_ROUNDS {
return Err(Error::Sync(format!(
"more than {MAX_ROUNDS} replies without reaching the head"
)));
}
self.links += links;
if self.links > MAX_LINKS_PER_SYNC {
return Err(Error::Sync(format!(
"more than {MAX_LINKS_PER_SYNC} links without reaching the head"
)));
}
Ok(())
}
pub(crate) fn cost(&self) -> (usize, usize) {
(self.links, self.rounds)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SyncReport {
pub head: BlockIdExt,
pub links: usize,
pub rounds: usize,
}
pub fn advanced(before: &BlockIdExt, after: &BlockIdExt) -> Result<(), Error> {
if after.seqno <= before.seqno {
return Err(Error::Sync(format!(
"a reply left the anchor at {}, so the walk cannot end",
before.seqno
)));
}
Ok(())
}
pub fn fresh_enough(gen_utime: u32, limit_seconds: u32) -> Result<(), Error> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
let stamped = u64::from(gen_utime);
if stamped > now.saturating_add(MAX_CLOCK_SKEW) {
return Err(Error::ClockBehind {
by_seconds: stamped - now,
tolerated_seconds: MAX_CLOCK_SKEW,
});
}
let age = now.saturating_sub(stamped);
if age > u64::from(limit_seconds) {
return Err(Error::Stale {
age_seconds: age,
limit_seconds: u64::from(limit_seconds),
});
}
Ok(())
}
pub fn worth_continuing(elapsed: std::time::Duration, limit_seconds: u32) -> Result<(), Error> {
if limit_seconds == 0 {
return Ok(());
}
let elapsed = elapsed.as_secs();
if elapsed > u64::from(limit_seconds) {
return Err(Error::Sync(format!(
"the walk has run {elapsed}s without finishing, longer than the {limit_seconds}s a head is allowed to be old"
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_walk_that_does_not_end_is_stopped() {
let mut walk = Walk::new();
for _ in 0..MAX_ROUNDS {
walk.round(1).expect("a round within the bound");
}
assert!(matches!(walk.round(1), Err(Error::Sync(_))));
}
#[test]
fn a_walk_with_too_many_links_is_stopped_before_the_round_bound() {
let mut walk = Walk::new();
while walk.round(MAX_LINKS_PER_REPLY).is_ok() {
assert!(walk.cost().1 <= MAX_ROUNDS, "the link bound never bit");
}
assert!(walk.cost().0 > MAX_LINKS_PER_SYNC);
}
#[test]
fn an_anchor_that_does_not_move_ends_the_walk() {
let at = |seqno: u32| BlockIdExt::new(-1, 0x8000_0000_0000_0000, seqno, [0; 32], [0; 32]);
assert!(advanced(&at(10), &at(11)).is_ok());
assert!(matches!(advanced(&at(10), &at(10)), Err(Error::Sync(_))));
assert!(matches!(advanced(&at(10), &at(9)), Err(Error::Sync(_))));
}
#[test]
fn a_head_older_than_the_bound_is_stale() {
#[allow(
clippy::cast_possible_truncation,
reason = "unix seconds fit in u32 until year 2106; fresh_enough takes gen_utime as u32, matching the width TON's utime field actually has on the wire"
)]
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("a clock after 1970")
.as_secs() as u32;
assert!(fresh_enough(now, 600).is_ok());
assert!(fresh_enough(now - 599, 600).is_ok());
assert!(fresh_enough(now - 601, 600).is_err());
match fresh_enough(now - 4_000, 600) {
Err(Error::Stale {
age_seconds,
limit_seconds,
}) => {
assert!((3_999..=4_001).contains(&age_seconds));
assert_eq!(limit_seconds, 600);
}
other => panic!("expected a stale head, got {other:?}"),
}
}
#[test]
fn a_clock_behind_the_chain_is_reported_rather_than_obeyed() {
#[allow(
clippy::cast_possible_truncation,
reason = "unix seconds fit in u32 until year 2106; fresh_enough takes gen_utime as u32, matching the width TON's utime field actually has on the wire"
)]
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("a clock after 1970")
.as_secs() as u32;
assert!(fresh_enough(now + 60, 600).is_ok());
match fresh_enough(now + 10_000, 600) {
Err(Error::ClockBehind {
by_seconds,
tolerated_seconds,
}) => {
assert!((9_999..=10_001).contains(&by_seconds));
assert_eq!(tolerated_seconds, 300);
}
other => panic!("expected the clock to be reported, got {other:?}"),
}
assert!(matches!(
fresh_enough(now + 10_000, u32::MAX),
Err(Error::ClockBehind { .. })
));
}
#[test]
fn a_walk_that_outlasts_the_freshness_bound_stops() {
use std::time::Duration;
assert!(worth_continuing(Duration::from_secs(599), 600).is_ok());
assert!(matches!(
worth_continuing(Duration::from_secs(601), 600),
Err(Error::Sync(_))
));
assert!(worth_continuing(Duration::from_secs(10_000), 0).is_ok());
}
#[test]
fn a_zero_bound_refuses_every_head() {
#[allow(
clippy::cast_possible_truncation,
reason = "unix seconds fit in u32 until year 2106; fresh_enough takes gen_utime as u32, matching the width TON's utime field actually has on the wire"
)]
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("a clock after 1970")
.as_secs() as u32;
assert!(fresh_enough(now - 1, 0).is_err());
}
}