Skip to main content

ton_net/
client.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2026 Nirapod Labs
3
4//! The client: one ADNL channel to one liteserver, with reads over it.
5
6use std::fmt;
7use std::future::Future;
8use std::time::Duration;
9
10use ton_net_adnl::TcpTransport;
11use ton_net_block::{proof, verify_chain, Account, AccountRead};
12use ton_net_lite::{
13    AccountId, AccountState, BlockIdExt, BlockLink, LiteClient, LiteError, MasterchainInfo,
14    PartialBlockProof, ServerReported,
15};
16
17use crate::sync::{self, SyncReport};
18use crate::{Address, Config, Error, Verified};
19
20/// The deadline for one read, after which the call returns [`Error::Timeout`].
21const CALL_TIMEOUT: Duration = Duration::from_secs(15);
22
23/// The deadline for one block-proof reply, which is a different size of thing.
24///
25/// An account read is a few kilobytes. One round of a proof chain is closer to seven
26/// hundred, because every link in it carries a configuration proof exposing a validator
27/// set of several hundred entries. Holding both to the same deadline means either
28/// refusing an honest proof on a slow link or letting a dead read hang.
29const PROOF_TIMEOUT: Duration = Duration::from_secs(60);
30
31/// The workchain id of the masterchain, whose accounts need no shard proof.
32const MASTERCHAIN: i32 = -1;
33
34/// The masterchain's shard: an empty prefix, so the whole workchain in one shard.
35const MASTERCHAIN_SHARD: u64 = 0x8000_0000_0000_0000;
36
37/// A connection to a single TON liteserver.
38///
39/// A `Client` owns one ADNL channel to one liteserver and serves reads over it.
40///
41/// Reads come in two kinds and the return type says which. A [`ServerReported`] value is
42/// the server's word, believed because the server said so. A [`Verified`] value was
43/// checked against a block hash the caller supplied, and could not have been produced any
44/// other way. Nothing converts one into the other.
45///
46/// A `Client` serializes its queries: overlapping calls on the same client run one after
47/// another over the single channel, because each takes `&mut self`. Open more than one
48/// client for real concurrency.
49pub struct Client {
50    lite: LiteClient<TcpTransport>,
51    /// The key block trust rests on. `None` until a sync has established one.
52    anchor: Option<BlockIdExt>,
53    /// The block a cold sync starts walking from, as the config named it.
54    init_block: Option<BlockIdExt>,
55    /// How far behind the local clock a proven head may be.
56    max_head_age: u32,
57}
58
59impl Client {
60    /// Connects to a liteserver from the config and completes the ADNL handshake.
61    ///
62    /// Tries the config's liteservers in turn until one connects and completes a
63    /// handshake. Nothing is proved yet: the client has no anchor until
64    /// [`sync`](Self::sync) establishes one.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`Error::Transport`] if no liteserver is reachable, or [`Error::Handshake`]
69    /// if the last one reached rejects the handshake.
70    pub async fn connect(config: &Config) -> Result<Self, Error> {
71        let mut last_error: Option<Error> = None;
72        for server in config.liteservers() {
73            let transport = match TcpTransport::connect(&server.addr).await {
74                Ok(transport) => transport,
75                Err(e) => {
76                    last_error = Some(e.into());
77                    continue;
78                }
79            };
80            match LiteClient::connect(transport, &server.key).await {
81                Ok(lite) => {
82                    return Ok(Self {
83                        lite,
84                        anchor: None,
85                        init_block: config.init_block().cloned(),
86                        max_head_age: config.max_head_age(),
87                    })
88                }
89                Err(e) => last_error = Some(e.into()),
90            }
91        }
92        Err(last_error.unwrap_or_else(|| Error::Config("config has no liteservers".to_string())))
93    }
94
95    /// Connects and starts the walk from a block the caller already trusts.
96    ///
97    /// `anchor` must be a masterchain key block. It is the client's root of trust:
98    /// everything the client goes on to believe is derived from it, so it is worth
99    /// exactly what the storage it came from is worth. Anything that can write to where
100    /// a caller keeps one can choose what this client believes.
101    ///
102    /// A block from a previous run's [`anchor`](Self::anchor) makes this sync short,
103    /// which is the whole reason the anchor is handed back.
104    ///
105    /// # Errors
106    ///
107    /// As [`connect`](Self::connect), plus [`Error::Sync`] if the server cannot prove a
108    /// chain from `anchor`, and [`Error::Stale`] if what it leads to is too old.
109    pub async fn connect_from(config: &Config, anchor: &BlockIdExt) -> Result<Self, Error> {
110        let mut client = Self::connect(config).await?;
111        client.anchor = Some(anchor.clone());
112        client.sync().await?;
113        Ok(client)
114    }
115
116    /// The key block the client's trust currently rests on, if a sync has run.
117    ///
118    /// Saving this and handing it to [`connect_from`](Self::connect_from) on a later run
119    /// makes that run's sync short. It is a public block identity and holds no secret,
120    /// but it is a root of trust, so where it is kept is a decision the caller's own
121    /// threat model makes. This library stores nothing and picks no location.
122    #[must_use]
123    pub fn anchor(&self) -> Option<&BlockIdExt> {
124        self.anchor.as_ref()
125    }
126
127    /// Walks the anchor forward to the network's current head.
128    ///
129    /// Without an anchor the walk starts at the config's init block, which is a first
130    /// sync and costs a run over every key block published since that block: about a
131    /// couple of minutes and fifty megabytes against mainnet in July 2026. With one it is
132    /// a few links.
133    ///
134    /// The head in the returned [`SyncReport`] is proved and then the client forgets it.
135    /// What the client keeps is the last key block on the way, because that is the only
136    /// kind of block a later chain can continue from. Read [`anchor`](Self::anchor) after
137    /// this to save it.
138    ///
139    /// # Errors
140    ///
141    /// Returns [`Error::Config`] if there is neither an anchor nor an init block,
142    /// [`Error::Sync`] if the proof chain does not check out or the server will not
143    /// finish it, [`Error::Stale`] if the head it leads to is older than the config's
144    /// freshness bound, or the transport errors.
145    pub async fn sync(&mut self) -> Result<SyncReport, Error> {
146        let start = match (&self.anchor, &self.init_block) {
147            (Some(anchor), _) => anchor.clone(),
148            (None, Some(init)) => init.clone(),
149            (None, None) => {
150                return Err(Error::Config(
151                    "config names no init block to start a sync from".to_string(),
152                ))
153            }
154        };
155
156        // The head is the server's word about where the chain ends, used as the target to
157        // ask for. Every block on the way to it is proved, this one included, and the
158        // walk is required below to actually arrive at it, so a server naming a block it
159        // cannot reach fails the walk rather than steering it somewhere shorter.
160        //
161        // What this does not settle is whether the head named is the network's. Nothing
162        // inside a proof says when it was served, so a server understating its own head
163        // is caught by the freshness bound and by nothing else.
164        let target = self.masterchain_info().await?.into_value().last;
165        // A server whose head is not ahead of what the client already trusts has nothing
166        // to prove, and there is no way to establish that its block is current without a
167        // chain to it. That is a refusal rather than a quiet success at the old block.
168        if target.seqno <= start.seqno {
169            return Err(Error::Sync(format!(
170                "the server's head at {} is not ahead of the trusted block at {}",
171                target.seqno, start.seqno
172            )));
173        }
174
175        let started = std::time::Instant::now();
176        let mut anchor = start.clone();
177        let mut trusted_key_block = start;
178        let mut walk = sync::Walk::new();
179        loop {
180            sync::worth_continuing(started.elapsed(), self.max_head_age)?;
181            let reply = within(PROOF_TIMEOUT, self.lite.block_proof(&anchor, &target)).await?;
182            sync::within_bounds(&reply)?;
183            walk.round(reply.steps.len())?;
184
185            let proven = verify_chain(&(&anchor).into(), &reply)
186                .map_err(|failure| Error::Sync(failure.to_string()))?;
187            let reached = BlockIdExt::from(proven.id);
188            sync::advanced(&anchor, &reached)?;
189
190            // Every link's key-block flag was checked against the destination's own
191            // header, so after the chain checks out the flag is proved rather than
192            // claimed and the last key block in the run can be taken from it.
193            if let Some(key_block) = last_key_block(&reply) {
194                trusted_key_block = key_block;
195            }
196            anchor = reached;
197
198            if reply.complete {
199                // A chain is only finished if it ends where it was asked to end. Without
200                // this the server picks the head, since nothing below reads `complete`
201                // and the chain layer checks only that the run is internally consistent
202                // and starts where the client said. Stopping short of a target the same
203                // server named a moment ago is not something an honest one does.
204                if anchor != target {
205                    return Err(Error::Sync(format!(
206                        "the server called the chain complete at {} without reaching the {} it named",
207                        anchor.seqno, target.seqno
208                    )));
209                }
210                sync::fresh_enough(proven.gen_utime, self.max_head_age)?;
211                self.anchor = Some(trusted_key_block);
212                let (links, rounds) = walk.cost();
213                return Ok(SyncReport {
214                    head: anchor,
215                    links,
216                    rounds,
217                });
218            }
219            // An unfinished chain has to be continued from where it stopped, and only a
220            // key block carries the validator set that makes the next step checkable.
221            if !proven.key_block {
222                return Err(Error::Sync(
223                    "an unfinished chain stopped at a block no chain can continue from".to_string(),
224                ));
225            }
226        }
227    }
228
229    /// Reads the liteserver's current masterchain head.
230    ///
231    /// The returned [`MasterchainInfo`] is fully decoded from the wire. It is not
232    /// proof-verified.
233    ///
234    /// # Errors
235    ///
236    /// Returns [`Error::Timeout`] if the query does not complete in time, [`Error::LiteServer`]
237    /// if the server returns an error, [`Error::Decode`] if the response does not decode,
238    /// or [`Error::Transport`] on a socket failure.
239    pub async fn masterchain_info(&mut self) -> Result<ServerReported<MasterchainInfo>, Error> {
240        bounded(self.lite.masterchain_info()).await
241    }
242
243    /// Reads an account and proves it against a block this client established itself.
244    ///
245    /// Walks the chain to a current head, reads the account there, and checks the proofs
246    /// against it. **Nothing in the result rests on a hash the caller supplied**, which is
247    /// what separates this from [`account_at`](Self::account_at): the block it proves
248    /// against was derived from the key block the config pins, one validator signature set
249    /// at a time.
250    ///
251    /// Every call walks. After the first that is a link or two, but it is not free, so a
252    /// caller reading many accounts should [`sync`](Self::sync) once and pass the head to
253    /// [`account_at`](Self::account_at) rather than pay it per account.
254    ///
255    /// # Errors
256    ///
257    /// Returns [`Error::Config`] if there is nothing to start a walk from, [`Error::Sync`]
258    /// if the chain does not check out, [`Error::Stale`] if the head it reaches is too
259    /// old, [`Error::Proof`] if the account does not bind to that head, or the transport
260    /// errors.
261    pub async fn account(&mut self, address: &Address) -> Result<Verified<Account>, Error> {
262        let head = self.sync().await?.head;
263        self.account_at(address, &head).await
264    }
265
266    /// Reads an account at the current masterchain head without checking anything.
267    ///
268    /// Reads the head first, then the account at that block. The value is the server's
269    /// word: the proofs it sent are carried along unchecked. It is named for what it is
270    /// because after this release the proven read is the one a caller lands on without
271    /// choosing, and this is the exception.
272    ///
273    /// # Errors
274    ///
275    /// Returns [`Error::Timeout`] if a query does not complete in time, [`Error::LiteServer`]
276    /// if the server returns an error, [`Error::Decode`] if a response does not decode,
277    /// [`Error::Cell`] if the account state does not read as an account, or
278    /// [`Error::Transport`] on a socket failure. Never [`Error::Proof`]: this call checks
279    /// no proof, so it has none to fail.
280    pub async fn account_reported(
281        &mut self,
282        address: &Address,
283    ) -> Result<ServerReported<Account>, Error> {
284        let head = self.masterchain_info().await?;
285        let reported = self.account_state(address, &head.value().last).await?;
286        // Decoding does not make the value any more believed, so it stays wrapped. The
287        // failure is classified by hand rather than through `?`, because the conversion
288        // reads a block-structure failure as a proof failure and there is no proof here.
289        reported
290            .try_map(|state| Account::decode(&state.state))
291            .map_err(|error| Error::decoding(&error))
292    }
293
294    /// Reads an account's raw state and proofs at a given block.
295    ///
296    /// The bytes come back as the server sent them, unchecked and undecoded. This is the
297    /// way out for a caller who wants to keep the proofs, check them elsewhere, or check
298    /// them against an anchor obtained later.
299    ///
300    /// # Errors
301    ///
302    /// Returns [`Error::Timeout`] if the query does not complete in time,
303    /// [`Error::LiteServer`] if the server returns an error, [`Error::Decode`] if the
304    /// response does not decode, or [`Error::Transport`] on a socket failure.
305    pub async fn account_state(
306        &mut self,
307        address: &Address,
308        block: &BlockIdExt,
309    ) -> Result<ServerReported<AccountState>, Error> {
310        let account = AccountId {
311            workchain: address.workchain(),
312            id: *address.account_id(),
313        };
314        bounded(self.lite.account_state(block, &account)).await
315    }
316
317    /// Reads an account at a block the caller names, and proves it belongs to that block.
318    ///
319    /// The proofs are checked against `trusted`'s root hash: for an account outside the
320    /// masterchain the shard block holding it is derived from the masterchain state rather
321    /// than taken from what the server named, and the state bytes are bound to the account
322    /// the proof carries. An account the block's state does not hold comes back as
323    /// [`AccountStatus::Nonexistent`](ton_net_block::AccountStatus::Nonexistent), which is
324    /// a proved answer rather than a failure. An account the proof declines to cover is a
325    /// failure.
326    ///
327    /// `trusted` is taken on faith, so where it came from is the whole question. Taking it
328    /// from [`masterchain_info`](Self::masterchain_info) on this same client proves
329    /// nothing: that only shows the server agrees with itself. The two sources that do
330    /// mean something are a block this client proved, from [`sync`](Self::sync) or
331    /// [`anchor`](Self::anchor), and a block the caller trusts independently.
332    ///
333    /// Reading many accounts at one proved block is what this is for now:
334    /// [`account`](Self::account) walks the chain on every call, so a caller who wants a
335    /// consistent snapshot syncs once and passes the head here.
336    ///
337    /// # Errors
338    ///
339    /// Returns [`Error::Proof`] if `trusted` is not a masterchain block, if a proof does
340    /// not check out, or if the account does not bind to `trusted`, or [`Error::Timeout`],
341    /// [`Error::LiteServer`], [`Error::Decode`], or [`Error::Transport`] as the read
342    /// fails.
343    pub async fn account_at(
344        &mut self,
345        address: &Address,
346        trusted: &BlockIdExt,
347    ) -> Result<Verified<Account>, Error> {
348        // The whole chain of reasoning below hangs off a masterchain block: a shard read
349        // derives its shard block from the masterchain state, and a masterchain read
350        // takes this hash as the state's own. A shard block here would leave the second
351        // path checking a server's proof against a server's hash and calling the result
352        // verified. The chain layer refuses a non-masterchain block by name, and this is
353        // the other door into the same trust.
354        if trusted.workchain != MASTERCHAIN || trusted.shard != MASTERCHAIN_SHARD {
355            return Err(Error::Proof(format!(
356                "the trusted block is in workchain {}, and only a masterchain block anchors a read",
357                trusted.workchain
358            )));
359        }
360        let reported = self.account_state(address, trusted).await?;
361        let anchor = trusted.root_hash;
362        let workchain = address.workchain();
363        let state = reported.value();
364
365        let read = if workchain == MASTERCHAIN {
366            AccountRead::masterchain(
367                &anchor,
368                address.account_id(),
369                reported.proof(),
370                &state.state,
371            )
372        } else {
373            AccountRead::in_shard(
374                &anchor,
375                workchain,
376                address.account_id(),
377                &state.shard_proof,
378                reported.proof(),
379                &state.state,
380            )
381        };
382
383        let account = proof::verify_account(&read)?;
384        Ok(Verified::new(account, trusted.clone()))
385    }
386}
387
388impl fmt::Debug for Client {
389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390        f.debug_struct("Client").finish_non_exhaustive()
391    }
392}
393
394/// The last block in a checked chain that a later chain can continue from.
395///
396/// Only safe to read after [`verify_chain`] has returned, because that is what ties each
397/// link's key-block flag to the destination block's own header.
398fn last_key_block(reply: &PartialBlockProof) -> Option<BlockIdExt> {
399    reply.steps.iter().rev().find_map(|step| match step {
400        BlockLink::Forward {
401            to_key_block: true,
402            to,
403            ..
404        } => Some(to.clone().into()),
405        _ => None,
406    })
407}
408
409/// Runs one liteserver read under the ordinary deadline.
410async fn bounded<T>(call: impl Future<Output = Result<T, LiteError>>) -> Result<T, Error> {
411    within(CALL_TIMEOUT, call).await
412}
413
414/// Runs one liteserver call under a given deadline, mapping its error into [`Error`].
415async fn within<T>(
416    deadline: Duration,
417    call: impl Future<Output = Result<T, LiteError>>,
418) -> Result<T, Error> {
419    match tokio::time::timeout(deadline, call).await {
420        Ok(result) => result.map_err(Error::from),
421        Err(_elapsed) => Err(Error::Timeout),
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    // A call that never answers must resolve to `Error::Timeout`, never hang. With the
430    // clock paused, tokio advances virtual time to the deadline the moment the runtime is
431    // otherwise idle, so this proves the bound in real time without a fifteen-second wait.
432    #[tokio::test(start_paused = true)]
433    async fn a_call_that_never_answers_times_out() {
434        let never = std::future::pending::<Result<(), LiteError>>();
435        let result: Result<(), Error> = bounded(never).await;
436        assert!(matches!(result, Err(Error::Timeout)));
437    }
438
439    // A call that answers before the deadline passes its result through untouched.
440    #[tokio::test(start_paused = true)]
441    async fn a_call_that_answers_is_not_timed_out() {
442        let ready = std::future::ready::<Result<u32, LiteError>>(Ok(7));
443        assert_eq!(bounded(ready).await.unwrap(), 7);
444    }
445}