use std::fmt;
use std::future::Future;
use std::time::Duration;
use ton_net_adnl::TcpTransport;
use ton_net_block::{proof, verify_chain, Account, AccountRead};
use ton_net_lite::{
AccountId, AccountState, BlockIdExt, BlockLink, LiteClient, LiteError, MasterchainInfo,
PartialBlockProof, ServerReported,
};
use crate::sync::{self, SyncReport};
use crate::{Address, Config, Error, Verified};
const CALL_TIMEOUT: Duration = Duration::from_secs(15);
const PROOF_TIMEOUT: Duration = Duration::from_secs(60);
const MASTERCHAIN: i32 = -1;
const MASTERCHAIN_SHARD: u64 = 0x8000_0000_0000_0000;
pub struct Client {
lite: LiteClient<TcpTransport>,
anchor: Option<BlockIdExt>,
init_block: Option<BlockIdExt>,
max_head_age: u32,
}
impl Client {
pub async fn connect(config: &Config) -> Result<Client, Error> {
let mut last_error: Option<Error> = None;
for server in config.liteservers() {
let transport = match TcpTransport::connect(&server.addr).await {
Ok(transport) => transport,
Err(e) => {
last_error = Some(e.into());
continue;
}
};
match LiteClient::connect(transport, &server.key).await {
Ok(lite) => {
return Ok(Client {
lite,
anchor: None,
init_block: config.init_block().cloned(),
max_head_age: config.max_head_age(),
})
}
Err(e) => last_error = Some(e.into()),
}
}
Err(last_error.unwrap_or_else(|| Error::Config("config has no liteservers".to_string())))
}
pub async fn connect_from(config: &Config, anchor: &BlockIdExt) -> Result<Client, Error> {
let mut client = Client::connect(config).await?;
client.anchor = Some(anchor.clone());
client.sync().await?;
Ok(client)
}
#[must_use]
pub fn anchor(&self) -> Option<&BlockIdExt> {
self.anchor.as_ref()
}
pub async fn sync(&mut self) -> Result<SyncReport, Error> {
let start = match (&self.anchor, &self.init_block) {
(Some(anchor), _) => anchor.clone(),
(None, Some(init)) => init.clone(),
(None, None) => {
return Err(Error::Config(
"config names no init block to start a sync from".to_string(),
))
}
};
let target = self.masterchain_info().await?.into_value().last;
if target.seqno <= start.seqno {
return Err(Error::Sync(format!(
"the server's head at {} is not ahead of the trusted block at {}",
target.seqno, start.seqno
)));
}
let started = std::time::Instant::now();
let mut anchor = start.clone();
let mut trusted_key_block = start;
let mut walk = sync::Walk::new();
loop {
sync::worth_continuing(started.elapsed(), self.max_head_age)?;
let reply = within(PROOF_TIMEOUT, self.lite.block_proof(&anchor, &target)).await?;
sync::within_bounds(&reply)?;
walk.round(reply.steps.len())?;
let proven = verify_chain(&(&anchor).into(), &reply)
.map_err(|failure| Error::Sync(failure.to_string()))?;
let reached = BlockIdExt::from(proven.id);
sync::advanced(&anchor, &reached)?;
if let Some(key_block) = last_key_block(&reply) {
trusted_key_block = key_block;
}
anchor = reached;
if reply.complete {
if anchor != target {
return Err(Error::Sync(format!(
"the server called the chain complete at {} without reaching the {} it named",
anchor.seqno, target.seqno
)));
}
sync::fresh_enough(proven.gen_utime, self.max_head_age)?;
self.anchor = Some(trusted_key_block);
let (links, rounds) = walk.cost();
return Ok(SyncReport {
head: anchor,
links,
rounds,
});
}
if !proven.key_block {
return Err(Error::Sync(
"an unfinished chain stopped at a block no chain can continue from".to_string(),
));
}
}
}
pub async fn masterchain_info(&mut self) -> Result<ServerReported<MasterchainInfo>, Error> {
bounded(self.lite.masterchain_info()).await
}
pub async fn account(&mut self, address: &Address) -> Result<Verified<Account>, Error> {
let head = self.sync().await?.head;
self.account_at(address, &head).await
}
pub async fn account_reported(
&mut self,
address: &Address,
) -> Result<ServerReported<Account>, Error> {
let head = self.masterchain_info().await?;
let reported = self.account_state(address, &head.value().last).await?;
reported
.try_map(|state| Account::decode(&state.state))
.map_err(Error::decoding)
}
pub async fn account_state(
&mut self,
address: &Address,
block: &BlockIdExt,
) -> Result<ServerReported<AccountState>, Error> {
let account = AccountId {
workchain: address.workchain(),
id: *address.account_id(),
};
bounded(self.lite.account_state(block, &account)).await
}
pub async fn account_at(
&mut self,
address: &Address,
trusted: &BlockIdExt,
) -> Result<Verified<Account>, Error> {
if trusted.workchain != MASTERCHAIN || trusted.shard != MASTERCHAIN_SHARD {
return Err(Error::Proof(format!(
"the trusted block is in workchain {}, and only a masterchain block anchors a read",
trusted.workchain
)));
}
let reported = self.account_state(address, trusted).await?;
let anchor = trusted.root_hash;
let workchain = address.workchain();
let state = reported.value();
let read = if workchain == MASTERCHAIN {
AccountRead::masterchain(
&anchor,
address.account_id(),
reported.proof(),
&state.state,
)
} else {
AccountRead::in_shard(
&anchor,
workchain,
address.account_id(),
&state.shard_proof,
reported.proof(),
&state.state,
)
};
let account = proof::verify_account(&read)?;
Ok(Verified::new(account, trusted.clone()))
}
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client").finish_non_exhaustive()
}
}
fn last_key_block(reply: &PartialBlockProof) -> Option<BlockIdExt> {
reply.steps.iter().rev().find_map(|step| match step {
BlockLink::Forward {
to_key_block: true,
to,
..
} => Some(to.clone().into()),
_ => None,
})
}
async fn bounded<T>(call: impl Future<Output = Result<T, LiteError>>) -> Result<T, Error> {
within(CALL_TIMEOUT, call).await
}
async fn within<T>(
deadline: Duration,
call: impl Future<Output = Result<T, LiteError>>,
) -> Result<T, Error> {
match tokio::time::timeout(deadline, call).await {
Ok(result) => result.map_err(Error::from),
Err(_elapsed) => Err(Error::Timeout),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn a_call_that_never_answers_times_out() {
let never = std::future::pending::<Result<(), LiteError>>();
let result: Result<(), Error> = bounded(never).await;
assert!(matches!(result, Err(Error::Timeout)));
}
#[tokio::test(start_paused = true)]
async fn a_call_that_answers_is_not_timed_out() {
let ready = std::future::ready::<Result<u32, LiteError>>(Ok(7));
assert_eq!(bounded(ready).await.unwrap(), 7);
}
}