diff --git README.md README.md index 83321d7..a937908 100644 --- README.md +++ README.md @@ -756,8 +756,12 @@ flowchart TD EmulationResult -- wallet transaction failed --> Rejected EmulationResult -- wallet succeeded --> Fees Fees -- no --> FeeBalance["CALL ERROR
InsufficientBalanceForFees"] + Delivery{"Wallet created every
intent message?"} + Fees -- yes --> Delivery + Delivery -- none / only some --> Rejected + Delivery -- not reported --> EmulationFailed Result["RETURN VALUE
SendPreview
fees · actions · warnings · BOC"] - Fees -- yes --> Result + Delivery -- yes --> Result classDef result fill:#dcfce7,stroke:#15803d,color:#14532d; classDef callError fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d; @@ -767,8 +771,32 @@ flowchart TD ``` Child transaction failures can make `traceSucceeded` false without rejecting -the preview. Only failure of the source wallet transaction produces -`EmulationRejected`. +the preview. `EmulationRejected` comes only from the source wallet +transaction: its compute or action phase failed, or it skipped or did not +create an outgoing message of the intent, for example a send mode with +2 +(ignore errors) whose balance does not cover the message. The wallet's action +counters show the delivery, or its `out_msgs` list when the counters are +unusable; an answer that shows it in neither is `EmulationFailed`. A skipped +message is a funds refusal only when the balance checks above establish one. +`previewTonConnect` and NFT transfer previews take this path too. +`previewSendBoc` emulates an opaque signed BOC without a message list, so it +checks only that the wallet transaction succeeded, and `previewSignMessage` +does not emulate. + +A `previewSend` request with `estimateShortfall` and exact values also asks +for what the operation costs. `walletFeesNanograms` stays the root wallet +transaction fee F, and the preview reports `operationSpendNanograms`, what +the wallet spends beyond the values: with send mode +1 (pay fees separately: +modes 3 and 19, and the mode-less default) F plus the part of the forwarding +fee that travels with the message, and for modes 2 and 18, whose values pay +the forwarding fee, F less the action fee. Such a preview succeeds only with a +known spend and only when the values plus the spend fit the balance; equality +fits, and one nanogram less is `InsufficientBalanceForFees` with the fee and +the spend. When the wallet skipped every message, a zero-value companion +emulated at the same block prices them, and the preview is the funds refusal +with that fee and spend, or `EmulationRejected` where the spend fits. A +refusal that established no amount carries none, and an unknown spend is never +zero. Messages of one intent must share a fee kind for a spend to be known. ### Sign and submit a transfer @@ -1150,7 +1178,8 @@ message could not be built. `EmulationFailed` means that the emulation service, transport, or response failed. `EmulationMessageNotAccepted` means that the current chain state rejected the external message, for example after another client advanced the wallet seqno. `EmulationRejected` means that the external -message created a wallet transaction, but its compute or action phase failed. +message created a wallet transaction, but its compute or action phase failed, +or, for an intent preview, that it did not create every outgoing message. The last error includes the returned TVM phase codes. Handle every send phase explicitly: diff --git examples/tui/src/app.rs examples/tui/src/app.rs index 3f7cd71..ba51f9b 100644 --- examples/tui/src/app.rs +++ examples/tui/src/app.rs @@ -629,12 +629,14 @@ impl App { body: SendMessageBody::Empty, bounce: false, state_init: None, + send_mode: None, }], }; self.status = Some("Checking transfer…".to_owned()); match client .preview_send(SendPreviewRequest { intent: intent.clone(), + estimate_shortfall: false, }) .await { diff --git examples/tui/src/ton_connect.rs examples/tui/src/ton_connect.rs index 5d7eeb3..b5d4b05 100644 --- examples/tui/src/ton_connect.rs +++ examples/tui/src/ton_connect.rs @@ -529,6 +529,7 @@ async fn handle_transaction( match wallet_client .preview_sign_message(SendPreviewRequest { intent: intent.clone(), + estimate_shortfall: false, }) .await { @@ -775,6 +776,7 @@ fn engine_transaction_intent( }), bounce: false, state_init, + send_mode: None, }); } let operation_id = NonEmptyString::try_from(format!("ton-connect-{session_id}-{request_id}")) diff --git examples/web/e2e/support/provider-server.ts examples/web/e2e/support/provider-server.ts index 9b67c75..d522a8b 100644 --- examples/web/e2e/support/provider-server.ts +++ examples/web/e2e/support/provider-server.ts @@ -8,6 +8,8 @@ import {createServer as createHttpsServer} from "node:https" import path from "node:path" import process from "node:process" +import {Cell, loadMessage} from "@ton/core" + import {ActonLocalnet} from "./acton-localnet" const DEFAULT_PORT: number = 5198 @@ -18,6 +20,9 @@ const SCRIPTED_NFT_COLLECTION: string = "0:4444444444444444444444444444444444444444444444444444444444444444" const REPOSITORY_ROOT: string = path.resolve(import.meta.dirname, "../../../..") const TLS_FIXTURES: string = path.join(REPOSITORY_ROOT, "tests/ton-connect/dapp/fixtures") +/** Telegram wallet opcodes of a signed external request with one or several messages. */ +const SEND_ONE_EXTERNAL_OPCODE: number = 0x63896e75 +const SEND_BULK_EXTERNAL_OPCODE: number = 0x73896e75 const port: number = parsePort(process.argv, DEFAULT_PORT) const servesInsecureHttp: boolean = process.argv.includes("--http") @@ -85,15 +90,15 @@ async function route(request: IncomingMessage, response: ServerResponse): Promis return } - scriptedResponse(request, requestUrl, response) + await scriptedResponse(request, requestUrl, response) } /** Returns the deterministic provider response used by non-localnet client scenarios. */ -function scriptedResponse( +async function scriptedResponse( request: IncomingMessage, requestUrl: URL, response: ServerResponse, -): void { +): Promise { if (requestUrl.pathname.endsWith("/api/v2/getAddressInformation")) { walletAddress = requestUrl.searchParams.get("address") ?? walletAddress sendJson(response, 200, { @@ -112,7 +117,8 @@ function scriptedResponse( sendJson(response, 409, {error: "Wallet account must be loaded before emulation"}) return } - sendJson(response, 200, successfulEmulation(walletAddress)) + const messages: number = emulatedMessageCount(await readBody(request)) + sendJson(response, 200, successfulEmulation(walletAddress, messages)) return } @@ -439,8 +445,36 @@ function scriptedNftArtwork(variant: string | null): string { ` } -/** Returns a successful trace rooted at the wallet most recently loaded by the engine. */ -function successfulEmulation(account: string): unknown { +/** Counts the outgoing messages of the wallet request signed into an emulateTrace body's BOC. */ +function emulatedMessageCount(body: Buffer): number { + const request: unknown = JSON.parse(body.toString("utf8")) + if ( + typeof request !== "object" || + request === null || + !("boc" in request) || + typeof request.boc !== "string" + ) { + throw new Error("Expected an emulateTrace body with a BOC") + } + const wallet = loadMessage(Cell.fromBase64(request.boc).beginParse()).body.beginParse() + // Signature, then opcode, wallet id, expiration and seqno. + wallet.skip(512) + const opcode: number = wallet.loadUint(32) + wallet.skip(96) + if (opcode === SEND_ONE_EXTERNAL_OPCODE) { + return 1 + } + if (opcode === SEND_BULK_EXTERNAL_OPCODE) { + return wallet.loadUint(8) + } + throw new Error(`Unsupported wallet request opcode 0x${opcode.toString(16)}`) +} + +/** + * Returns a successful trace rooted at the wallet most recently loaded by the engine, in which the + * wallet created each of its `messages` outgoing messages, as the engine's preview requires. + */ +function successfulEmulation(account: string, messages: number): unknown { return { actions: [], is_incomplete: false, @@ -452,10 +486,17 @@ function successfulEmulation(account: string): unknown { account, description: { aborted: false, - action: {result_code: 0, success: true}, + action: { + msgs_created: messages, + result_code: 0, + skipped_actions: 0, + success: true, + tot_actions: messages, + }, compute_ph: {exit_code: 0, success: true}, type: "ord", }, + out_msgs: Array.from({length: messages}, () => ({source: account})), total_fees: "1000000", }, }, diff --git src/domain/error.rs src/domain/error.rs index 26b26f4..a2c64b6 100644 --- src/domain/error.rs +++ src/domain/error.rs @@ -1,6 +1,6 @@ //! Resource state and errors exposed by wallet operations. -use super::AccountStatus; +use super::{AccountStatus, SendIntentError}; use crate::{HttpHostErrorKind, UnsignedDecimalString}; /// Replaces control characters and bounds diagnostics stored in public errors. @@ -254,6 +254,22 @@ pub enum WalletClientError { available_nanograms: UnsignedDecimalString, /// The requested transfer value, in nanograms. requested_nanograms: UnsignedDecimalString, + /// The wallet fee of this exact operation, in nanograms, present only + /// when a preview that asked for it established it from the + /// provider's emulations. + #[serde(default, skip_serializing_if = "Option::is_none")] + operation_fee_nanograms: Option, + /// What this exact operation spends beyond the requested value, in + /// nanograms, present only when a preview that asked for the + /// operation's fee established it; `None` means unknown, never zero. + /// + /// Unlike `operation_fee_nanograms`, the root wallet transaction fee, + /// this counts the part of the forwarding fee that travels with each + /// message under send mode +1, and leaves out the action fee that a + /// message without +1 pays from its own value: the requested value + /// plus this amount is what the wallet would spend. + #[serde(default, skip_serializing_if = "Option::is_none")] + operation_spend_nanograms: Option, }, /// The requested exact value fits, but the value and emulated wallet fee do not. #[error( @@ -266,6 +282,24 @@ pub enum WalletClientError { requested_nanograms: UnsignedDecimalString, /// The wallet transaction fee returned by emulation. estimated_fee_nanograms: UnsignedDecimalString, + /// The wallet fee of this exact operation, in nanograms, present only + /// when a preview that asked for it established it from the + /// provider's emulations. + #[serde(default, skip_serializing_if = "Option::is_none")] + operation_fee_nanograms: Option, + /// What this exact operation spends beyond the requested value, in + /// nanograms, present only when a preview that asked for the + /// operation's fee established it; `None` means unknown, never zero. + /// + /// Unlike `operation_fee_nanograms`, the root wallet transaction fee, + /// this counts the part of the forwarding fee that travels with each + /// message under send mode +1, and leaves out the action fee that a + /// message without +1 pays from its own value. When it is present, + /// this refusal means that the requested value plus this amount + /// exceeds the balance, where equality fits, instead of a comparison + /// with `estimated_fee_nanograms`. + #[serde(default, skip_serializing_if = "Option::is_none")] + operation_spend_nanograms: Option, }, /// The protected secret cannot be decoded as a valid wallet recovery phrase. #[error("the protected wallet secret is invalid")] @@ -333,4 +367,145 @@ pub enum WalletClientError { /// Bounded developer-facing reason that contains no secret material. diagnostic: String, }, + /// A message names a send mode that the engine cannot sign exactly as given. + /// + /// No signed message is produced for the request. + #[error("send mode {mode} is not supported: {diagnostic}")] + UnsupportedSendMode { + /// The refused mode exactly as the caller supplied it. + mode: i32, + /// A fixed reason that contains no message data or secret material. + diagnostic: String, + }, +} + +impl From for WalletClientError { + fn from(error: SendIntentError) -> Self { + match error { + SendIntentError::InvalidMessageCount | SendIntentError::WholeBalanceInBatch => { + Self::InvalidSendRequest + } + SendIntentError::UnsupportedSendMode { mode, reason } => Self::UnsupportedSendMode { + mode, + diagnostic: reason.to_string(), + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::WalletClientError; + use crate::UnsignedDecimalString; + + /// Keeps the JSON of a funds refusal without an operation fee as it was, + /// reads that JSON without the field as `None`, and round-trips a fee. + #[test] + fn funds_refusals_serialize_an_absent_operation_fee_as_before() { + let legacy = [ + r#"{"insufficientBalance":{"available_nanograms":"5","requested_nanograms":"7"}}"#, + r#"{"insufficientBalanceForFees":{"available_nanograms":"9","requested_nanograms":"7","estimated_fee_nanograms":"2"}}"#, + ]; + let without_fee = [ + WalletClientError::InsufficientBalance { + available_nanograms: UnsignedDecimalString::from(5_u64), + requested_nanograms: UnsignedDecimalString::from(7_u64), + operation_fee_nanograms: None, + operation_spend_nanograms: None, + }, + WalletClientError::InsufficientBalanceForFees { + available_nanograms: UnsignedDecimalString::from(9_u64), + requested_nanograms: UnsignedDecimalString::from(7_u64), + estimated_fee_nanograms: UnsignedDecimalString::from(2_u64), + operation_fee_nanograms: None, + operation_spend_nanograms: None, + }, + ]; + for (json, error) in legacy.into_iter().zip(without_fee) { + assert_eq!( + serde_json::from_str::(json).expect("legacy JSON decodes"), + error + ); + assert_eq!( + serde_json::to_string(&error).expect("refusal serializes"), + json + ); + } + + let with_fee = WalletClientError::InsufficientBalance { + available_nanograms: UnsignedDecimalString::from(5_u64), + requested_nanograms: UnsignedDecimalString::from(7_u64), + operation_fee_nanograms: Some(UnsignedDecimalString::from(419_405_u64)), + operation_spend_nanograms: None, + }; + let json = serde_json::to_value(&with_fee).expect("refusal serializes"); + assert_eq!( + json["insufficientBalance"]["operation_fee_nanograms"], + "419405" + ); + assert_eq!( + serde_json::from_value::(json).expect("refusal decodes"), + with_fee + ); + assert_eq!( + with_fee.to_string(), + "insufficient wallet balance: requested 7 nanograms, available 5" + ); + } + + /// Reads a funds refusal without the spend as `None`, omits an absent + /// spend and round-trips a positive one beside the fee, with the same + /// display text. + #[test] + fn funds_refusals_carry_an_optional_operation_spend() { + let short = |spend: Option| WalletClientError::InsufficientBalance { + available_nanograms: UnsignedDecimalString::from(5_u64), + requested_nanograms: UnsignedDecimalString::from(7_u64), + operation_fee_nanograms: Some(UnsignedDecimalString::from(419_380_u64)), + operation_spend_nanograms: spend.map(UnsignedDecimalString::from), + }; + let short_for_fees = |spend: Option| WalletClientError::InsufficientBalanceForFees { + available_nanograms: UnsignedDecimalString::from(701_082_553_u64), + requested_nanograms: UnsignedDecimalString::from(700_614_284_u64), + estimated_fee_nanograms: UnsignedDecimalString::from(419_380_u64), + operation_fee_nanograms: Some(UnsignedDecimalString::from(419_380_u64)), + operation_spend_nanograms: spend.map(UnsignedDecimalString::from), + }; + let rows = [ + ( + short(None), + short(Some(468_270)), + "insufficientBalance", + r#"{"insufficientBalance":{"available_nanograms":"5","requested_nanograms":"7","operation_fee_nanograms":"419380"}}"#, + "insufficient wallet balance: requested 7 nanograms, available 5", + ), + ( + short_for_fees(None), + short_for_fees(Some(468_270)), + "insufficientBalanceForFees", + r#"{"insufficientBalanceForFees":{"available_nanograms":"701082553","requested_nanograms":"700614284","estimated_fee_nanograms":"419380","operation_fee_nanograms":"419380"}}"#, + "insufficient wallet balance including fees: requested 700614284 nanograms, estimated fee 419380 nanograms, available 701082553 nanograms", + ), + ]; + for (without_spend, with_spend, variant, json, display) in rows { + assert_eq!( + serde_json::from_str::(json).expect("JSON decodes"), + without_spend + ); + assert_eq!( + serde_json::to_string(&without_spend).expect("refusal serializes"), + json + ); + + let encoded = serde_json::to_value(&with_spend).expect("refusal serializes"); + assert_eq!(encoded[variant]["operation_spend_nanograms"], "468270"); + assert_eq!(encoded[variant]["operation_fee_nanograms"], "419380"); + assert_eq!( + serde_json::from_value::(encoded).expect("refusal decodes"), + with_spend + ); + assert_eq!(without_spend.to_string(), display); + assert_eq!(with_spend.to_string(), display); + } + } } diff --git src/domain/send.rs src/domain/send.rs index 5fd95f5..a93eda4 100644 --- src/domain/send.rs +++ src/domain/send.rs @@ -2,6 +2,11 @@ use std::ops::Add; +use ton::block_tlb::{ + SEND_MODE_CARRY_ALL_BALANCE, SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE, + SEND_MODE_DESTROY_ACCOUNT, SEND_MODE_IGNORE_ERRORS, +}; + use crate::{ Base64Hash, Boc, NonEmptyString, TonAddressString, UnsignedDecimalString, UnsignedDecimalStringError, @@ -71,6 +76,51 @@ pub struct SendMessage { pub bounce: bool, /// Optional destination-contract `StateInit` attached independently of the body. pub state_init: Option, + /// Optional wallet send mode signed exactly as given for this message. + /// + /// `None` keeps the engine's modes: 3 for an exact value and 130 for + /// [`SendAmount::All`]. An explicit mode needs an exact value and can combine + /// only +1 (pay fees separately), +2 (ignore errors) and +16 (bounce on action + /// failure); an external message also needs +2. The engine never changes a + /// given mode and refuses any other value with + /// [`crate::WalletClientError::UnsupportedSendMode`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[uniffi(default = None)] + pub send_mode: Option, +} + +/// Flags that no send mode defines. +const UNDEFINED_SEND_MODE_FLAGS: u8 = 4 | 8; + +impl SendMessage { + /// Validates the explicit send mode accepted by every delivery form. + /// + /// `None` means the message keeps the engine's mode for its amount. + pub(crate) fn explicit_send_mode(&self) -> Result, SendIntentError> { + let Some(mode) = self.send_mode else { + return Ok(None); + }; + let refuse = |reason| SendIntentError::UnsupportedSendMode { mode, reason }; + let Ok(flags) = u8::try_from(mode) else { + return Err(refuse(SendModeRefusal::OutOfRange)); + }; + if matches!(self.amount, SendAmount::All) { + return Err(refuse(SendModeRefusal::WholeBalanceAmount)); + } + if flags & UNDEFINED_SEND_MODE_FLAGS != 0 { + return Err(refuse(SendModeRefusal::UndefinedFlag)); + } + if flags & SEND_MODE_CARRY_ALL_BALANCE != 0 { + return Err(refuse(SendModeRefusal::CarryAllBalance)); + } + if flags & SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE != 0 { + return Err(refuse(SendModeRefusal::CarryInboundValue)); + } + if flags & SEND_MODE_DESTROY_ACCOUNT != 0 { + return Err(refuse(SendModeRefusal::DestroyAccount)); + } + Ok(Some(flags)) + } } /// The policy used to select the wallet message expiration boundary. @@ -108,12 +158,17 @@ impl SendIntent { /// /// `None` identifies the single whole-balance form, whose final value can /// only be determined by the wallet contract after fees are charged. + /// Every explicit send mode must pass the checks shared by both delivery + /// forms; [`Self::exact_value_total_for_external`] adds the external rule. pub(crate) fn exact_value_total( &self, ) -> Result, SendIntentError> { if self.messages.is_empty() || self.messages.len() > 255 { return Err(SendIntentError::InvalidMessageCount); } + for message in &self.messages { + let _ = message.explicit_send_mode()?; + } if self.messages.len() > 1 && self .messages @@ -132,6 +187,29 @@ impl SendIntent { } Ok(Some(total)) } + + /// Validates an intent signed as an incoming external message. + /// + /// External requests also need +2 (ignore errors) in every explicit mode: + /// a failed action would otherwise abort the request with its seqno + /// uncommitted, so the same request would be processed again until it + /// expires. + pub(crate) fn exact_value_total_for_external( + &self, + ) -> Result, SendIntentError> { + let total = self.exact_value_total()?; + for message in &self.messages { + if let Some(flags) = message.explicit_send_mode()? + && flags & SEND_MODE_IGNORE_ERRORS == 0 + { + return Err(SendIntentError::UnsupportedSendMode { + mode: i32::from(flags), + reason: SendModeRefusal::MissingIgnoreErrors, + }); + } + } + Ok(total) + } } /// Reports a transfer batch that Wallet V5 cannot represent unambiguously. @@ -143,6 +221,51 @@ pub(crate) enum SendIntentError { /// Carry-all-balance mode cannot be combined with another outgoing message. #[error("whole-balance transfer must be the only message in its batch")] WholeBalanceInBatch, + /// An explicit message send mode cannot be signed exactly as given. + #[error("send mode {mode} is not supported: {reason}")] + UnsupportedSendMode { + /// The explicit mode exactly as the caller supplied it. + mode: i32, + /// The first refusal rule the mode matched. + reason: SendModeRefusal, + }, +} + +/// Why an explicit send mode is refused, in checking order. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SendModeRefusal { + /// The value does not fit the wallet action's 8-bit mode. + OutOfRange, + /// The whole-balance amount keeps its own carry-all mode. + WholeBalanceAmount, + /// Flag 4 or 8 is not a send-mode flag. + UndefinedFlag, + /// +128 sends the whole balance instead of the message value. + CarryAllBalance, + /// +64 adds the remaining inbound value to the message value. + CarryInboundValue, + /// +32 requests destruction of the wallet account. + DestroyAccount, + /// An external message needs +2, which keeps a failed action replay-safe. + MissingIgnoreErrors, +} + +impl std::fmt::Display for SendModeRefusal { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::OutOfRange => "the mode does not fit the wallet action's 8-bit field", + Self::WholeBalanceAmount => "a whole-balance transfer keeps its own send mode", + Self::UndefinedFlag => "the mode sets flag 4 or 8, which no send mode defines", + Self::CarryAllBalance => { + "flag 128 would send the whole balance instead of the message value" + } + Self::CarryInboundValue => { + "flag 64 would add the remaining inbound value to the message value" + } + Self::DestroyAccount => "flag 32 would request destruction of the wallet account", + Self::MissingIgnoreErrors => "an external wallet message needs flag 2 (ignore errors)", + }) + } } /// Requests one signed wallet transfer. @@ -165,21 +288,36 @@ pub struct SendRequest { /// /// The engine resolves one fresh wallet sequence number and one expiration /// timestamp, then signs the transfer as both an incoming external message and -/// an owner-signed internal message. It does not submit or persist either BOC. +/// an owner-signed internal message, the latter with [`Self::gasless_messages`] +/// when given. It does not submit or persist either BOC. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, uniffi::Record)] #[serde(rename_all = "camelCase")] pub struct PrepareTransferRequest { /// A unique identifier chosen by the application for the prepared transfer. pub operation_id: NonEmptyString, - /// The immutable messages and expiration policy covered by both signatures. + /// The immutable external-form messages and the expiration policy of both + /// forms. The internal form signs these messages too unless + /// [`Self::gasless_messages`] is given. pub intent: SendIntent, + /// Optional messages for the internal form instead of the intent's. + /// + /// `None` signs the intent's messages in both forms. Given messages are + /// signed exactly, in the internal form only, under the same `seqno` and + /// `valid_until` as the external form. Their explicit send modes need not + /// include +2, and an empty list is refused. The exact total of each form + /// must fit the fresh balance, fees excluded; a whole-balance form has no + /// exact total to check. + #[serde(default)] + #[uniffi(default = None)] + pub gasless_messages: Option>, } /// Two signed delivery forms prepared from the same wallet state. /// /// Both BOCs cover the same `seqno` and `valid_until`, so they are alternative -/// representations of one transfer. The caller must hand off only the delivery -/// form selected by its server. This result is not written to the send journal. +/// forms of one operation, possibly with different messages. The caller may +/// send both to its server to select one for on-chain execution. This result +/// is not written to the send journal. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, uniffi::Record)] #[serde(rename_all = "camelCase")] pub struct PreparedTransfer { @@ -255,6 +393,18 @@ pub struct SignMessageResult { pub struct SendPreviewRequest { /// The same immutable intent accepted by the signed-send operation. pub intent: SendIntent, + /// Whether a funds refusal of an exact-value intent may carry the wallet + /// fee of this exact operation. + /// + /// `false` previews exactly as before. With `true`, a value above the + /// fresh balance is still refused, but only after the engine tried to + /// establish the fee from the provider's emulations, and an emulation in + /// which the wallet does not create every message is never a successful + /// preview. A refusal carries the fee only when the emulations established + /// it. Intents with a whole-balance message ignore this field. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + #[uniffi(default = false)] + pub estimate_shortfall: bool, } /// An informational transfer preview produced without unlocking the wallet secret. @@ -279,6 +429,26 @@ pub struct SendPreview { pub message_boc_base64: Boc, /// The bounded Toncenter emulation summary shown before authorization. pub emulation: SendEmulation, + /// What the wallet spends beyond the exact message values, in nanograms. + /// + /// Present only on a preview that asked for the operation's fee with + /// [`SendPreviewRequest::estimate_shortfall`] for an exact-value intent; + /// such a preview succeeds only when the engine established this amount. + /// It is not [`SendEmulation::wallet_fees_nanograms`], the root wallet + /// transaction fee: with send mode +1 (pay fees separately: modes 3 and + /// 19, and the mode-less exact value) it adds the part of the forwarding + /// fee that travels with each message, and without +1 (modes 2 and 18) + /// the forwarding fee comes out of the message value instead, so it is + /// that fee less the action fee. The values plus this amount fit the + /// fresh balance, equality included; one nanogram less refuses. + /// + /// `None` means the amount is unknown, never zero: every default preview, + /// every whole-balance intent and every BOC preview leaves it absent. + /// Default intent previews also refuse an emulation in which the wallet + /// did not create every outgoing message. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[uniffi(default = None)] + pub operation_spend_nanograms: Option, } /// A validated internal-message signing preview without submission fee claims. @@ -454,9 +624,11 @@ pub struct SendResult { #[cfg(test)] mod tests { use super::{ - SendAmount, SendExpiration, SendIntent, SendMessage, SendMessageBody, SendRequest, + PrepareTransferRequest, SendAmount, SendEmulation, SendExpiration, SendIntent, + SendIntentError, SendMessage, SendMessageBody, SendModeRefusal, SendPreview, + SendPreviewRequest, SendRequest, }; - use crate::{Boc, NonEmptyString, TonAddressString}; + use crate::{Boc, NonEmptyString, TonAddressString, UnsignedDecimalString, WalletClientError}; use ton::ton_core::cell::TonCell; #[test] @@ -548,6 +720,454 @@ mod tests { assert!(!decoded.intent.messages[0].bounce); } + /// Keeps mode-less JSON unchanged and preserves an explicit signed mode. + #[test] + fn send_mode_json_is_omitted_when_absent_and_round_trips_when_present() { + let request = send_request(SendExpiration::EngineDefault, SendMessageBody::Empty); + let json = serde_json::to_value(&request).expect("send request serializes"); + assert!(json["intent"]["messages"][0].get("sendMode").is_none()); + + let mut explicit = request; + for mode in [-1, 19, 256] { + explicit.intent.messages[0].send_mode = Some(mode); + let json = serde_json::to_value(&explicit).expect("send request serializes"); + assert_eq!(json["intent"]["messages"][0]["sendMode"], mode); + + let decoded: SendRequest = + serde_json::from_value(json).expect("send request deserializes"); + assert_eq!(decoded, explicit); + } + } + + /// Keeps a default preview request's JSON unchanged, reads one without + /// the field as a default request and round-trips an explicit opt-in. + #[test] + fn preview_request_json_omits_a_default_shortfall_estimate() { + let intent = send_request(SendExpiration::EngineDefault, SendMessageBody::Empty).intent; + let request = SendPreviewRequest { + intent: intent.clone(), + estimate_shortfall: false, + }; + let json = serde_json::to_value(&request).expect("preview request serializes"); + assert_eq!(json, serde_json::json!({ "intent": intent })); + let decoded: SendPreviewRequest = + serde_json::from_value(json).expect("preview request deserializes"); + assert_eq!(decoded, request); + + let opted = SendPreviewRequest { + estimate_shortfall: true, + ..request + }; + let json = serde_json::to_value(&opted).expect("preview request serializes"); + assert_eq!(json["estimateShortfall"], true); + let decoded: SendPreviewRequest = + serde_json::from_value(json).expect("preview request deserializes"); + assert_eq!(decoded, opted); + } + + /// Reads a preview request written before the shortfall field existed, + /// or with an explicit `false`, as a default request. + #[test] + fn legacy_preview_request_json_reads_as_a_default_request() { + let legacy = r#"{"intent":{"expiration":{"kind":"engineDefault"},"messages":[{"destination":"0:2222222222222222222222222222222222222222222222222222222222222222","amount":{"kind":"exact","nanograms":"1"},"body":{"kind":"empty"},"bounce":false,"stateInit":null}]}}"#; + let request: SendPreviewRequest = + serde_json::from_str(legacy).expect("legacy preview request decodes"); + assert!(!request.estimate_shortfall); + assert_eq!( + request.intent, + send_request(SendExpiration::EngineDefault, SendMessageBody::Empty).intent + ); + assert_eq!( + serde_json::to_string(&request).expect("preview request serializes"), + legacy + ); + + let mut explicit: serde_json::Value = + serde_json::from_str(legacy).expect("legacy JSON parses"); + explicit["estimateShortfall"] = false.into(); + let decoded: SendPreviewRequest = + serde_json::from_value(explicit).expect("explicit default decodes"); + assert_eq!(decoded, request); + } + + /// Keeps a preview without a spend as it serialized before the field + /// existed, reads that JSON as `None` and round-trips a positive spend. + #[test] + fn preview_json_omits_an_absent_operation_spend() { + let preview = SendPreview { + messages: send_request(SendExpiration::EngineDefault, SendMessageBody::Empty) + .intent + .messages, + valid_until: 1_900_000_000, + message_boc_base64: Boc::try_from(TonCell::EMPTY_BOC.to_vec()).expect("valid BOC"), + emulation: SendEmulation { + mc_block_seqno: 104_737_326, + wallet_fees_nanograms: UnsignedDecimalString::from(419_380_u64), + trace_fees_nanograms: UnsignedDecimalString::from(419_380_u64), + transaction_count: 1, + actions: Vec::new(), + transactions: Vec::new(), + trace_succeeded: true, + is_incomplete: false, + }, + operation_spend_nanograms: None, + }; + let json = serde_json::to_value(&preview).expect("preview serializes"); + let mut fields = json + .as_object() + .expect("preview object") + .keys() + .map(String::as_str) + .collect::>(); + fields.sort_unstable(); + assert_eq!( + fields, + ["emulation", "messageBocBase64", "messages", "validUntil"] + ); + let decoded: SendPreview = serde_json::from_value(json).expect("preview deserializes"); + assert_eq!(decoded, preview); + + let opted = SendPreview { + operation_spend_nanograms: Some(UnsignedDecimalString::from(468_270_u64)), + ..preview + }; + let json = serde_json::to_value(&opted).expect("preview serializes"); + assert_eq!(json["operationSpendNanograms"], "468270"); + assert_eq!(json["emulation"]["walletFeesNanograms"], "419380"); + let decoded: SendPreview = serde_json::from_value(json).expect("preview deserializes"); + assert_eq!(decoded, opted); + } + + /// Reads a message persisted before send modes existed as a mode-less one. + #[test] + fn legacy_send_message_json_reads_without_a_send_mode() { + let legacy = r#"{"destination":"0:2222222222222222222222222222222222222222222222222222222222222222","amount":{"kind":"exact","nanograms":"1"},"body":{"kind":"empty"},"bounce":false,"stateInit":null}"#; + + let message: SendMessage = serde_json::from_str(legacy).expect("legacy message decodes"); + + assert_eq!(message.send_mode, None); + assert_eq!( + serde_json::to_string(&message).expect("message serializes"), + legacy + ); + } + + /// Reads a preparation request without a gasless list as `None` and keeps + /// a supplied list, including an explicit empty one, exactly. + #[test] + fn prepare_transfer_json_keeps_an_absent_empty_or_distinct_gasless_list() { + let legacy = r#"{"operationId":"operation","intent":{"expiration":{"kind":"engineDefault"},"messages":[{"destination":"0:2222222222222222222222222222222222222222222222222222222222222222","amount":{"kind":"exact","nanograms":"1"},"body":{"kind":"empty"},"bounce":false,"stateInit":null}]}}"#; + let request = PrepareTransferRequest { + operation_id: NonEmptyString::try_from("operation").expect("valid operation id"), + intent: send_request(SendExpiration::EngineDefault, SendMessageBody::Empty).intent, + gasless_messages: None, + }; + + let decoded: PrepareTransferRequest = + serde_json::from_str(legacy).expect("request without a gasless list decodes"); + assert_eq!(decoded, request); + + let payload = Boc::try_from(TonCell::EMPTY_BOC.to_vec()).expect("valid payload BOC"); + let distinct = PrepareTransferRequest { + gasless_messages: Some(vec![ + SendMessage { + destination: TonAddressString::try_from( + "0:3333333333333333333333333333333333333333333333333333333333333333", + ) + .expect("valid destination"), + amount: SendAmount::exact("700").expect("valid amount"), + body: SendMessageBody::RawPayload { + boc: payload.clone(), + }, + bounce: true, + state_init: Some(payload), + send_mode: Some(0), + }, + SendMessage { + destination: TonAddressString::try_from( + "0:4444444444444444444444444444444444444444444444444444444444444444", + ) + .expect("valid destination"), + amount: SendAmount::exact("300").expect("valid amount"), + body: SendMessageBody::Comment { + text: "gasless".to_owned(), + }, + bounce: false, + state_init: None, + send_mode: Some(18), + }, + ]), + ..request.clone() + }; + let json = serde_json::to_value(&distinct).expect("request serializes"); + assert_eq!( + json["gaslessMessages"].as_array().map(Vec::len), + Some(2), + "{json}" + ); + let decoded: PrepareTransferRequest = + serde_json::from_value(json).expect("request deserializes"); + assert_eq!(decoded, distinct); + + let mut empty = serde_json::to_value(&request).expect("request serializes"); + empty["gaslessMessages"] = serde_json::json!([]); + let decoded: PrepareTransferRequest = + serde_json::from_value(empty).expect("request with an empty list deserializes"); + assert_eq!(decoded.gasless_messages, Some(Vec::new())); + } + + /// Lists the explicit modes one exact-value message accepts under `validate`. + /// + /// Sweeps every value around the 8-bit action field plus the `i32` + /// extremes and 1024, the fee-estimation flag that only `SENDMSG` defines. + fn accepted_send_modes( + validate: impl Fn(&SendIntent) -> Result, SendIntentError>, + ) -> Vec { + (-1..=256) + .chain([i32::MIN, 1024, i32::MAX]) + .filter(|&mode| { + let mut request = + send_request(SendExpiration::EngineDefault, SendMessageBody::Empty); + request.intent.messages[0].send_mode = Some(mode); + let accepted = validate(&request.intent); + if let Ok(total) = &accepted { + assert_eq!(total, &Some(UnsignedDecimalString::from(1_u64))); + } + accepted.is_ok() + }) + .collect() + } + + #[test] + fn explicit_send_modes_accept_only_the_literal_sets() { + assert_eq!( + accepted_send_modes(SendIntent::exact_value_total), + [0, 1, 2, 3, 16, 17, 18, 19] + ); + assert_eq!( + accepted_send_modes(SendIntent::exact_value_total_for_external), + [2, 3, 18, 19] + ); + } + + /// Returns a one-message intent whose message names `mode` explicitly. + fn intent_with_mode(amount: SendAmount, mode: i32) -> SendIntent { + let mut intent = send_request(SendExpiration::EngineDefault, SendMessageBody::Empty).intent; + intent.messages[0].amount = amount; + intent.messages[0].send_mode = Some(mode); + intent + } + + /// Names the supplied signed value and the first matching rule in order. + #[test] + fn refused_send_modes_name_the_supplied_value_and_the_first_reason() { + use SendModeRefusal::{ + CarryAllBalance, CarryInboundValue, DestroyAccount, MissingIgnoreErrors, OutOfRange, + UndefinedFlag, + }; + + let refused_in_every_form = [ + (i32::MIN, OutOfRange), + (-1, OutOfRange), + (256, OutOfRange), + (1024, OutOfRange), + (i32::MAX, OutOfRange), + (4, UndefinedFlag), + (8, UndefinedFlag), + (36, UndefinedFlag), + (255, UndefinedFlag), + (128, CarryAllBalance), + (130, CarryAllBalance), + (160, CarryAllBalance), + (192, CarryAllBalance), + (64, CarryInboundValue), + (66, CarryInboundValue), + (96, CarryInboundValue), + (32, DestroyAccount), + (34, DestroyAccount), + ]; + for (mode, reason) in refused_in_every_form { + let intent = intent_with_mode(SendAmount::exact("1").expect("valid amount"), mode); + let refused = Err(SendIntentError::UnsupportedSendMode { mode, reason }); + + assert_eq!(intent.exact_value_total(), refused, "mode {mode}"); + assert_eq!( + intent.exact_value_total_for_external(), + refused, + "mode {mode}" + ); + } + + for mode in [0, 1, 16, 17] { + let intent = intent_with_mode(SendAmount::exact("1").expect("valid amount"), mode); + + assert_eq!( + intent.exact_value_total(), + Ok(Some(UnsignedDecimalString::from(1_u64))), + "mode {mode}" + ); + assert_eq!( + intent.exact_value_total_for_external(), + Err(SendIntentError::UnsupportedSendMode { + mode, + reason: MissingIgnoreErrors, + }), + "mode {mode}" + ); + } + } + + /// Keeps the whole-balance form on its own mode instead of a served one. + #[test] + fn whole_balance_messages_refuse_every_explicit_send_mode() { + for mode in [0, 2, 3, 19, 128, 130] { + let intent = intent_with_mode(SendAmount::All, mode); + let refused = Err(SendIntentError::UnsupportedSendMode { + mode, + reason: SendModeRefusal::WholeBalanceAmount, + }); + + assert_eq!(intent.exact_value_total(), refused, "mode {mode}"); + assert_eq!( + intent.exact_value_total_for_external(), + refused, + "mode {mode}" + ); + } + + let unrepresentable = intent_with_mode(SendAmount::All, 256); + assert_eq!( + unrepresentable.exact_value_total(), + Err(SendIntentError::UnsupportedSendMode { + mode: 256, + reason: SendModeRefusal::OutOfRange, + }) + ); + + let mut mode_less = intent_with_mode(SendAmount::All, 130); + mode_less.messages[0].send_mode = None; + assert_eq!(mode_less.exact_value_total(), Ok(None)); + assert_eq!(mode_less.exact_value_total_for_external(), Ok(None)); + } + + /// Refuses a whole batch when only a later message names a refused mode. + #[test] + fn a_refused_later_message_refuses_the_whole_batch() { + let mut intent = intent_with_mode(SendAmount::exact("1").expect("valid amount"), 3); + let second = SendMessage { + amount: SendAmount::exact("2").expect("valid amount"), + send_mode: Some(64), + ..intent.messages[0].clone() + }; + intent.messages.push(second); + let carries_inbound_value = Err(SendIntentError::UnsupportedSendMode { + mode: 64, + reason: SendModeRefusal::CarryInboundValue, + }); + assert_eq!(intent.exact_value_total(), carries_inbound_value); + assert_eq!( + intent.exact_value_total_for_external(), + carries_inbound_value + ); + + intent.messages[1].send_mode = Some(1); + assert_eq!( + intent.exact_value_total(), + Ok(Some(UnsignedDecimalString::from(3_u64))) + ); + assert_eq!( + intent.exact_value_total_for_external(), + Err(SendIntentError::UnsupportedSendMode { + mode: 1, + reason: SendModeRefusal::MissingIgnoreErrors, + }) + ); + + intent.messages[1].send_mode = None; + let total = Ok(Some(UnsignedDecimalString::from(3_u64))); + assert_eq!(intent.exact_value_total(), total); + assert_eq!(intent.exact_value_total_for_external(), total); + } + + /// Converts each refusal into the public error with the original signed value. + #[test] + fn send_mode_refusals_convert_to_a_public_error_naming_the_signed_value() { + let cases = [ + ( + i32::MIN, + SendModeRefusal::OutOfRange, + "send mode -2147483648 is not supported: the mode does not fit the wallet action's 8-bit field", + ), + ( + -1, + SendModeRefusal::OutOfRange, + "send mode -1 is not supported: the mode does not fit the wallet action's 8-bit field", + ), + ( + i32::MAX, + SendModeRefusal::OutOfRange, + "send mode 2147483647 is not supported: the mode does not fit the wallet action's 8-bit field", + ), + ( + 130, + SendModeRefusal::WholeBalanceAmount, + "send mode 130 is not supported: a whole-balance transfer keeps its own send mode", + ), + ( + 12, + SendModeRefusal::UndefinedFlag, + "send mode 12 is not supported: the mode sets flag 4 or 8, which no send mode defines", + ), + ( + 192, + SendModeRefusal::CarryAllBalance, + "send mode 192 is not supported: flag 128 would send the whole balance instead of the message value", + ), + ( + 64, + SendModeRefusal::CarryInboundValue, + "send mode 64 is not supported: flag 64 would add the remaining inbound value to the message value", + ), + ( + 32, + SendModeRefusal::DestroyAccount, + "send mode 32 is not supported: flag 32 would request destruction of the wallet account", + ), + ( + 17, + SendModeRefusal::MissingIgnoreErrors, + "send mode 17 is not supported: an external wallet message needs flag 2 (ignore errors)", + ), + ]; + for (mode, reason, display) in cases { + let error = + WalletClientError::from(SendIntentError::UnsupportedSendMode { mode, reason }); + + let WalletClientError::UnsupportedSendMode { + mode: public_mode, + diagnostic, + } = &error + else { + panic!("mode {mode} converted to {error:?}"); + }; + assert_eq!(*public_mode, mode); + assert_eq!( + display.strip_prefix(&format!("send mode {mode} is not supported: ")), + Some(diagnostic.as_str()) + ); + assert_eq!(error.to_string(), display); + } + + assert_eq!( + WalletClientError::from(SendIntentError::InvalidMessageCount), + WalletClientError::InvalidSendRequest + ); + assert_eq!( + WalletClientError::from(SendIntentError::WholeBalanceInBatch), + WalletClientError::InvalidSendRequest + ); + } + /// Builds one public send request for serialization tests. fn send_request(expiration: SendExpiration, body: SendMessageBody) -> SendRequest { SendRequest { @@ -564,6 +1184,7 @@ mod tests { body, bounce: false, state_init: None, + send_mode: None, }], }, } diff --git src/engine/emulation.rs src/engine/emulation.rs index 2fe02bf..101b7d6 100644 --- src/engine/emulation.rs +++ src/engine/emulation.rs @@ -13,7 +13,8 @@ use crate::types::Boc; use crate::{ Base64Hash, DomainError, ErrorCategory, ErrorCode, HttpHeader, HttpMethod, HttpRequest, HttpRequestId, NonEmptyString, RetryAdvice, SendEmulation, SendEmulationAction, - SendEmulationTransaction, TonAddressString, WalletClientConfig, WalletClientError, + SendEmulationTransaction, TonAddressString, UnsignedDecimalString, WalletClientConfig, + WalletClientError, }; #[derive(Debug)] @@ -22,12 +23,121 @@ pub(super) struct EvaluatedEmulation { pub(super) wallet_succeeded: bool, pub(super) compute_exit_code: Option, pub(super) action_result_code: Option, + /// The root wallet transaction's message delivery, when its counters are usable. + pub(super) delivery: Option, + /// The length of the root wallet transaction's `out_msgs` list, when it is + /// a list: one entry for each outgoing message the wallet created. + pub(super) out_messages: Option, + /// The root wallet transaction's fee components, when all of them are usable. + pub(super) composition: Option, + /// The root wallet transaction's forwarding fees, when both are usable. + pub(super) forwarding: Option, } +impl EvaluatedEmulation { + /// How the root wallet transaction delivered `messages` outgoing messages. + /// + /// The action counters decide when they are usable; only otherwise does + /// the length of the root's `out_msgs` list. `None` means that neither + /// records the delivery, never that nothing was created. + pub(super) fn message_creation(&self, messages: usize) -> Option { + let creation = if let Some(delivery) = self.delivery { + if delivery.created_all(messages) { + MessageCreation::Every + } else if delivery.skipped_all(messages) { + MessageCreation::Nothing + } else { + MessageCreation::Partial + } + } else { + match self.out_messages? { + created if created == messages => MessageCreation::Every, + 0 => MessageCreation::Nothing, + _ => MessageCreation::Partial, + } + }; + Some(creation) + } +} + +/// How the root wallet transaction delivered the requested outgoing messages. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum MessageCreation { + /// It created every message and skipped none. + Every, + /// It created none of them. + Nothing, + /// Any other delivery, such as only some of the messages. + Partial, +} + +/// How the root wallet transaction's action phase handled its actions. +/// +/// Read leniently from the answer: unusable counters leave this absent and +/// never change how the rest of the answer parses. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct RootDelivery { + /// `tot_actions`: every action in the wallet's action list. + pub(super) total_actions: u16, + /// `skipped_actions`: actions skipped under send mode +2. + pub(super) skipped_actions: u16, + /// `msgs_created`: outgoing messages the action phase created. + pub(super) messages_created: u16, +} + +impl RootDelivery { + /// Whether the wallet created each of `messages` outgoing messages and skipped none. + pub(super) fn created_all(self, messages: usize) -> bool { + usize::from(self.total_actions) == messages + && usize::from(self.messages_created) == messages + && self.skipped_actions == 0 + } + + /// Whether the wallet skipped each of `messages` outgoing messages and created none. + pub(super) fn skipped_all(self, messages: usize) -> bool { + usize::from(self.total_actions) == messages + && usize::from(self.skipped_actions) == messages + && self.messages_created == 0 + } +} + +/// Root wallet transaction fee components that only a shortfall quote reads. +/// +/// Read leniently from the answer, separately from [`RootDelivery`], so a +/// created operation keeps its fee even when one of these is unusable. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct RootComposition { + /// `total_action_fees`; the protocol omits it when it is zero. + pub(super) total_action_fees: BigUint, + /// The compute phase's `gas_used`. + pub(super) gas_used: BigUint, + /// `storage_fees_collected`; zero only when the storage phase is absent. + pub(super) storage_fees: BigUint, +} + +/// Root wallet transaction forwarding fees, from which a preview prices the +/// wallet's spend on the messages that this transaction created. +/// +/// Read leniently from the answer, separately from [`RootComposition`]: a +/// created operation needs neither its gas nor its storage fee. Whether the +/// values can price a message is decided where they are used. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct RootForwarding { + /// `total_action_fees`: the forwarding fees' part that the action phase + /// keeps; the protocol omits it when it is zero. + pub(super) total_action_fees: BigUint, + /// `total_fwd_fees`: the whole forwarding fees of the created messages, + /// which includes the action fees; the protocol omits it when it is zero. + pub(super) total_fwd_fees: BigUint, +} + +/// Builds the Emulate API request; `mc_block_seqno` pins the emulated state +/// to that masterchain block, and `None` asks for the current state. pub(super) fn build_emulation_request( config: &WalletClientConfig, id: HttpRequestId, signed_boc: &Boc, + mc_block_seqno: Option, ) -> Result { let body = serde_json::to_vec(&serde_json::json!({ "boc": signed_boc, @@ -36,7 +146,7 @@ pub(super) fn build_emulation_request( "include_address_book": false, "include_metadata": false, "with_actions": true, - "mc_block_seqno": null, + "mc_block_seqno": mc_block_seqno, })) .map_err(|_| WalletClientError::StateUnavailable)?; @@ -161,9 +271,77 @@ pub(super) fn parse_emulation( .action .as_ref() .and_then(|phase| phase.result_code), + delivery: root_delivery(&wallet.description), + out_messages: wallet.out_msgs.as_array().map(Vec::len), + composition: root_composition(&wallet.description), + forwarding: root_forwarding(&wallet.description), + }) +} + +fn root_delivery(description: &EmulatedTransactionDescription) -> Option { + let action = description.action.as_ref()?; + let count = |value: &serde_json::Value| u16::try_from(&lenient_unsigned(value)?).ok(); + Some(RootDelivery { + total_actions: count(&action.tot_actions)?, + skipped_actions: count(&action.skipped_actions)?, + messages_created: count(&action.msgs_created)?, + }) +} + +fn root_composition(description: &EmulatedTransactionDescription) -> Option { + let action = description.action.as_ref()?; + let compute = description.compute_ph.as_ref()?; + Some(RootComposition { + total_action_fees: maybe_nanograms(&action.total_action_fees)?, + gas_used: lenient_unsigned(&compute.gas_used)?, + storage_fees: match &description.storage_ph { + // `storage_ph:(Maybe TrStoragePhase)` absent: nothing was collected. + serde_json::Value::Null => BigUint::default(), + serde_json::Value::Object(phase) => { + lenient_unsigned(phase.get("storage_fees_collected")?)? + } + serde_json::Value::Bool(_) + | serde_json::Value::Number(_) + | serde_json::Value::String(_) + | serde_json::Value::Array(_) => return None, + }, + }) +} + +fn root_forwarding(description: &EmulatedTransactionDescription) -> Option { + let action = description.action.as_ref()?; + Some(RootForwarding { + total_action_fees: maybe_nanograms(&action.total_action_fees)?, + total_fwd_fees: maybe_nanograms(&action.total_fwd_fees)?, }) } +/// Reads a `(Maybe Grams)` fee that the protocol stores only when nonzero: +/// an absent or `null` value is zero, any other value reads as +/// [`lenient_unsigned`] does. +fn maybe_nanograms(value: &serde_json::Value) -> Option { + if value.is_null() { + Some(BigUint::default()) + } else { + lenient_unsigned(value) + } +} + +/// Reads a nonnegative integer that Toncenter encodes as a JSON number or as +/// a canonical decimal string; any other value is unusable. +fn lenient_unsigned(value: &serde_json::Value) -> Option { + match value { + serde_json::Value::Number(number) => number.as_u64().map(BigUint::from), + serde_json::Value::String(text) => UnsignedDecimalString::try_from(text.as_str()) + .ok() + .map(UnsignedDecimalString::into_biguint), + serde_json::Value::Null + | serde_json::Value::Bool(_) + | serde_json::Value::Array(_) + | serde_json::Value::Object(_) => None, + } +} + pub(super) fn is_message_not_accepted(error: &DomainError) -> bool { let diagnostic = error.developer_message.to_ascii_lowercase(); diagnostic.contains("external message") && diagnostic.contains("not accepted") @@ -277,25 +455,46 @@ struct EmulatedTransaction { account: String, total_fees: String, description: EmulatedTransactionDescription, + /// Read only for its length, leniently like the fields below. + #[serde(default)] + out_msgs: serde_json::Value, } +// The raw `serde_json::Value` fields are read leniently by `root_delivery`, +// `root_composition`, `root_forwarding` and `parse_emulation`: any JSON value +// deserializes, so they never change whether or how the rest of an answer +// parses. #[derive(Deserialize)] struct EmulatedTransactionDescription { aborted: Option, compute_ph: Option, action: Option, + #[serde(default)] + storage_ph: serde_json::Value, } #[derive(Deserialize)] struct EmulatedComputePhase { success: Option, exit_code: Option, + #[serde(default)] + gas_used: serde_json::Value, } #[derive(Deserialize)] struct EmulatedActionPhase { success: Option, result_code: Option, + #[serde(default)] + tot_actions: serde_json::Value, + #[serde(default)] + skipped_actions: serde_json::Value, + #[serde(default)] + msgs_created: serde_json::Value, + #[serde(default)] + total_action_fees: serde_json::Value, + #[serde(default)] + total_fwd_fees: serde_json::Value, } #[cfg(test)] @@ -304,7 +503,7 @@ mod tests { use super::*; use crate::types::Boc; - use crate::{Network, ProviderConfig, UnsignedDecimalString}; + use crate::{Network, ProviderConfig}; use ton::ton_core::cell::TonCell; const ADDRESS: &str = "0:1111111111111111111111111111111111111111111111111111111111111111"; @@ -313,7 +512,7 @@ mod tests { fn builds_the_emulate_trace_request_from_the_provider_base() { let config = config("https://provider.example/custom/"); let boc = Boc::try_from(TonCell::EMPTY_BOC.to_vec()).expect("valid BOC fixture"); - let request = build_emulation_request(&config, HttpRequestId { value: 9 }, &boc) + let request = build_emulation_request(&config, HttpRequestId { value: 9 }, &boc, None) .expect("emulation request must build"); let body: serde_json::Value = serde_json::from_slice(&request.body).expect("request body must be JSON"); @@ -328,6 +527,415 @@ mod tests { assert_eq!(body["with_actions"], true); } + /// An unpinned request keeps the previous body byte for byte; a pinned + /// one differs only by the block number. + #[test] + fn pins_the_emulated_state_only_when_a_block_is_given() { + let config = config("https://provider.example/"); + let boc = Boc::try_from(TonCell::EMPTY_BOC.to_vec()).expect("valid BOC fixture"); + let previous = serde_json::to_vec(&serde_json::json!({ + "boc": boc, + "ignore_chksig": true, + "include_code_data": false, + "include_address_book": false, + "include_metadata": false, + "with_actions": true, + "mc_block_seqno": null, + })) + .expect("previous body serializes"); + + let unpinned = build_emulation_request(&config, HttpRequestId { value: 1 }, &boc, None) + .expect("unpinned request builds"); + assert_eq!(unpinned.body, previous); + + let pinned = + build_emulation_request(&config, HttpRequestId { value: 1 }, &boc, Some(104_746_942)) + .expect("pinned request builds"); + let mut expected: serde_json::Value = + serde_json::from_slice(&previous).expect("previous body parses"); + expected["mc_block_seqno"] = serde_json::json!(104_746_942_u32); + assert_eq!( + serde_json::from_slice::(&pinned.body).expect("pinned body parses"), + expected + ); + } + + /// Reads the counters and fee components of a captured skipped answer, + /// and zero for a `total_action_fees` or storage phase the protocol omits. + #[test] + fn reads_the_root_delivery_and_fee_components() { + let source = TonAddressString::try_from(ADDRESS).expect("test address must parse"); + let mut root = transaction(ADDRESS, "396627", false, true, true, 0, 0); + root["description"]["storage_ph"] = serde_json::json!({ + "storage_fees_collected": "26", + "status_change": "unchanged" + }); + root["description"]["compute_ph"]["gas_used"] = serde_json::json!("3560"); + let action = &mut root["description"]["action"]; + action["tot_actions"] = serde_json::json!(1); + action["skipped_actions"] = serde_json::json!(1); + action["msgs_created"] = serde_json::json!(0); + action["total_action_fees"] = serde_json::json!("1666"); + + let parsed = parse(&root, &source).expect("answer parses"); + assert_eq!( + parsed.delivery, + Some(RootDelivery { + total_actions: 1, + skipped_actions: 1, + messages_created: 0, + }) + ); + let delivery = parsed.delivery.expect("delivery is present"); + assert!(delivery.skipped_all(1)); + assert!(!delivery.created_all(1)); + assert!(!delivery.skipped_all(2)); + assert_eq!( + parsed.composition, + Some(RootComposition { + total_action_fees: BigUint::from(1666_u32), + gas_used: BigUint::from(3560_u32), + storage_fees: BigUint::from(26_u32), + }) + ); + + let mut omitted = root.clone(); + let description = omitted["description"] + .as_object_mut() + .expect("description object"); + let _ = description.remove("storage_ph"); + let _ = description["action"] + .as_object_mut() + .expect("action object") + .remove("total_action_fees"); + let parsed = parse(&omitted, &source).expect("answer parses"); + assert_eq!( + parsed.composition, + Some(RootComposition { + total_action_fees: BigUint::default(), + gas_used: BigUint::from(3560_u32), + storage_fees: BigUint::default(), + }) + ); + } + + /// Reads the forwarding fees of captured created and skipped answers as + /// numbers or decimal strings, an omitted fee as zero, and leaves the + /// record absent for a malformed fee or a missing action phase; created + /// answers keep it without gas or storage fees, which only the + /// composition needs. The delivery and composition never depend on it. + #[test] + fn reads_the_root_forwarding_fees_leniently() { + let source = TonAddressString::try_from(ADDRESS).expect("test address must parse"); + let forwarding = |action: u32, total: u32| { + Some(RootForwarding { + total_action_fees: BigUint::from(action), + total_fwd_fees: BigUint::from(total), + }) + }; + // The captured mode-3 1e8 answer at block 104746942. + let mut created = transaction(ADDRESS, "419405", false, true, true, 0, 0); + created["description"]["storage_ph"] = serde_json::json!({ + "storage_fees_collected": "26", + "status_change": "unchanged" + }); + created["description"]["compute_ph"]["gas_used"] = serde_json::json!("3560"); + let action = &mut created["description"]["action"]; + action["tot_actions"] = serde_json::json!(1); + action["skipped_actions"] = serde_json::json!(0); + action["msgs_created"] = serde_json::json!(1); + action["total_action_fees"] = serde_json::json!("24444"); + action["total_fwd_fees"] = serde_json::json!("73334"); + let parsed = parse(&created, &source).expect("answer parses"); + assert_eq!(parsed.forwarding, forwarding(24_444, 73_334)); + assert!(parsed.composition.is_some()); + let delivery = parsed.delivery; + assert!(delivery.is_some_and(|delivery| delivery.created_all(1))); + + let mut numbers = created.clone(); + numbers["description"]["action"]["total_action_fees"] = serde_json::json!(24_444); + numbers["description"]["action"]["total_fwd_fees"] = serde_json::json!(73_334); + assert_eq!( + parse(&numbers, &source).expect("answer parses").forwarding, + forwarding(24_444, 73_334) + ); + + // A skipped answer reports its fine and a `null` forwarding total. + let mut skipped = created.clone(); + skipped["description"]["action"]["skipped_actions"] = serde_json::json!(1); + skipped["description"]["action"]["msgs_created"] = serde_json::json!(0); + skipped["description"]["action"]["total_action_fees"] = serde_json::json!("1666"); + skipped["description"]["action"]["total_fwd_fees"] = serde_json::Value::Null; + assert_eq!( + parse(&skipped, &source).expect("answer parses").forwarding, + forwarding(1_666, 0) + ); + let mut omitted = skipped.clone(); + let _ = omitted["description"]["action"] + .as_object_mut() + .expect("action object") + .remove("total_fwd_fees"); + assert_eq!( + parse(&omitted, &source).expect("answer parses").forwarding, + forwarding(1_666, 0) + ); + + for value in [ + serde_json::json!(-73_334), + serde_json::json!(73_334.5), + serde_json::json!("073334"), + serde_json::json!("+73334"), + serde_json::json!("0x11e76"), + serde_json::json!([73_334]), + serde_json::json!({ "value": 73_334 }), + serde_json::json!(true), + ] { + for field in ["total_action_fees", "total_fwd_fees"] { + let mut root = created.clone(); + root["description"]["action"][field] = value.clone(); + let parsed = parse(&root, &source).expect("answer still parses"); + assert_eq!(parsed.forwarding, None, "{field} {value}"); + assert_eq!(parsed.delivery, delivery, "{field} {value}"); + if field == "total_fwd_fees" { + assert!(parsed.composition.is_some(), "{value}"); + } + } + } + + // Gas and storage fees are not part of the forwarding record. + let mut bare = created.clone(); + let description = bare["description"] + .as_object_mut() + .expect("description object"); + let _ = description.remove("storage_ph"); + let _ = description["compute_ph"] + .as_object_mut() + .expect("compute object") + .remove("gas_used"); + let parsed = parse(&bare, &source).expect("answer parses"); + assert_eq!(parsed.composition, None); + assert_eq!(parsed.forwarding, forwarding(24_444, 73_334)); + + let mut no_action = created; + no_action["description"]["action"] = serde_json::Value::Null; + assert_eq!( + parse(&no_action, &source) + .expect("answer parses") + .forwarding, + None + ); + } + + /// Unusable new fields leave the rest of the answer, and so every default + /// preview, exactly as without them; they only make the reading absent. + #[test] + fn unusable_delivery_fields_never_change_the_default_parse() { + let source = TonAddressString::try_from(ADDRESS).expect("test address must parse"); + let plain = transaction(ADDRESS, "11", false, true, true, 0, 0); + let baseline = parse(&plain, &source).expect("plain answer parses"); + assert_eq!(baseline.delivery, None); + assert_eq!(baseline.out_messages, None); + assert_eq!(baseline.composition, None); + // Both omitted `(Maybe Grams)` fees read as zero; admission decides. + assert_eq!( + baseline.forwarding, + Some(RootForwarding { + total_action_fees: BigUint::default(), + total_fwd_fees: BigUint::default(), + }) + ); + + let unusable = [ + serde_json::json!(-1), + serde_json::json!(1.5), + serde_json::json!("01"), + serde_json::json!("+1"), + serde_json::json!("x"), + serde_json::json!(65_536), + serde_json::json!([1]), + serde_json::json!({ "value": 1 }), + serde_json::json!(true), + ]; + for value in unusable { + let mut root = plain.clone(); + root["out_msgs"] = value.clone(); + root["description"]["storage_ph"] = value.clone(); + root["description"]["compute_ph"]["gas_used"] = value.clone(); + for field in [ + "tot_actions", + "skipped_actions", + "msgs_created", + "total_action_fees", + "total_fwd_fees", + ] { + root["description"]["action"][field] = value.clone(); + } + let parsed = parse(&root, &source).expect("answer still parses"); + assert_eq!(parsed.summary, baseline.summary, "{value}"); + assert_eq!(parsed.wallet_succeeded, baseline.wallet_succeeded); + assert_eq!(parsed.delivery, None, "{value}"); + let list_length = value.as_array().map(Vec::len); + assert_eq!(parsed.out_messages, list_length, "{value}"); + assert_eq!(parsed.composition, None, "{value}"); + // Only the uint16-overflowing count is a valid fee. + let forwarding = (value == serde_json::json!(65_536)).then(|| RootForwarding { + total_action_fees: BigUint::from(65_536_u32), + total_fwd_fees: BigUint::from(65_536_u32), + }); + assert_eq!(parsed.forwarding, forwarding, "{value}"); + } + + // A present storage phase without its collected fee is unknown, not zero. + let mut root = plain; + root["description"]["storage_ph"] = serde_json::json!({ "status_change": "unchanged" }); + root["description"]["compute_ph"]["gas_used"] = serde_json::json!("3560"); + root["description"]["action"]["total_action_fees"] = serde_json::json!("1666"); + assert_eq!( + parse(&root, &source).expect("answer parses").composition, + None + ); + } + + /// A counter beyond the TL-B `uint16` range, as a number or as a decimal + /// string, leaves the delivery unknown; the unbounded fee components keep + /// their reading, and the largest `uint16` is still a count. + #[test] + fn counter_overflow_leaves_the_delivery_unknown() { + let source = TonAddressString::try_from(ADDRESS).expect("test address must parse"); + let root = |skipped: serde_json::Value| { + let mut root = transaction(ADDRESS, "396627", false, true, true, 0, 0); + root["description"]["compute_ph"]["gas_used"] = serde_json::json!("3560"); + let action = &mut root["description"]["action"]; + action["tot_actions"] = serde_json::json!(1); + action["skipped_actions"] = skipped; + action["msgs_created"] = serde_json::json!(0); + action["total_action_fees"] = serde_json::json!("1666"); + root + }; + let composition = Some(RootComposition { + total_action_fees: BigUint::from(1666_u32), + gas_used: BigUint::from(3560_u32), + storage_fees: BigUint::default(), + }); + for value in [ + serde_json::json!(65_536), + serde_json::json!(u64::MAX), + serde_json::json!("18446744073709551616"), + serde_json::json!(1e20), + ] { + let parsed = parse(&root(value.clone()), &source).expect("answer parses"); + assert_eq!(parsed.delivery, None, "{value}"); + assert_eq!(parsed.composition, composition, "{value}"); + } + let parsed = parse(&root(serde_json::json!("65535")), &source).expect("answer parses"); + assert_eq!( + parsed.delivery, + Some(RootDelivery { + total_actions: 1, + skipped_actions: u16::MAX, + messages_created: 0, + }) + ); + } + + /// Usable counters decide the message creation even beside a missing or + /// disagreeing `out_msgs` list; only without them does the list's length + /// decide, and without either the creation is unknown, never "none". + #[test] + fn counters_decide_the_message_creation_before_the_output_list() { + use MessageCreation::{Every, Nothing, Partial}; + + let source = TonAddressString::try_from(ADDRESS).expect("test address must parse"); + let entry = serde_json::json!({ "source": ADDRESS, "destination": ADDRESS }); + let list = |length: usize| serde_json::Value::Array(vec![entry.clone(); length]); + let root = |counters: Option<(u16, u16, u16)>, out_msgs: Option| { + let mut root = transaction(ADDRESS, "11", false, true, true, 0, 0); + if let Some((total, skipped, created)) = counters { + let action = &mut root["description"]["action"]; + action["tot_actions"] = total.into(); + action["skipped_actions"] = skipped.into(); + action["msgs_created"] = created.into(); + } + if let Some(out_msgs) = out_msgs { + root["out_msgs"] = out_msgs; + } + root + }; + // Counters, output list, message count and the expected creation. + let rows = [ + (Some((1, 0, 1)), Some(list(1)), 1, Some(Every)), + (Some((1, 0, 1)), None, 1, Some(Every)), + ( + Some((1, 0, 1)), + Some(serde_json::json!("x")), + 1, + Some(Every), + ), + (Some((1, 0, 1)), Some(list(0)), 1, Some(Every)), + (Some((1, 1, 0)), Some(list(1)), 1, Some(Nothing)), + (Some((1, 1, 0)), None, 1, Some(Nothing)), + (Some((1, 1, 1)), Some(list(1)), 1, Some(Partial)), + (Some((2, 1, 1)), Some(list(1)), 2, Some(Partial)), + (Some((2, 0, 2)), Some(list(2)), 2, Some(Every)), + (Some((2, 2, 0)), Some(list(0)), 2, Some(Nothing)), + (Some((1, 0, 1)), Some(list(1)), 2, Some(Partial)), + (None, Some(list(1)), 1, Some(Every)), + (None, Some(list(0)), 1, Some(Nothing)), + (None, Some(list(2)), 2, Some(Every)), + (None, Some(list(1)), 2, Some(Partial)), + (None, Some(list(0)), 2, Some(Nothing)), + (None, Some(list(2)), 1, Some(Partial)), + (None, None, 1, None), + (None, Some(serde_json::Value::Null), 1, None), + (None, Some(serde_json::json!({ "0": entry })), 1, None), + (None, Some(serde_json::json!(1)), 1, None), + (None, Some(serde_json::json!("[]")), 1, None), + ]; + for (counters, out_msgs, messages, expected) in rows { + let label = format!("{counters:?} {out_msgs:?} {messages}"); + let parsed = parse(&root(counters, out_msgs), &source).expect("answer parses"); + assert_eq!(parsed.message_creation(messages), expected, "{label}"); + } + + // Unusable counters fall back to the list exactly like absent ones. + for counter in [ + serde_json::json!(-1), + serde_json::json!(1.5), + serde_json::json!("one"), + serde_json::json!(65_536), + serde_json::json!("18446744073709551616"), + serde_json::Value::Null, + ] { + for (out_msgs, expected) in [ + (Some(list(1)), Some(Every)), + (Some(list(0)), Some(Nothing)), + (None, None), + ] { + let mut root = root(Some((1, 0, 1)), out_msgs); + root["description"]["action"]["msgs_created"] = counter.clone(); + let parsed = parse(&root, &source).expect("answer parses"); + assert_eq!(parsed.delivery, None, "{counter}"); + assert_eq!(parsed.message_creation(1), expected, "{counter}"); + } + } + } + + fn parse( + root: &serde_json::Value, + source: &TonAddressString, + ) -> Result { + parse_emulation( + &serde_json::to_vec(&serde_json::json!({ + "mc_block_seqno": 17, + "trace": { "tx_hash": "root" }, + "transactions": { "root": root }, + "is_incomplete": false, + })) + .expect("fixture must serialize"), + source, + ) + } + #[test] fn parses_fees_and_detects_a_failed_child_transaction() { let source = TonAddressString::try_from(ADDRESS).expect("test address must parse"); @@ -516,12 +1124,20 @@ mod tests { compute_ph: compute.map(|(success, exit_code)| EmulatedComputePhase { success: Some(success), exit_code: Some(exit_code), + gas_used: serde_json::Value::Null, }), action: action.map(|(success, result_code)| EmulatedActionPhase { success: Some(success), result_code: Some(result_code), + tot_actions: serde_json::Value::Null, + skipped_actions: serde_json::Value::Null, + msgs_created: serde_json::Value::Null, + total_action_fees: serde_json::Value::Null, + total_fwd_fees: serde_json::Value::Null, }), + storage_ph: serde_json::Value::Null, }, + out_msgs: serde_json::Value::Null, } } diff --git src/engine/nft_transfer.rs src/engine/nft_transfer.rs index c727fc4..93bf6c7 100644 --- src/engine/nft_transfer.rs +++ src/engine/nft_transfer.rs @@ -34,6 +34,7 @@ impl WalletClient { let preview = self .preview_send(SendPreviewRequest { intent: canonical.intent, + estimate_shortfall: false, }) .await?; validate_nft_emulation(&preview, &request.intent.nft_address)?; @@ -305,6 +306,7 @@ mod tests { trace_succeeded: true, is_incomplete: false, }, + operation_spend_nanograms: None, } } diff --git src/engine/prepare_transfer.rs src/engine/prepare_transfer.rs index 50d5caf..137bac5 100644 --- src/engine/prepare_transfer.rs +++ src/engine/prepare_transfer.rs @@ -5,7 +5,8 @@ use crate::transport::build_toncenter_v2_request; use crate::wallet::send::FreshSendAccount; use crate::wallet::transfer::{derive_source, prepare_transfer_pair}; use crate::{ - AccountStatus, PrepareTransferRequest, PreparedTransfer, SendRequest, WalletClientError, + AccountStatus, PrepareTransferRequest, PreparedTransfer, SendIntent, SendRequest, + WalletClientError, }; use super::WalletClient; @@ -21,18 +22,39 @@ impl WalletClient { /// /// The client fetches account state and `seqno` once, resolves one /// `valid_until`, and unlocks the protected phrase once. Both returned BOCs - /// therefore authorize the same transfer and are mutually exclusive + /// therefore share one `seqno` and are mutually exclusive /// delivery alternatives. This method does not read or write the send /// journal and does not submit either message. + /// + /// The external BOC signs the request's intent. The internal BOC signs + /// [`PrepareTransferRequest::gasless_messages`] when given, otherwise the + /// same intent. pub async fn prepare_transfer( &self, request: PrepareTransferRequest, ) -> Result { - let requested = request + let normal_requested = request .intent - .exact_value_total() - .map_err(|_| WalletClientError::InvalidSendRequest)?; + .exact_value_total_for_external() + .map_err(WalletClientError::from)?; + let gasless_intent = request.gasless_messages.map(|messages| SendIntent { + expiration: request.intent.expiration.clone(), + messages, + }); + let gasless_requested = gasless_intent + .as_ref() + .map(SendIntent::exact_value_total) + .transpose() + .map_err(WalletClientError::from)? + .flatten(); + // The server executes at most one form, so the largest exact total must fit. + let requested = normal_requested.into_iter().chain(gasless_requested).max(); let operation_id = request.operation_id.clone(); + let gasless_request = gasless_intent.map(|intent| SendRequest { + operation_id: request.operation_id.clone(), + force: false, + intent, + }); let send_request = SendRequest { operation_id: request.operation_id, force: false, @@ -102,6 +124,8 @@ impl WalletClient { let error = WalletClientError::InsufficientBalance { available_nanograms: account.balance_nanograms, requested_nanograms, + operation_fee_nanograms: None, + operation_spend_nanograms: None, }; self.discard_transfer_preparation(generation); return Err(error); @@ -164,6 +188,7 @@ impl WalletClient { &expected_source, config.network, &send_request, + gasless_request.as_ref(), &fresh, valid_until, ) @@ -226,3 +251,1041 @@ impl WalletClient { } } } + +#[cfg(test)] +mod tests { + use std::str::FromStr; + use std::sync::{Arc, Mutex}; + + use ed25519_dalek::{Signature, VerifyingKey}; + use futures::executor::block_on; + use ton::block_tlb::{CommonMsgInfo, Msg, StateInit}; + use ton::ton_core::cell::TonCell; + use ton::ton_core::traits::tlb::TLB; + use ton::ton_core::types::TonAddress; + use ton::ton_core::types::tlb_core::TLBCoins; + use ton::ton_wallet::{WalletExtMsgBody, WalletInternalSignedBody}; + + use super::*; + use crate::wallet::crypto::derive_wallet; + use crate::{ + Boc, HttpHostError, HttpHostErrorKind, HttpMethod, HttpRequest, HttpRequestId, + HttpResponse, JournalCompareExchange, JournalCompareExchangeResult, JournalHostError, + JournalKey, JournalRecord, Network, NonEmptyString, ProtectedSecretHostError, + ProtectedSecretRef, ProtectedSecretStore, ProviderConfig, SendAmount, SendExpiration, + SendIntent, SendMessage, SendMessageBody, TonAddressString, UnsignedDecimalString, + WalletClientConfig, WalletHttpHost, WalletPlatformHost, + }; + + const MNEMONIC: &str = + "notice tortoise soup strong gun divide offer process salon siren general carry"; + const DESTINATION: &str = "0:2222222222222222222222222222222222222222222222222222222222222222"; + + /// Records every provider request and answers it as offline. + struct OfflineHost { + requests: Mutex>, + } + + impl OfflineHost { + fn request_count(&self) -> usize { + self.requests.lock().expect("request lock").len() + } + } + + #[async_trait::async_trait] + impl WalletHttpHost for OfflineHost { + async fn execute_http(&self, request: HttpRequest) -> Result { + self.requests.lock().expect("request lock").push(request); + Err(HttpHostError::Failed { + kind: HttpHostErrorKind::Offline, + diagnostic: "scripted offline".to_owned(), + }) + } + + async fn cancel_http(&self, _request_id: HttpRequestId) {} + } + + /// Records protected-secret reads; transfer preparation uses no other call. + struct SecretHost { + reasons: Mutex>, + } + + impl SecretHost { + fn read_count(&self) -> usize { + self.reasons.lock().expect("reason lock").len() + } + + fn reasons(&self) -> Vec { + self.reasons.lock().expect("reason lock").clone() + } + } + + #[async_trait::async_trait] + impl WalletPlatformHost for SecretHost { + async fn read_protected_secret( + &self, + request: ProtectedSecretRead, + ) -> Result, ProtectedSecretHostError> { + self.reasons + .lock() + .expect("reason lock") + .push(request.reason); + Ok(MNEMONIC.as_bytes().to_vec()) + } + + async fn store_protected_secret( + &self, + _request: ProtectedSecretStore, + ) -> Result<(), ProtectedSecretHostError> { + panic!("not used by transfer preparation") + } + + async fn delete_protected_secret( + &self, + _secret_ref: ProtectedSecretRef, + ) -> Result<(), ProtectedSecretHostError> { + panic!("not used by transfer preparation") + } + + async fn load_journal( + &self, + _key: JournalKey, + ) -> Result, JournalHostError> { + panic!("not used by transfer preparation") + } + + async fn compare_exchange_journal( + &self, + _mutation: JournalCompareExchange, + ) -> Result { + panic!("not used by transfer preparation") + } + } + + fn client_config() -> WalletClientConfig { + let wallet = derive_wallet(MNEMONIC, Network::Testnet).expect("wallet derives"); + WalletClientConfig { + record_id: NonEmptyString::try_from("prepare-transfer-test").expect("record ID"), + address: TonAddressString::from_address(&wallet.address, Network::Testnet), + public_key: wallet.key_pair.public_key.to_vec(), + local_secret_ref: Some(ProtectedSecretRef { + value: "wallet-secret".to_owned(), + }), + network: Network::Testnet, + send_validity_seconds: 300, + resolution_margin_seconds: 60, + providers: ProviderConfig { + toncenter_base_url: "https://provider.example".to_owned(), + dns_root_address: None, + request_timeout_ms: 15_000, + }, + } + } + + /// Builds a one-message preparation request naming `send_mode`. + fn request(send_mode: Option) -> PrepareTransferRequest { + PrepareTransferRequest { + operation_id: NonEmptyString::try_from("prepare-transfer").expect("operation ID"), + intent: SendIntent { + expiration: SendExpiration::EngineDefault, + messages: vec![SendMessage { + destination: TonAddressString::try_from(DESTINATION).expect("destination"), + amount: SendAmount::exact("1").expect("amount"), + body: SendMessageBody::Empty, + bounce: false, + state_init: None, + send_mode, + }], + }, + gasless_messages: None, + } + } + + /// Refuses a served mode before any provider request or secret read. + #[test] + fn unsupported_send_modes_are_refused_before_provider_or_secret_access() { + let http = Arc::new(OfflineHost { + requests: Mutex::new(Vec::new()), + }); + let platform = Arc::new(SecretHost { + reasons: Mutex::new(Vec::new()), + }); + let client = WalletClient::new(client_config(), http.clone(), platform.clone()) + .expect("client builds"); + + for (mode, diagnostic) in [ + (1, "an external wallet message needs flag 2 (ignore errors)"), + (256, "the mode does not fit the wallet action's 8-bit field"), + ] { + let error = block_on(client.prepare_transfer(request(Some(mode)))) + .expect_err("the mode is refused"); + + assert_eq!( + error, + WalletClientError::UnsupportedSendMode { + mode, + diagnostic: diagnostic.to_owned(), + } + ); + assert_eq!( + error.to_string(), + format!("send mode {mode} is not supported: {diagnostic}") + ); + assert_eq!(http.request_count(), 0, "mode {mode}"); + assert_eq!(platform.read_count(), 0, "mode {mode}"); + } + + // Control: an accepted mode reaches the provider, which is offline, and + // the refusals above left no preparation in progress. + let error = block_on(client.prepare_transfer(request(Some(3)))) + .expect_err("the offline provider fails the preparation"); + assert!( + !matches!(error, WalletClientError::UnsupportedSendMode { .. }), + "{error:?}" + ); + assert_eq!(http.request_count(), 1); + assert_eq!(platform.read_count(), 0); + } + + const DESTINATION_B: &str = + "0:3333333333333333333333333333333333333333333333333333333333333333"; + const DESTINATION_C: &str = + "0:4444444444444444444444444444444444444444444444444444444444444444"; + const OPERATION: &str = "prepare-distinct"; + /// Fixed expiry of the explicit-expiration preparations. + const VALID_UNTIL: u64 = 1_900_000_000; + const MISSING_IGNORE_ERRORS: &str = "an external wallet message needs flag 2 (ignore errors)"; + + /// A provider call that transfer preparation is expected to make. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum ProviderCall { + /// `getAddressInformation` for the configured wallet. + Account, + /// The JSON-RPC `runGetMethod` read of the configured wallet's `seqno`. + Seqno, + } + + /// Answers the configured wallet's account read as an active account with + /// `balance` at provider time 1 and its `seqno` read as 42. Every other + /// request fails; all requests are recorded exactly. + struct PreparationHost { + address: String, + balance: u64, + requests: Mutex>, + } + + impl PreparationHost { + fn new(config: &WalletClientConfig, balance: u64) -> Self { + Self { + address: config.address.as_str().to_owned(), + balance, + requests: Mutex::new(Vec::new()), + } + } + + /// Classifies each recorded request in order; `None` is unexpected. + fn calls(&self) -> Vec> { + self.requests + .lock() + .expect("request lock") + .iter() + .map(|request| self.classify(request)) + .collect() + } + + fn classify(&self, request: &HttpRequest) -> Option { + let url = url::Url::parse(&request.url).ok()?; + if url.host_str() != Some("provider.example") { + return None; + } + match (request.method, url.path()) { + (HttpMethod::Get, "/api/v2/getAddressInformation") => { + let query = url.query_pairs().into_owned().collect::>(); + (query == [("address".to_owned(), self.address.clone())]) + .then_some(ProviderCall::Account) + } + (HttpMethod::Post, "/api/v2/jsonRPC") => { + let body: serde_json::Value = serde_json::from_slice(&request.body).ok()?; + (body["method"] == "runGetMethod" + && body["params"]["method"] == "seqno" + && body["params"]["address"] == self.address.as_str()) + .then_some(ProviderCall::Seqno) + } + _ => None, + } + } + } + + #[async_trait::async_trait] + impl WalletHttpHost for PreparationHost { + async fn execute_http(&self, request: HttpRequest) -> Result { + self.requests + .lock() + .expect("request lock") + .push(request.clone()); + let body = match self.classify(&request) { + Some(ProviderCall::Account) => serde_json::json!({ + "ok": true, + "result": { + "balance": self.balance.to_string(), + "state": "active", + "sync_utime": 1 + } + }), + Some(ProviderCall::Seqno) => serde_json::json!({ + "ok": true, + "result": { "exit_code": 0, "stack": [["num", "0x2a"]] } + }), + None => { + return Err(HttpHostError::Failed { + kind: HttpHostErrorKind::Other, + diagnostic: "unexpected scripted request".to_owned(), + }); + } + }; + Ok(HttpResponse { + status: 200, + headers: Vec::new(), + body: serde_json::to_vec(&body).expect("response JSON"), + final_url: request.url, + }) + } + + async fn cancel_http(&self, _request_id: HttpRequestId) {} + } + + /// A client over a fresh `PreparationHost` and recording `SecretHost`. + struct ScriptedClient { + client: Arc, + http: Arc, + platform: Arc, + } + + impl ScriptedClient { + fn new(balance: u64) -> Self { + let config = client_config(); + let http = Arc::new(PreparationHost::new(&config, balance)); + let platform = Arc::new(SecretHost { + reasons: Mutex::new(Vec::new()), + }); + let client = + WalletClient::new(config, http.clone(), platform.clone()).expect("client builds"); + Self { + client, + http, + platform, + } + } + + fn prepare( + &self, + request: PrepareTransferRequest, + ) -> Result { + block_on(self.client.prepare_transfer(request)) + } + } + + /// Builds a preparation request with an optional gasless list. + fn prepare_request( + expiration: SendExpiration, + messages: Vec, + gasless_messages: Option>, + ) -> PrepareTransferRequest { + PrepareTransferRequest { + operation_id: NonEmptyString::try_from(OPERATION).expect("operation ID"), + intent: SendIntent { + expiration, + messages, + }, + gasless_messages, + } + } + + /// A value-only message to `DESTINATION`: an exact value, or the whole + /// balance for `None`, with an optional explicit mode. + fn message(nanograms: Option, send_mode: Option) -> SendMessage { + SendMessage { + destination: TonAddressString::try_from(DESTINATION).expect("destination"), + amount: nanograms.map_or(SendAmount::All, |nanograms| { + SendAmount::exact(nanograms.to_string()).expect("amount") + }), + body: SendMessageBody::Empty, + bounce: false, + state_init: None, + send_mode, + } + } + + /// One mode-less message per value; `None` is a whole-balance message. + fn messages(nanograms: &[Option]) -> Vec { + nanograms + .iter() + .map(|nanograms| message(*nanograms, None)) + .collect() + } + + /// A cell holding the 32-bit `bits` and references to `children`. + fn cell(bits: u32, children: &[TonCell]) -> TonCell { + let mut cell = TonCell::builder(); + cell.write_num(&bits, 32).expect("bits fit one cell"); + for child in children { + cell.write_ref(child.clone()).expect("child reference fits"); + } + cell.build().expect("cell builds") + } + + /// One served message described by literals, independent of the signer. + struct Literal { + destination: &'static str, + nanograms: u64, + bounce: bool, + /// The raw body cell's 32-bit opcode. + opcode: u32, + /// The code and data cells of an attached contract `StateInit`. + init: Option<(TonCell, TonCell)>, + mode: i32, + } + + impl Literal { + /// The engine message a caller builds from these literal fields. + fn message(&self) -> SendMessage { + SendMessage { + destination: TonAddressString::try_from(self.destination) + .expect("literal destination"), + amount: SendAmount::exact(self.nanograms.to_string()).expect("literal value"), + body: SendMessageBody::RawPayload { + boc: Boc::try_from(cell(self.opcode, &[]).to_boc().expect("body encodes")) + .expect("body BOC"), + }, + bounce: self.bounce, + state_init: self.init.as_ref().map(|(code, data)| { + let state_init = StateInit::new(code.clone(), data.clone()); + Boc::try_from(state_init.to_boc().expect("StateInit encodes")) + .expect("StateInit BOC") + }), + send_mode: Some(self.mode), + } + } + + /// Asserts that one decoded wallet action carries exactly these fields. + fn assert_carried_by(&self, mode: u8, action: &Msg, label: &str) { + assert_eq!(i32::from(mode), self.mode, "{label}: mode"); + let CommonMsgInfo::Int(info) = &action.info else { + panic!("{label}: a wallet action must be an internal message"); + }; + let destination = TonAddress::from_str(self.destination).expect("literal address"); + assert_eq!( + info.dst, + destination.to_msg_address(), + "{label}: destination" + ); + assert_eq!( + info.value.coins, + TLBCoins::new(u128::from(self.nanograms)), + "{label}: value" + ); + assert_eq!(info.bounce, self.bounce, "{label}: bounce"); + assert_eq!(action.body.value, cell(self.opcode, &[]), "{label}: body"); + let Some((code, data)) = &self.init else { + assert!(action.init.is_none(), "{label}: no StateInit was served"); + return; + }; + let init = &action + .init + .as_ref() + .unwrap_or_else(|| panic!("{label}: the action carries no StateInit")) + .value; + assert_eq!(init.split_depth, None, "{label}: split depth"); + assert_eq!(init.tick_tock, None, "{label}: tick-tock"); + assert_eq!(init.code.as_deref(), Some(code), "{label}: code"); + assert_eq!(init.data.as_deref(), Some(data), "{label}: data"); + assert!(init.library.is_empty(), "{label}: library"); + } + } + + /// Delivery form of a signed wallet request. + #[derive(Debug, Clone, Copy)] + enum Delivery { + External, + Internal, + } + + /// The wallet request decoded from one returned signed BOC. + struct SignedRequest { + seqno: u32, + valid_until: u32, + actions: Vec<(u8, Msg)>, + } + + /// Decodes a returned BOC with the vendored readers alone. + /// + /// The envelope must be `delivery`'s kind, address the configured wallet + /// and deploy nothing; the configured key must verify the request; each + /// action message must be consumed completely. + fn decode_signed_request( + boc: &Boc, + config: &WalletClientConfig, + delivery: Delivery, + ) -> SignedRequest { + let root = TonCell::from_boc(boc.as_bytes().to_vec()).expect("signed BOC parses"); + let envelope = read_whole_message(&root); + assert!(envelope.init.is_none(), "an active wallet is not deployed"); + let source = config.address.as_address(); + let mut parser = envelope.body.value.parser(); + let (body, signature, seqno, valid_until, modes, messages) = match delivery { + Delivery::External => { + let CommonMsgInfo::ExtIn(info) = &envelope.info else { + panic!("an external request must use an external envelope"); + }; + assert_eq!(info.dst, source.to_msg_address_int()); + let (request, signature) = + WalletExtMsgBody::read_signed(&mut parser).expect("external request decodes"); + let body = request.to_cell().expect("external request serializes"); + let WalletExtMsgBody { + valid_until, + msg_seqno, + msgs_modes, + msgs, + .. + } = request; + (body, signature, msg_seqno, valid_until, msgs_modes, msgs) + } + Delivery::Internal => { + let CommonMsgInfo::Int(info) = &envelope.info else { + panic!("an internal request must use an internal envelope"); + }; + assert_eq!(info.dst, source.to_msg_address()); + let (request, signature) = WalletInternalSignedBody::read_signed(&mut parser) + .expect("internal request decodes"); + let body = request.to_cell().expect("internal request serializes"); + let WalletInternalSignedBody { + valid_until, + msg_seqno, + msgs_modes, + msgs, + .. + } = request; + (body, signature, msg_seqno, valid_until, msgs_modes, msgs) + } + }; + let public_key = + <[u8; 32]>::try_from(config.public_key.as_slice()).expect("32-byte public key"); + VerifyingKey::from_bytes(&public_key) + .expect("public key is valid") + .verify_strict( + body.cell_hash().expect("request hashes").as_slice(), + &Signature::from_slice(&signature).expect("64-byte signature"), + ) + .expect("the configured wallet key signs the request"); + assert_eq!(modes.len(), messages.len()); + SignedRequest { + seqno, + valid_until, + actions: modes + .into_iter() + .zip(messages.iter().map(read_whole_message)) + .collect(), + } + } + + /// Reads one message cell and requires that nothing follows the message. + fn read_whole_message(cell: &TonCell) -> Msg { + let mut parser = cell.parser(); + let message = Msg::::read(&mut parser).expect("message decodes"); + parser + .ensure_empty() + .expect("message has no trailing bits or references"); + message + } + + /// Asserts that a decoded request carries exactly `expected`, in order. + fn assert_carries(request: &SignedRequest, expected: &[Literal], label: &str) { + assert_eq!( + request.actions.len(), + expected.len(), + "{label}: action count" + ); + for (index, ((mode, action), literal)) in request.actions.iter().zip(expected).enumerate() { + literal.assert_carried_by(*mode, action, &format!("{label}, action {index}")); + } + } + + /// Signs a gasless list that differs from the intent in every field. + /// + /// Each internal-only gasless mode is signed exactly beside a normal mode + /// 2 or 3. The external form carries only the intent, the internal form + /// only the list, and both come from one account and `seqno` resolution, + /// one expiry and one secret read, without a journal call or submission. + #[test] + fn distinct_gasless_messages_are_signed_under_one_resolution_and_one_secret_read() { + let config = client_config(); + let code = cell(0xc0de_c0de, &[cell(0x0000_0001, &[])]); + let data = cell(0xda7a_da7a, &[cell(0x0000_0002, &[])]); + let runs = [(0, 2), (1, 3), (16, 2), (17, 3)].map(|(gasless_mode, normal_mode)| { + let normal = vec![Literal { + destination: DESTINATION, + nanograms: 1_000, + bounce: false, + opcode: 0x0a0a_0a0a, + init: None, + mode: normal_mode, + }]; + let gasless = vec![ + Literal { + destination: DESTINATION_B, + nanograms: 700, + bounce: true, + opcode: 0x0b0b_0b0b, + init: Some((code.clone(), data.clone())), + mode: gasless_mode, + }, + Literal { + destination: DESTINATION_C, + nanograms: 300, + bounce: false, + opcode: 0x0c0c_0c0c, + init: None, + mode: 18, + }, + ]; + let scripted = ScriptedClient::new(1_000_000); + let result = scripted.prepare(prepare_request( + SendExpiration::Exact { + unix_timestamp: VALID_UNTIL, + }, + normal.iter().map(Literal::message).collect(), + Some(gasless.iter().map(Literal::message).collect()), + )); + let label = format!("gasless mode {gasless_mode} beside normal mode {normal_mode}"); + (label, normal, gasless, scripted, result) + }); + let refused = runs + .iter() + .filter_map(|(label, _, _, _, result)| { + result + .as_ref() + .err() + .map(|error| format!("{label}: {error}")) + }) + .collect::>(); + assert!( + refused.is_empty(), + "accepted modes were refused: {refused:#?}" + ); + + for (label, normal, gasless, scripted, result) in runs { + let prepared = result.expect("both forms are signed"); + assert_eq!(prepared.operation_id.as_str(), OPERATION, "{label}"); + assert_eq!(prepared.seqno, 42, "{label}"); + assert_eq!(prepared.valid_until, 1_900_000_000, "{label}"); + for (boc, delivery, expected) in [ + (&prepared.external_boc, Delivery::External, &normal), + (&prepared.internal_boc, Delivery::Internal, &gasless), + ] { + let label = format!("{label}, {delivery:?} form"); + let request = decode_signed_request(boc, &config, delivery); + assert_eq!(request.seqno, 42, "{label}: seqno"); + assert_eq!(request.valid_until, 1_900_000_000, "{label}: expiry"); + assert_carries(&request, expected, &label); + } + assert_eq!( + scripted.http.calls(), + [Some(ProviderCall::Account), Some(ProviderCall::Seqno)], + "{label}" + ); + assert_eq!( + scripted.platform.reasons(), + [SecretAccessReason::SignTransfer], + "{label}" + ); + } + } + + /// Without a list, and with a list equal to the intent, the public engine + /// returns exactly the standalone external and internal signers' BOCs. + #[test] + fn omitted_and_equal_gasless_lists_keep_the_existing_pair() { + let config = client_config(); + let account = FreshSendAccount { + status: AccountStatus::Active, + seqno: 42, + }; + let exact = SendExpiration::Exact { + unix_timestamp: VALID_UNTIL, + }; + let cases = [ + ( + "mode-less exact values, engine expiry", + SendExpiration::EngineDefault, + 301, + messages(&[Some(1_000), Some(2_000)]), + ), + ( + "an exact value with mode 3", + exact.clone(), + 1_900_000_000, + vec![message(Some(1_000), Some(3))], + ), + ( + "a mode-less whole balance", + exact, + 1_900_000_000, + messages(&[None]), + ), + ]; + + for (name, expiration, valid_until, messages) in cases { + let request = SendRequest { + operation_id: NonEmptyString::try_from(OPERATION).expect("operation ID"), + force: false, + intent: SendIntent { + expiration, + messages, + }, + }; + let sign = |internal: bool| { + let signer = if internal { + crate::wallet::transfer::prepare_internal_signed_transfer + } else { + crate::wallet::transfer::prepare_transfer + }; + signer( + MNEMONIC.as_bytes(), + &config.record_id, + &config.address, + config.network, + &request, + &account, + valid_until, + ) + .expect("the standalone signer builds") + .signed_boc + }; + let (external, internal) = (sign(false), sign(true)); + + for (list, gasless_messages) in [ + ("without a list", None), + ("with an equal list", Some(request.intent.messages.clone())), + ] { + let label = format!("{name}, {list}"); + let scripted = ScriptedClient::new(1_000_000); + let prepared = scripted + .prepare(PrepareTransferRequest { + operation_id: request.operation_id.clone(), + intent: request.intent.clone(), + gasless_messages, + }) + .expect("both forms are signed"); + assert_eq!(prepared.external_boc, external, "{label}: external form"); + assert_eq!(prepared.internal_boc, internal, "{label}: internal form"); + assert_eq!(prepared.seqno, 42, "{label}"); + assert_eq!(prepared.valid_until, valid_until, "{label}"); + for (boc, delivery) in [ + (&prepared.external_boc, Delivery::External), + (&prepared.internal_boc, Delivery::Internal), + ] { + let signed = decode_signed_request(boc, &config, delivery); + assert_eq!(signed.seqno, 42, "{label}, {delivery:?}"); + assert_eq!( + u64::from(signed.valid_until), + valid_until, + "{label}, {delivery:?}" + ); + } + assert_eq!( + scripted.http.calls(), + [Some(ProviderCall::Account), Some(ProviderCall::Seqno)], + "{label}" + ); + assert_eq!( + scripted.platform.reasons(), + [SecretAccessReason::SignTransfer], + "{label}" + ); + } + } + } + + /// Refuses an invalid gasless list, or an invalid intent beside any list, + /// by name before any provider request or secret read. + #[test] + fn gasless_lists_are_refused_before_provider_or_secret_access() { + let http = Arc::new(OfflineHost { + requests: Mutex::new(Vec::new()), + }); + let platform = Arc::new(SecretHost { + reasons: Mutex::new(Vec::new()), + }); + let client = WalletClient::new(client_config(), http.clone(), platform.clone()) + .expect("client builds"); + let exact = |mode| message(Some(1), mode); + let refused_mode = |mode, diagnostic: &str| WalletClientError::UnsupportedSendMode { + mode, + diagnostic: diagnostic.to_owned(), + }; + let cases = [ + ( + "normal mode 1 beside a valid list", + exact(Some(1)), + vec![exact(Some(1))], + refused_mode(1, MISSING_IGNORE_ERRORS), + ), + ( + "gasless mode 128", + exact(Some(3)), + vec![exact(Some(128))], + refused_mode( + 128, + "flag 128 would send the whole balance instead of the message value", + ), + ), + ( + "gasless mode 256", + exact(Some(3)), + vec![exact(Some(256))], + refused_mode(256, "the mode does not fit the wallet action's 8-bit field"), + ), + ( + "an empty gasless list", + exact(None), + Vec::new(), + WalletClientError::InvalidSendRequest, + ), + ( + "256 gasless messages", + exact(None), + vec![exact(None); 256], + WalletClientError::InvalidSendRequest, + ), + ( + "a whole-balance gasless message beside an exact one", + exact(None), + vec![message(None, None), exact(None)], + WalletClientError::InvalidSendRequest, + ), + ( + "a whole-balance gasless message with mode 2", + exact(None), + vec![message(None, Some(2))], + refused_mode(2, "a whole-balance transfer keeps its own send mode"), + ), + ( + "a refused third gasless message", + exact(None), + vec![exact(Some(0)), exact(Some(17)), exact(Some(64))], + refused_mode( + 64, + "flag 64 would add the remaining inbound value to the message value", + ), + ), + ( + "both lists refused", + exact(Some(17)), + vec![exact(Some(128))], + refused_mode(17, MISSING_IGNORE_ERRORS), + ), + ]; + + for (name, normal, gasless, expected) in cases { + let request = + prepare_request(SendExpiration::EngineDefault, vec![normal], Some(gasless)); + let error = block_on(client.prepare_transfer(request)).expect_err(name); + assert_eq!(error, expected, "{name}"); + assert_eq!(http.request_count(), 0, "{name}"); + assert_eq!(platform.read_count(), 0, "{name}"); + } + + // Control: valid lists with internal-only gasless modes reach the + // offline provider once, and no refusal left a preparation in progress. + let request = prepare_request( + SendExpiration::EngineDefault, + vec![exact(Some(3))], + Some(vec![exact(Some(0)), exact(Some(17))]), + ); + let error = block_on(client.prepare_transfer(request)) + .expect_err("the offline provider fails the preparation"); + assert!( + !matches!( + error, + WalletClientError::UnsupportedSendMode { .. } + | WalletClientError::InvalidSendRequest + ), + "{error:?}" + ); + assert_eq!(http.request_count(), 1); + assert_eq!(platform.read_count(), 0); + } + + /// One balance-table preparation; `None` values are whole-balance messages. + struct BalanceRow { + name: &'static str, + normal: &'static [Option], + gasless: &'static [Option], + balance: u64, + /// The total the refusal names, or `None` when both forms are signed. + refused: Option, + } + + const fn row( + name: &'static str, + normal: &'static [Option], + gasless: &'static [Option], + balance: u64, + refused: Option, + ) -> BalanceRow { + BalanceRow { + name, + normal, + gasless, + balance, + refused, + } + } + + /// What a preparation returned, the provider calls and the secret reads. + type Observed = ( + Result<(), WalletClientError>, + Vec>, + Vec, + ); + + /// Every exact alternative must fit the fresh balance on its own; the + /// alternatives are never added, and a whole-balance form has no total. + #[test] + fn the_balance_rule_checks_every_exact_alternative() { + let rows = [ + row( + "gasless larger, at its total", + &[Some(1_000)], + &[Some(1_200), Some(800)], + 2_000, + None, + ), + row( + "gasless larger, one below", + &[Some(1_000)], + &[Some(1_200), Some(800)], + 1_999, + Some(2_000), + ), + row( + "normal larger, at its total", + &[Some(1_500), Some(500)], + &[Some(1_000)], + 2_000, + None, + ), + row( + "normal larger, one below", + &[Some(1_500), Some(500)], + &[Some(1_000)], + 1_999, + Some(2_000), + ), + row( + "exact normal, whole-balance gasless, at the total", + &[Some(1_000)], + &[None], + 1_000, + None, + ), + row( + "exact normal, whole-balance gasless, one below", + &[Some(1_000)], + &[None], + 999, + Some(1_000), + ), + row( + "whole-balance normal, exact gasless, at the total", + &[None], + &[Some(1_000)], + 1_000, + None, + ), + row( + "whole-balance normal, exact gasless, one below", + &[None], + &[Some(1_000)], + 999, + Some(1_000), + ), + row( + "whole balance in both forms at zero", + &[None], + &[None], + 0, + None, + ), + ]; + let account = Some(ProviderCall::Account); + let seqno = Some(ProviderCall::Seqno); + let observe = |scripted: &ScriptedClient, result: Result| { + ( + result.map(drop), + scripted.http.calls(), + scripted.platform.reasons(), + ) + }; + let mut failures = Vec::new(); + + for row in rows { + let scripted = ScriptedClient::new(row.balance); + let result = scripted.prepare(prepare_request( + SendExpiration::EngineDefault, + messages(row.normal), + Some(messages(row.gasless)), + )); + let observed: Observed = observe(&scripted, result); + let expected: Observed = row.refused.map_or_else( + || { + ( + Ok(()), + vec![account, seqno], + vec![SecretAccessReason::SignTransfer], + ) + }, + |requested| { + let error = WalletClientError::InsufficientBalance { + available_nanograms: UnsignedDecimalString::from(row.balance), + requested_nanograms: UnsignedDecimalString::from(requested), + operation_fee_nanograms: None, + operation_spend_nanograms: None, + }; + (Err(error), vec![account], Vec::new()) + }, + ); + if observed != expected { + failures.push(format!( + "{}: expected {expected:?}, observed {observed:?}", + row.name + )); + continue; + } + if row.refused.is_none() { + continue; + } + + // The refusal released the preparation: smaller values that fit + // are signed on the same client. + let retry = scripted.prepare(prepare_request( + SendExpiration::EngineDefault, + messages(&[Some(1)]), + Some(messages(&[Some(1)])), + )); + let observed = observe(&scripted, retry); + let expected: Observed = ( + Ok(()), + vec![account, account, seqno], + vec![SecretAccessReason::SignTransfer], + ); + if observed != expected { + failures.push(format!( + "{} retry: expected {expected:?}, observed {observed:?}", + row.name + )); + } + } + assert!(failures.is_empty(), "balance rows failed: {failures:#?}"); + } +} diff --git src/engine/preview.rs src/engine/preview.rs index 4a91f8a..1ed5c97 100644 --- src/engine/preview.rs +++ src/engine/preview.rs @@ -1,17 +1,23 @@ //! Pre-authorization transfer previews built from fresh provider state. +use num_bigint::BigUint; + use crate::domain::bounded_diagnostic; use crate::transport::build_toncenter_v2_request; use crate::wallet::send::FreshSendAccount; use crate::wallet::transfer::{prepare_signed_boc, prepare_transfer_emulation}; use crate::{ - AccountStatus, Boc, DomainError, HttpRequest, HttpRequestId, SendBocRequest, SendEmulation, - SendPreview, SendPreviewRequest, SendRequest, SignMessagePreview, TonAddressString, - WalletClientConfig, WalletClientError, + AccountStatus, Boc, DomainError, HttpRequest, HttpRequestId, SendAmount, SendBocRequest, + SendEmulation, SendIntent, SendMessage, SendPreview, SendPreviewRequest, SendRequest, + SignMessagePreview, TonAddressString, UnsignedDecimalString, WalletClientConfig, + WalletClientError, }; use super::WalletClient; -use super::emulation::{build_emulation_request, is_message_not_accepted, parse_emulation}; +use super::emulation::{ + EvaluatedEmulation, MessageCreation, RootComposition, build_emulation_request, + is_message_not_accepted, parse_emulation, +}; use super::expiration::resolve_send_expiration; use super::provider::parse_account; use super::send_http::{build_seqno_request, parse_seqno}; @@ -91,20 +97,27 @@ impl WalletClient { let available = account.balance_nanograms.clone(); let requested = request .intent - .exact_value_total() - .map_err(|_| self.preview_error(generation, WalletClientError::InvalidSendRequest))?; + .exact_value_total_for_external() + .map_err(|error| self.preview_error(generation, WalletClientError::from(error)))?; - if let Some(nanograms) = &requested - && nanograms > &available - { - return Err(self.preview_error( - generation, - WalletClientError::InsufficientBalance { + // A preview that asks for the operation's fee defers this refusal to + // attempt the quote; any failure of that attempt keeps it, without a fee. + let deferred_refusal = match &requested { + Some(nanograms) if nanograms > &available => { + let refusal = WalletClientError::InsufficientBalance { available_nanograms: available.clone(), requested_nanograms: nanograms.clone(), - }, - )); - } + operation_fee_nanograms: None, + operation_spend_nanograms: None, + }; + if !request.estimate_shortfall { + return Err(self.preview_error(generation, refusal)); + } + Some(refusal) + } + Some(_) | None => None, + }; + let refuse = |error| deferred_refusal.clone().unwrap_or(error); let seqno = match account.status { AccountStatus::Active => self @@ -114,16 +127,16 @@ impl WalletClient { .map_err(|error| { self.preview_error( generation, - WalletClientError::SendPreviewFailed { + refuse(WalletClientError::SendPreviewFailed { diagnostic: bounded_diagnostic(error.developer_message), - }, + }), ) })?, AccountStatus::Nonexistent | AccountStatus::Uninitialized => 0, status @ (AccountStatus::Frozen | AccountStatus::Unknown) => { return Err(self.preview_error( generation, - WalletClientError::SendAccountUnavailable { status }, + refuse(WalletClientError::SendAccountUnavailable { status }), )); } }; @@ -137,9 +150,9 @@ impl WalletClient { .map_err(|error| { self.preview_error( generation, - WalletClientError::SendPreviewFailed { + refuse(WalletClientError::SendPreviewFailed { diagnostic: error.to_string(), - }, + }), ) })?; @@ -159,48 +172,89 @@ impl WalletClient { .map_err(|error| { self.preview_error( generation, - WalletClientError::SendPreviewFailed { + refuse(WalletClientError::SendPreviewFailed { diagnostic: bounded_diagnostic(format!("failed to prepare preview: {error}")), - }, + }), ) })?; - let emulation = self - .emulate_preview_boc( - generation, - &config, - &expected_source, - emulation_request_id, - &boc, - ) - .await?; + let (emulation, operation_fee, operation_spend, undelivered) = match &requested { + Some(nanograms) if request.estimate_shortfall => { + let companion = || { + prepare_transfer_emulation( + &expected_source, + &config.public_key, + config.network, + &shortfall_companion(&request.intent, valid_until), + &fresh, + valid_until, + ) + .ok() + }; + match self + .quote_operation( + generation, + &config, + emulation_request_id, + &boc, + &request.intent.messages, + companion, + ) + .await? + { + Ok(OperationQuote::Created { emulation, spend }) => { + let fee = emulation.wallet_fees_nanograms.clone(); + (emulation, Some(fee), Some(spend), None) + } + Ok(OperationQuote::Unusable(quote)) => { + return Err( + self.preview_error(generation, quote.refusal(&available, nanograms)) + ); + } + Err(error) => return Err(self.preview_error(generation, refuse(error))), + } + } + Some(_) | None => { + let evaluated = self + .emulate_preview_boc( + generation, + &config, + &expected_source, + emulation_request_id, + &boc, + ) + .await?; + let undelivered = delivery_refusal(&evaluated, request.intent.messages.len()); + (evaluated.summary, None, None, undelivered) + } + }; if let Some(nanograms) = &requested { - // Exact sends must leave a positive remainder after the emulated - // wallet fee. Use `SendAmount::All` when the intent is to drain - // the wallet with carry-all-balance mode instead. - #[allow( - clippy::arithmetic_side_effects, - reason = "UnsignedDecimalString uses arbitrary-precision BigUint addition" - )] - let required = nanograms + &emulation.wallet_fees_nanograms; - if required >= available { - return Err(self.preview_error( - generation, - WalletClientError::InsufficientBalanceForFees { - available_nanograms: available.clone(), - requested_nanograms: nanograms.clone(), - estimated_fee_nanograms: emulation.wallet_fees_nanograms, - }, - )); + // Only a preview that asked for the operation's fee gets here + // above the balance, with the fee and the spend of its created + // operation. + if let Some(refusal) = funds_refusal( + &available, + nanograms, + &emulation.wallet_fees_nanograms, + operation_fee, + operation_spend.clone(), + ) { + return Err(self.preview_error(generation, refusal)); } } + // A default preview whose wallet did not create every message is + // refused only after the funds checks above, which keep their outcome. + if let Some(refusal) = undelivered { + return Err(self.preview_error(generation, refusal)); + } let preview = SendPreview { messages: request.intent.messages, valid_until, message_boc_base64: boc, emulation, + operation_spend_nanograms: operation_spend, }; self.finish_preview(generation)?; Ok(preview) @@ -335,6 +389,7 @@ impl WalletClient { ) })?; + // The signed BOC stays opaque, so no message count is checked here. let emulation = self .emulate_preview_boc( generation, @@ -343,13 +398,15 @@ impl WalletClient { emulation_request_id, &prepared.signed_boc, ) - .await?; + .await? + .summary; let preview = SendPreview { messages: prepared.messages, valid_until, message_boc_base64: prepared.signed_boc, emulation, + operation_spend_nanograms: None, }; self.finish_preview(generation)?; Ok(preview) @@ -365,6 +422,7 @@ impl WalletClient { ) -> Result { self.preview_send(SendPreviewRequest { intent: request.intent, + estimate_shortfall: false, }) .await } @@ -407,7 +465,7 @@ impl WalletClient { let _ = request .intent .exact_value_total() - .map_err(|_| self.preview_error(generation, WalletClientError::InvalidSendRequest))?; + .map_err(|error| self.preview_error(generation, WalletClientError::from(error)))?; let account = self .execute_tracked_preview_request(generation, &account_request) .await? @@ -472,7 +530,265 @@ impl WalletClient { } } +/// What a preview that asked for the operation's fee learned from emulating it. +enum OperationQuote { + /// The wallet created every message and paid a positive root fee, which + /// is the operation's fee in `emulation`, and the answer established the + /// operation's `spend` beyond the message values. + Created { + emulation: SendEmulation, + spend: UnsignedDecimalString, + }, + /// The emulation cannot stand for the operation. + Unusable(UnusableQuote), +} + +/// An emulation of the exact operation that is not a successful preview. +struct UnusableQuote { + /// This emulation's root wallet fee, which is not the operation's fee + /// unless the wallet created every message. + raw_fee: UnsignedDecimalString, + /// The operation's fee, when the emulations established it. + operation_fee: Option, + /// The operation's spend beyond the message values, when the emulations + /// established it; never without `operation_fee`. + operation_spend: Option, + /// The emulation error that stands when no funds check refuses. + error: WalletClientError, +} + +impl UnusableQuote { + /// Resolves the preview with the funds checks of [`funds_refusal`], never + /// as a success. + /// + /// An established spend decides like a created emulation's spend, and an + /// established fee without one is compared like the default preview's + /// fee; both are reported. Without either, the raw fee keeps only the + /// refusal that the default preview would give and is never reported as + /// the operation's fee. When no check refuses, the emulation error stands, + /// even where the spend fits: the wallet did not create the messages. + fn refusal( + self, + available: &UnsignedDecimalString, + requested: &UnsignedDecimalString, + ) -> WalletClientError { + let Self { + raw_fee, + operation_fee, + operation_spend, + error, + } = self; + let fee = operation_fee.clone().unwrap_or(raw_fee); + funds_refusal(available, requested, &fee, operation_fee, operation_spend).unwrap_or(error) + } +} + +/// The funds refusal of an emulated exact-value preview, if any. +/// +/// A value above the balance is refused first. With `operation_spend`, the +/// operation's spend beyond the value that the preview established, the +/// value plus that spend must fit the balance, equality included: exactly +/// then can the wallet create the messages. Without it, exact sends must +/// leave a positive remainder after `fee`, the emulated wallet fee that the +/// check compares; use `SendAmount::All` to drain the wallet with +/// carry-all-balance mode instead. Either refusal reports `operation_fee` +/// and `operation_spend`, the operation's fee and spend when the preview +/// established them. +fn funds_refusal( + available: &UnsignedDecimalString, + requested: &UnsignedDecimalString, + fee: &UnsignedDecimalString, + operation_fee: Option, + operation_spend: Option, +) -> Option { + if requested > available { + return Some(WalletClientError::InsufficientBalance { + available_nanograms: available.clone(), + requested_nanograms: requested.clone(), + operation_fee_nanograms: operation_fee, + operation_spend_nanograms: operation_spend, + }); + } + #[allow( + clippy::arithmetic_side_effects, + reason = "UnsignedDecimalString uses arbitrary-precision BigUint addition" + )] + let refused = match &operation_spend { + Some(spend) => &(requested + spend) > available, + None => &(requested + fee) >= available, + }; + refused.then(|| WalletClientError::InsufficientBalanceForFees { + available_nanograms: available.clone(), + requested_nanograms: requested.clone(), + estimated_fee_nanograms: fee.clone(), + operation_fee_nanograms: operation_fee, + operation_spend_nanograms: operation_spend, + }) +} + +/// What the wallet spends beyond the exact values of `messages`, priced +/// from `created`, an emulation in which the wallet created every one of +/// them, and `fee`, the operation's root wallet fee. +/// +/// The action phase keeps the first part of each message's forwarding fee, +/// A (`total_action_fees`), inside the root fee; the rest travels with the +/// message. With send mode +1 the wallet pays the whole forwarding fee T +/// (`total_fwd_fees`) beside the value, otherwise the value pays it, so the +/// spend is `fee - A + T` or `fee - A`. `None` mode is the engine's mode 3 +/// for an exact value. The messages must share one fee kind among the +/// external modes 2, 3, 18 and 19, and A must be positive, within T and +/// within `fee`; otherwise, or for a zero spend, nothing is established. +fn operation_spend( + fee: &UnsignedDecimalString, + created: &EvaluatedEmulation, + messages: &[SendMessage], +) -> Option { + let pays_forwarding = |message: &SendMessage| match (&message.amount, message.send_mode) { + (SendAmount::Exact { .. }, None) => Some(true), + (SendAmount::Exact { .. }, Some(mode @ (2 | 3 | 18 | 19))) => Some(mode & 1 != 0), + (SendAmount::Exact { .. } | SendAmount::All, _) => None, + }; + let (first, rest) = messages.split_first()?; + let pays = pays_forwarding(first)?; + if rest + .iter() + .any(|message| pays_forwarding(message) != Some(pays)) + { + return None; + } + let forwarding = created.forwarding.as_ref()?; + let action = &forwarding.total_action_fees; + let fee = fee.as_biguint(); + if action == &BigUint::default() || &forwarding.total_fwd_fees < action || fee < action { + return None; + } + #[allow( + clippy::arithmetic_side_effects, + reason = "the action fee is within the fee, which rules out BigUint underflow, and addition cannot overflow" + )] + let spend = if pays { + fee - action + &forwarding.total_fwd_fees + } else { + fee - action + }; + (spend != BigUint::default()).then(|| spend.into()) +} + +/// The zero-value companion of an exact-value operation. +/// +/// Each message keeps its destination, body, `StateInit`, bounce flag and +/// send mode, with value 0; modes 2 and 18, which take forwarding fees from +/// the message value, become 3 and 19 so that a zero-value message pays them +/// from the balance. Neither change touches the cells outside the message +/// root, from which the network prices the action fee. +fn shortfall_companion(intent: &SendIntent, valid_until: u64) -> SendPreviewRequest { + SendPreviewRequest { + intent: SendIntent { + expiration: crate::SendExpiration::Exact { + unix_timestamp: valid_until, + }, + messages: intent + .messages + .iter() + .map(|message| SendMessage { + amount: SendAmount::Exact { + nanograms: UnsignedDecimalString::from(0_u64), + }, + send_mode: match message.send_mode { + Some(2) => Some(3), + Some(18) => Some(19), + mode => mode, + }, + ..message.clone() + }) + .collect(), + }, + estimate_shortfall: false, + } +} + +/// `total_fees(M) - total_action_fees(M) + total_action_fees(C)`, when the +/// companion C proves the action fee of the skipped messages of operation M. +/// +/// Both answers already belong to the configured wallet. They must come from +/// one block, run the wallet successfully with equal gas and storage fees, +/// and M must have skipped every message that C created. Each root fee must +/// be positive and contain its own action fee. The result is never zero. +fn composite_fee( + operation: &EvaluatedEmulation, + companion: &EvaluatedEmulation, + messages: usize, +) -> Option { + let operation_parts = consistent_composition(operation)?; + let companion_parts = consistent_composition(companion)?; + let proved = operation.wallet_succeeded + && companion.wallet_succeeded + && operation + .delivery + .is_some_and(|delivery| delivery.skipped_all(messages)) + && companion + .delivery + .is_some_and(|delivery| delivery.created_all(messages)) + && companion.summary.mc_block_seqno == operation.summary.mc_block_seqno + && companion_parts.gas_used == operation_parts.gas_used + && companion_parts.storage_fees == operation_parts.storage_fees; + if !proved { + return None; + } + #[allow( + clippy::arithmetic_side_effects, + reason = "a consistent composition rules out BigUint underflow and addition cannot overflow" + )] + let fee = operation.summary.wallet_fees_nanograms.as_biguint() + - &operation_parts.total_action_fees + + &companion_parts.total_action_fees; + (fee != BigUint::default()).then(|| fee.into()) +} + +/// The root fee components of `emulation` when its root fee is positive and +/// contains the action fee; no other answer can price a message. +fn consistent_composition(emulation: &EvaluatedEmulation) -> Option<&RootComposition> { + let parts = emulation.composition.as_ref()?; + let total = emulation.summary.wallet_fees_nanograms.as_biguint(); + (total != &BigUint::default() && total >= &parts.total_action_fees).then_some(parts) +} + +/// The refusal for an emulation in which the source wallet did not complete. +fn rejected_emulation(evaluated: &EvaluatedEmulation, diagnostic: &str) -> WalletClientError { + WalletClientError::EmulationRejected { + diagnostic: diagnostic.to_owned(), + compute_exit_code: evaluated.compute_exit_code, + action_result_code: evaluated.action_result_code, + } +} + +const CREATED_NONE: &str = "emulated wallet created none of the messages"; +const CREATED_ONLY_SOME: &str = "emulated wallet created only some of the messages"; +const DELIVERY_UNREPORTED: &str = "emulation did not report the wallet's message delivery"; +const SPEND_UNPROVED: &str = "emulation did not establish the wallet's spend beyond the values"; + +/// The refusal of a default preview whose successful wallet transaction did +/// not create each of its `messages` outgoing messages, if any. +/// +/// A skipped message alone does not prove insufficient funds, so this is an +/// emulation refusal; an answer that records the delivery nowhere fails. +fn delivery_refusal(evaluated: &EvaluatedEmulation, messages: usize) -> Option { + match evaluated.message_creation(messages) { + Some(MessageCreation::Every) => None, + Some(MessageCreation::Nothing) => Some(rejected_emulation(evaluated, CREATED_NONE)), + Some(MessageCreation::Partial) => Some(rejected_emulation(evaluated, CREATED_ONLY_SOME)), + None => Some(WalletClientError::EmulationFailed { + diagnostic: DELIVERY_UNREPORTED.to_owned(), + }), + } +} + impl WalletClient { + /// Emulates `boc` for a preview and returns the emulation of a successful + /// wallet transaction. + /// + /// Every error ends the preview: a provider, parse or wallet failure + /// finishes it here, and after a lifecycle failure it has already ended. async fn emulate_preview_boc( &self, generation: u64, @@ -480,44 +796,232 @@ impl WalletClient { expected_source: &TonAddressString, emulation_request_id: HttpRequestId, boc: &Boc, - ) -> Result { - let emulation_request = build_emulation_request(config, emulation_request_id, boc) - .map_err(|error| { - self.preview_error( - generation, - WalletClientError::SendPreviewFailed { + ) -> Result { + let evaluated = self + .evaluate_preview_boc( + generation, + config, + expected_source, + emulation_request_id, + boc, + None, + ) + .await? + .map_err(|error| self.preview_error(generation, error))?; + + if !evaluated.wallet_succeeded { + return Err(self.preview_error( + generation, + rejected_emulation( + &evaluated, + "emulated transfer did not complete successfully", + ), + )); + } + + Ok(evaluated) + } + + /// Emulates one message for a preview without finishing the preview. + /// + /// The outer error is a lifecycle failure: the preview was replaced or + /// cancelled, or the client shut down. The inner error is the public + /// provider or parse failure, which the caller reports and finishes. + /// `mc_block_seqno` pins the emulated state to that block. + async fn evaluate_preview_boc( + &self, + generation: u64, + config: &WalletClientConfig, + expected_source: &TonAddressString, + emulation_request_id: HttpRequestId, + boc: &Boc, + mc_block_seqno: Option, + ) -> Result, WalletClientError> { + let emulation_request = + match build_emulation_request(config, emulation_request_id, boc, mc_block_seqno) { + Ok(request) => request, + Err(error) => { + return Ok(Err(WalletClientError::SendPreviewFailed { diagnostic: bounded_diagnostic(error.to_string()), - }, - ) - })?; + })); + } + }; - let evaluated = self + Ok(self .execute_tracked_preview_request(generation, &emulation_request) .await? .and_then(|body| parse_emulation(&body, expected_source)) .map_err(|error| { let not_accepted = is_message_not_accepted(&error); let diagnostic = bounded_diagnostic(error.developer_message); - let public = if not_accepted { + if not_accepted { WalletClientError::EmulationMessageNotAccepted { diagnostic } } else { WalletClientError::EmulationFailed { diagnostic } - }; - self.preview_error(generation, public) - })?; + } + })) + } - if !evaluated.wallet_succeeded { - return Err(self.preview_error( + /// Emulates the exact operation of a preview that asked for its fee. + /// + /// A created operation is the default preview, and it is a quote only + /// with the spend its answer establishes for `messages`. When the wallet + /// skipped every message, `companion` is emulated in the same preview, + /// pinned to the operation's block, to establish the operation's fee and + /// spend. The outer error is a lifecycle failure; the inner one is the + /// emulation error of the operation itself. + async fn quote_operation( + &self, + generation: u64, + config: &WalletClientConfig, + emulation_request_id: HttpRequestId, + boc: &Boc, + messages: &[SendMessage], + companion: impl FnOnce() -> Option, + ) -> Result, WalletClientError> { + let evaluated = match self + .evaluate_preview_boc( generation, - WalletClientError::EmulationRejected { - diagnostic: "emulated transfer did not complete successfully".to_owned(), - compute_exit_code: evaluated.compute_exit_code, - action_result_code: evaluated.action_result_code, + config, + &config.address, + emulation_request_id, + boc, + None, + ) + .await? + { + Ok(evaluated) => evaluated, + Err(error) => return Ok(Err(error)), + }; + if !evaluated.wallet_succeeded { + return Ok(Err(rejected_emulation( + &evaluated, + "emulated transfer did not complete successfully", + ))); + } + + let raw_fee = evaluated.summary.wallet_fees_nanograms.clone(); + let unusable = |operation_fee, operation_spend, error| { + Ok(Ok(OperationQuote::Unusable(UnusableQuote { + raw_fee: raw_fee.clone(), + operation_fee, + operation_spend, + error, + }))) + }; + match evaluated.delivery { + Some(delivery) if delivery.created_all(messages.len()) => { + if raw_fee.as_biguint() == &BigUint::default() { + return unusable( + None, + None, + WalletClientError::EmulationFailed { + diagnostic: "emulated wallet fee is zero".to_owned(), + }, + ); + } + match operation_spend(&raw_fee, &evaluated, messages) { + Some(spend) => Ok(Ok(OperationQuote::Created { + emulation: evaluated.summary, + spend, + })), + // The created operation's fee stands; without its spend + // the preview is no quote. + None => unusable( + Some(raw_fee.clone()), + None, + WalletClientError::EmulationFailed { + diagnostic: SPEND_UNPROVED.to_owned(), + }, + ), + } + } + Some(delivery) if delivery.skipped_all(messages.len()) => { + let (operation_fee, operation_spend) = match companion() { + Some(companion) => self + .quote_companion(generation, config, &evaluated, messages, &companion) + .await? + .map_or((None, None), |(fee, spend)| (Some(fee), spend)), + None => (None, None), + }; + unusable( + operation_fee, + operation_spend, + rejected_emulation(&evaluated, CREATED_NONE), + ) + } + Some(_) => unusable( + None, + None, + rejected_emulation(&evaluated, CREATED_ONLY_SOME), + ), + None => unusable( + None, + None, + WalletClientError::EmulationFailed { + diagnostic: DELIVERY_UNREPORTED.to_owned(), }, - )); + ), + } + } + + /// Emulates the zero-value companion at the operation's block and returns + /// the operation's fee when the two answers establish it, with the + /// operation's spend on `messages` when the companion's forwarding fees + /// establish that too. + /// + /// The companion request belongs to the same preview, so cancelling the + /// preview cancels it too. Only lifecycle failures are errors; any other + /// failure leaves the fee and the spend unknown. + async fn quote_companion( + &self, + generation: u64, + config: &WalletClientConfig, + operation: &EvaluatedEmulation, + messages: &[SendMessage], + companion: &Boc, + ) -> Result)>, WalletClientError> + { + if operation.composition.is_none() { + return Ok(None); } + let Ok(request_id) = self.allocate_preview_request_id(generation)? else { + return Ok(None); + }; + let evaluated = self + .evaluate_preview_boc( + generation, + config, + &config.address, + request_id, + companion, + Some(operation.summary.mc_block_seqno), + ) + .await?; + Ok(evaluated.ok().and_then(|companion| { + // The companion created the same messages outside their roots, so + // its forwarding fees are the operation's own (see + // `shortfall_companion`); the modes stay the operation's. + let fee = composite_fee(operation, &companion, messages.len())?; + let spend = operation_spend(&fee, &companion, messages); + Some((fee, spend)) + })) + } - Ok(evaluated.summary) + /// Allocates the identifier of a further request of the current preview. + /// + /// The outer error is a lifecycle failure; an exhausted identifier space + /// is returned inside. + fn allocate_preview_request_id( + &self, + generation: u64, + ) -> Result, WalletClientError> { + let mut state = self.lock()?; + ensure_running(&state)?; + if !state.is_current(OperationFamily::Preview, generation) { + return Err(WalletClientError::StateUnavailable); + } + Ok(state.allocate_request_id()) } fn preview_error(&self, generation: u64, error: WalletClientError) -> WalletClientError { @@ -588,3 +1092,3404 @@ impl WalletClient { Ok(()) } } + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::sync::mpsc; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use futures::executor::block_on; + use ton::block_tlb::{CommonMsgInfo, Msg}; + use ton::ton_core::cell::TonCell; + use ton::ton_core::traits::tlb::TLB; + use ton::ton_core::types::tlb_core::TLBCoins; + use ton::ton_wallet::WalletExtMsgBody; + + use super::*; + use crate::domain::ProtectedSecretRead; + use crate::wallet::crypto::{derive_wallet, derive_wallet_public_state}; + use crate::{ + HttpHostError, HttpHostErrorKind, HttpMethod, HttpResponse, JournalCompareExchange, + JournalCompareExchangeResult, JournalHostError, JournalKey, JournalRecord, Network, + NonEmptyString, ProtectedSecretHostError, ProtectedSecretRef, ProtectedSecretStore, + ProviderConfig, SendExpiration, SendMessageBody, WalletHttpHost, WalletPlatformHost, + }; + + /// A throwaway phrase; previews never read it. + const MNEMONIC: &str = + "notice tortoise soup strong gun divide offer process salon siren general carry"; + const DESTINATION: &str = "0:2222222222222222222222222222222222222222222222222222222222222222"; + const DESTINATION_B: &str = + "0:3333333333333333333333333333333333333333333333333333333333333333"; + /// The comment of the commented shapes. + const COMMENT: &str = "shortfall fee probe"; + /// The provider time of every scripted account read. + const PROVIDER_TIME: u64 = 1; + + /// A provider account state answered by [`ScriptedHost`]. + #[derive(Clone, Copy)] + struct Account { + balance: u64, + status: AccountStatus, + /// The `seqno` get-method answer, read only for an active account. + seqno: u32, + } + + /// The public rev00 wallet `0:C48024FF…9339` as read on mainnet. + const W4: Account = Account { + balance: 701_082_553, + status: AccountStatus::Active, + seqno: 4, + }; + /// The public rev00 wallet `0:BCF53F47…8F48`, with a 5-byte balance. + const W5: Account = Account { + balance: 100_006_637_868, + status: AccountStatus::Active, + seqno: 96, + }; + /// A never-funded throwaway rev00 wallet: no state on chain. + const NEVER_DEPLOYED: Account = Account { + balance: 0, + status: AccountStatus::Uninitialized, + seqno: 0, + }; + /// The public deployed rev00 wallet `0:94A0AC8B…9785` with a zero balance. + const DEPLOYED_ZERO: Account = Account { + balance: 0, + status: AccountStatus::Active, + seqno: 1, + }; + /// The public v3r1 wallet `0:386E0E9B…2899`, whose balance is below the + /// flat gas price of 6667. + const DUST: Account = Account { + balance: 4_379, + status: AccountStatus::Active, + seqno: 3, + }; + + /// The root wallet transaction fields of one emulateTrace answer that the + /// engine reads; [`answer`] builds the rest of the answer around them. + /// + /// Unless a constant says otherwise, these copy the fields of mainnet + /// answers for the wallets above (fake signature, `ignore_chksig`), with + /// the account rewritten to the test wallet: faithful fixtures, not a chain + /// proof for the test wallet. Every one of them ran the wallet code with + /// compute exit 0 and action result 0. + #[derive(Clone, Copy)] + struct Root { + block: u32, + total_fees: u64, + storage_fees: u64, + gas_used: u64, + /// `tot_actions`, `skipped_actions`, `msgs_created`. + delivery: (u16, u16, u16), + /// `total_action_fees`, left out of the answer when zero, as the + /// protocol does. + action_fees: u64, + /// `total_fwd_fees`, left out of the answer when zero (`null` in + /// every captured skipped answer), as the protocol does. + forwarding: u64, + } + + impl Root { + /// This root's fee composite with `companion`: the operation's fee. + const fn composite(self, companion: Self) -> u64 { + self.total_fees - self.action_fees + companion.action_fees + } + } + + /// The wallet's spend beyond `value` that a captured created answer + /// shows: its root transaction's `account_state_before.balance` minus + /// its `account_state_after.balance`, minus the value. An oracle + /// independent of the engine's fee fields. + const fn debit_spend(value: u64, before: u64, after: u64) -> u64 { + before - after - value + } + + const SKIPPED: (u16, u16, u16) = (1, 1, 0); + const CREATED: (u16, u16, u16) = (1, 0, 1); + + /// `W4` at block 104746942: 1e9 (4 bytes), empty body, modes 3, 2 and 18. + const W4_SKIPPED_EMPTY: Root = w4(396_627, SKIPPED, 1_666, 0); + /// `W4` at block 104746942: 5e9 (5 bytes), empty body, modes 3 and 2. + const W4_SKIPPED_EMPTY_5B: Root = w4(397_160, SKIPPED, 1_666, 0); + /// `W4` at block 104746942: 1e9, comment, mode 3. + const W4_SKIPPED_COMMENT: Root = w4(408_894, SKIPPED, 1_666, 0); + /// `W4` at block 104746942: 1e9, opcode, query id and a referenced text, mode 3. + const W4_SKIPPED_PAYLOAD: Root = w4(421_493, SKIPPED, 3_332, 0); + /// `W4` at block 104746942: 1e9, `StateInit` and comment, modes 3 and 2. + const W4_SKIPPED_INIT: Root = w4(460_626, SKIPPED, 4_998, 0); + /// `W4` at block 104746942: value 0, empty body, modes 3 and 19. + const W4_ZERO_EMPTY: Root = w4(417_272, CREATED, 24_444, 73_334); + /// `W4` at block 104746942: value 0, empty body, modes 2 and 18, which + /// take the forwarding fee from the zero value and skip. + const W4_ZERO_EMPTY_KEPT_MODE: Root = w4(392_828, SKIPPED, 0, 0); + /// `W4` at block 104746942: value 0, comment, mode 3. + const W4_ZERO_COMMENT: Root = w4(433_627, CREATED, 28_533, 85_601); + /// `W4` at block 104746942: value 0, the payload above, mode 3. + const W4_ZERO_PAYLOAD: Root = w4(448_205, CREATED, 32_177, 96_534); + /// `W4` at block 104746942: value 0, `StateInit` and comment, mode 3. + const W4_ZERO_INIT: Root = w4(498_026, CREATED, 44_532, 133_601); + /// `W4` at block 104746942: 1e8 (4 bytes), empty body, modes 3, 2, 18 and 19. + const W4_CREATED_EMPTY: Root = w4(419_405, CREATED, 24_444, 73_334); + /// `W4` at block 104746942: 1e7 (3 bytes), empty body, mode 3. + const W4_CREATED_EMPTY_3B: Root = w4(418_872, CREATED, 24_444, 73_334); + /// `W4` at block 104746942: 1e8, comment, mode 3. + const W4_CREATED_COMMENT: Root = w4(435_761, CREATED, 28_533, 85_601); + /// `W4` at block 104746942: 1e8, the payload above, mode 3. + const W4_CREATED_PAYLOAD: Root = w4(450_338, CREATED, 32_177, 96_534); + /// `W4` at block 104746942: 1e8, `StateInit` and comment, modes 3 and 2. + const W4_CREATED_INIT: Root = w4(500_160, CREATED, 44_532, 133_601); + + /// `W5` at block 104747074: 5e11 (5 bytes), empty body, mode 3. + const W5_SKIPPED_EMPTY_5B: Root = w5(397_140, SKIPPED, 1_666, 0); + /// `W5` at block 104747074: 2e12 (6 bytes), empty body, mode 3. + const W5_SKIPPED_EMPTY_6B: Root = w5(397_674, SKIPPED, 1_666, 0); + /// `W5` at block 104747074: 5e11, comment, mode 18. + const W5_SKIPPED_COMMENT: Root = w5(409_407, SKIPPED, 1_666, 0); + /// `W5` at block 104747074: 5e11, `StateInit` and comment, mode 2. + const W5_SKIPPED_INIT: Root = w5(461_139, SKIPPED, 4_998, 0); + /// `W5` at block 104747074: value 0, empty body, mode 3. + const W5_ZERO_EMPTY: Root = w5(417_252, CREATED, 24_444, 73_334); + /// `W5` at block 104747074: value 0, comment, mode 19. + const W5_ZERO_COMMENT: Root = w5(433_607, CREATED, 28_533, 85_601); + /// `W5` at block 104747074: value 0, `StateInit` and comment, mode 3. + const W5_ZERO_INIT: Root = w5(498_006, CREATED, 44_532, 133_601); + /// `W5` at block 104747074: 5e9 (5 bytes), empty body, mode 3. + const W5_CREATED_EMPTY_5B: Root = w5(419_918, CREATED, 24_444, 73_334); + /// `W5` at block 104747074: 5e9, comment, mode 18. + const W5_CREATED_COMMENT: Root = w5(436_274, CREATED, 28_533, 85_601); + /// `W5` at block 104747074: 5e9, `StateInit` and comment, mode 2. + const W5_CREATED_INIT: Root = w5(500_673, CREATED, 44_532, 133_601); + + /// `W4` at the earlier block 104737326, empty body, mode 3: every value + /// from 700614284 through 700685951 and 1e9, all of 4 bytes. + const W4_EARLIER_SKIPPED: Root = w4_earlier(396_602, SKIPPED, 1_666, 0); + /// `W4` at block 104737326: value 0, empty body, mode 3. + const W4_EARLIER_ZERO: Root = w4_earlier(417_247, CREATED, 24_444, 73_334); + /// `W4` at block 104737326: 1e8, 5e8, 7e8 and 700614283, the largest + /// value whose message the wallet still created. + const W4_EARLIER_CREATED: Root = w4_earlier(419_380, CREATED, 24_444, 73_334); + + const fn w4( + total_fees: u64, + delivery: (u16, u16, u16), + action_fees: u64, + forwarding: u64, + ) -> Root { + Root { + block: 104_746_942, + total_fees, + storage_fees: 26, + gas_used: 3_560, + delivery, + action_fees, + forwarding, + } + } + + const fn w5( + total_fees: u64, + delivery: (u16, u16, u16), + action_fees: u64, + forwarding: u64, + ) -> Root { + Root { + block: 104_747_074, + total_fees, + storage_fees: 6, + gas_used: 3_560, + delivery, + action_fees, + forwarding, + } + } + + const fn w4_earlier( + total_fees: u64, + delivery: (u16, u16, u16), + action_fees: u64, + forwarding: u64, + ) -> Root { + Root { + block: 104_737_326, + total_fees, + storage_fees: 1, + gas_used: 3_560, + delivery, + action_fees, + forwarding, + } + } + + /// One scripted answer to an emulateTrace request. + enum Reply { + /// An HTTP status and a JSON body. + Json(u16, serde_json::Value), + /// An HTTP 200 body that is not JSON. + Malformed, + /// A host transport failure. + Offline, + /// Waits until the test releases the request, then answers like the + /// inner reply. + Held(Box), + } + + /// The complete answer for `root`, in the shape Toncenter returns. + fn answer_json(address: &str, root: Root) -> serde_json::Value { + let (total_actions, skipped_actions, messages_created) = root.delivery; + let mut action = serde_json::json!({ + "success": true, + "valid": true, + "no_funds": false, + "result_code": 0, + "tot_actions": total_actions, + "spec_actions": 0, + "skipped_actions": skipped_actions, + "msgs_created": messages_created, + }); + if root.action_fees != 0 { + action["total_action_fees"] = root.action_fees.to_string().into(); + } + if root.forwarding != 0 { + action["total_fwd_fees"] = root.forwarding.to_string().into(); + } + // One entry per created message, as in every captured answer, and an + // empty list for a skipped one; the engine reads only its length. + let out_msgs = (0..messages_created) + .map(|_| serde_json::json!({ "source": address, "destination": DESTINATION })) + .collect::>(); + serde_json::json!({ + "mc_block_seqno": root.block, + "trace": { "tx_hash": "root" }, + "transactions": { + "root": { + "account": address, + "total_fees": root.total_fees.to_string(), + "out_msgs": out_msgs, + "description": { + "type": "ord", + "aborted": false, + "storage_ph": { + "storage_fees_collected": root.storage_fees.to_string(), + "status_change": "unchanged" + }, + "compute_ph": { + "skipped": false, + "success": true, + "exit_code": 0, + "gas_used": root.gas_used.to_string() + }, + "action": action, + } + } + }, + "is_incomplete": false, + }) + } + + fn answer(address: &str, root: Root) -> Reply { + Reply::Json(200, answer_json(address, root)) + } + + /// The answer for `root` with its root transaction changed by `edit`. + fn edited(address: &str, root: Root, edit: fn(&mut serde_json::Value)) -> Reply { + let mut body = answer_json(address, root); + edit(&mut body["transactions"]["root"]); + Reply::Json(200, body) + } + + /// The HTTP 500 answer Toncenter gives when the account rejects the + /// external message before its code runs, as captured for the + /// never-deployed, the deployed zero and the dust wallets. + fn rejection(address: &str) -> Reply { + let account = address.split_once(':').map_or(address, |(_, hash)| hash); + Reply::Json( + 500, + serde_json::json!({ + "error": format!( + "failed to emulate shard block: cannot run message on account inbound \ + external message rejected by account {account} before smart-contract \ + execution" + ) + }), + ) + } + + /// A provider call that a preview makes. + #[derive(Debug, Clone, PartialEq, Eq)] + enum Call { + /// `getAddressInformation` for the configured wallet. + Account, + /// The JSON-RPC `runGetMethod` read of the configured wallet's `seqno`. + Seqno, + /// `emulateTrace` with the `mc_block_seqno` of its body, `None` for `null`. + Emulate(Option), + /// Any other request, which the host fails (`sendBoc` included). + Unexpected(String), + } + + const UNTIL_OPERATION: [Call; 3] = [Call::Account, Call::Seqno, Call::Emulate(None)]; + + /// Account, seqno, the unpinned operation and the companion pinned to `block`. + fn with_companion(block: u32) -> Vec { + vec![ + Call::Account, + Call::Seqno, + Call::Emulate(None), + Call::Emulate(Some(block.into())), + ] + } + + /// Answers the configured wallet's account read and `seqno` read from an + /// [`Account`] and each emulateTrace from the next scripted [`Reply`]. + /// Every request is recorded; any other request fails. + struct ScriptedHost { + address: String, + account: Account, + emulations: Mutex>, + requests: Mutex>, + cancelled: Mutex>, + hold: Mutex, mpsc::Receiver<()>)>>, + } + + impl ScriptedHost { + fn requests(&self) -> Vec { + self.requests.lock().expect("request lock").clone() + } + + fn calls(&self) -> Vec { + self.requests() + .iter() + .map(|request| self.classify(request)) + .collect() + } + + /// The JSON bodies of the recorded emulateTrace requests, in order. + fn emulations(&self) -> Vec { + self.requests() + .iter() + .filter(|request| matches!(self.classify(request), Call::Emulate(_))) + .map(|request| serde_json::from_slice(&request.body).expect("emulation body")) + .collect() + } + + fn cancelled(&self) -> Vec { + self.cancelled.lock().expect("cancel lock").clone() + } + + fn classify(&self, request: &HttpRequest) -> Call { + let unexpected = || Call::Unexpected(request.url.clone()); + let Ok(url) = url::Url::parse(&request.url) else { + return unexpected(); + }; + if url.host_str() != Some("provider.example") { + return unexpected(); + } + let body = || serde_json::from_slice::(&request.body).ok(); + match (request.method, url.path()) { + (HttpMethod::Get, "/api/v2/getAddressInformation") => { + let query = url.query_pairs().into_owned().collect::>(); + if query == [("address".to_owned(), self.address.clone())] { + Call::Account + } else { + unexpected() + } + } + (HttpMethod::Post, "/api/v2/jsonRPC") => { + if let Some(body) = body() + && body["method"] == "runGetMethod" + && body["params"]["method"] == "seqno" + && body["params"]["address"] == self.address.as_str() + { + Call::Seqno + } else { + unexpected() + } + } + (HttpMethod::Post, "/api/emulate/v1/emulateTrace") => { + let Some(body) = body() else { + return unexpected(); + }; + let block = &body["mc_block_seqno"]; + if block.is_null() { + Call::Emulate(None) + } else { + block + .as_u64() + .map_or_else(unexpected, |block| Call::Emulate(Some(block))) + } + } + _ => unexpected(), + } + } + + fn respond( + &self, + request: &HttpRequest, + reply: Reply, + ) -> Result { + let (status, body) = match reply { + Reply::Json(status, body) => { + (status, serde_json::to_vec(&body).expect("response JSON")) + } + Reply::Malformed => (200, b"{\"mc_block_seqno\": 104746942, \"trace\"".to_vec()), + Reply::Offline => { + return Err(HttpHostError::Failed { + kind: HttpHostErrorKind::Offline, + diagnostic: "scripted offline".to_owned(), + }); + } + Reply::Held(reply) => { + let (held, release) = self + .hold + .lock() + .expect("hold lock") + .take() + .expect("the test armed a hold"); + held.send(request.id).expect("the test waits for the hold"); + release + .recv_timeout(Duration::from_secs(60)) + .expect("the test releases the hold"); + return self.respond(request, *reply); + } + }; + Ok(HttpResponse { + status, + headers: Vec::new(), + body, + final_url: request.url.clone(), + }) + } + } + + #[async_trait::async_trait] + impl WalletHttpHost for ScriptedHost { + async fn execute_http(&self, request: HttpRequest) -> Result { + self.requests + .lock() + .expect("request lock") + .push(request.clone()); + let reply = match self.classify(&request) { + Call::Account => Reply::Json( + 200, + serde_json::json!({ + "ok": true, + "result": { + "balance": self.account.balance.to_string(), + "state": state_name(self.account.status), + "sync_utime": PROVIDER_TIME + } + }), + ), + Call::Seqno => Reply::Json( + 200, + serde_json::json!({ + "ok": true, + "result": { + "exit_code": 0, + "stack": [["num", format!("{:#x}", self.account.seqno)]] + } + }), + ), + Call::Emulate(_) => self + .emulations + .lock() + .expect("emulation lock") + .pop_front() + .expect("a scripted emulation answer"), + Call::Unexpected(_) => { + return Err(HttpHostError::Failed { + kind: HttpHostErrorKind::Other, + diagnostic: "unexpected scripted request".to_owned(), + }); + } + }; + self.respond(&request, reply) + } + + async fn cancel_http(&self, request_id: HttpRequestId) { + self.cancelled.lock().expect("cancel lock").push(request_id); + } + } + + /// The Toncenter `state` string for `status`. + const fn state_name(status: AccountStatus) -> &'static str { + match status { + AccountStatus::Nonexistent => "nonexistent", + AccountStatus::Uninitialized => "uninitialized", + AccountStatus::Active => "active", + AccountStatus::Frozen => "frozen", + AccountStatus::Unknown => "unknown", + } + } + + /// A preview reads no protected secret and no journal. + struct NoSecretHost; + + #[async_trait::async_trait] + impl WalletPlatformHost for NoSecretHost { + async fn read_protected_secret( + &self, + _request: ProtectedSecretRead, + ) -> Result, ProtectedSecretHostError> { + panic!("a preview must not read the protected secret") + } + + async fn store_protected_secret( + &self, + _request: ProtectedSecretStore, + ) -> Result<(), ProtectedSecretHostError> { + panic!("a preview must not store a secret") + } + + async fn delete_protected_secret( + &self, + _secret_ref: ProtectedSecretRef, + ) -> Result<(), ProtectedSecretHostError> { + panic!("a preview must not delete a secret") + } + + async fn load_journal( + &self, + _key: JournalKey, + ) -> Result, JournalHostError> { + panic!("a preview must not read the journal") + } + + async fn compare_exchange_journal( + &self, + _mutation: JournalCompareExchange, + ) -> Result { + panic!("a preview must not write the journal") + } + } + + fn client_config() -> WalletClientConfig { + let wallet = derive_wallet(MNEMONIC, Network::Testnet).expect("wallet derives"); + WalletClientConfig { + record_id: NonEmptyString::try_from("shortfall-preview-test").expect("record ID"), + address: TonAddressString::from_address(&wallet.address, Network::Testnet), + public_key: wallet.key_pair.public_key.to_vec(), + local_secret_ref: None, + network: Network::Testnet, + send_validity_seconds: 300, + resolution_margin_seconds: 60, + providers: ProviderConfig { + toncenter_base_url: "https://provider.example".to_owned(), + dns_root_address: None, + request_timeout_ms: 15_000, + }, + } + } + + /// A client over a fresh [`ScriptedHost`] and the panicking [`NoSecretHost`]. + struct Scripted { + client: Arc, + http: Arc, + } + + impl Scripted { + /// `emulations` receives the test wallet's raw address for the answers. + fn new(account: Account, emulations: impl FnOnce(&str) -> Vec) -> Self { + let config = client_config(); + let raw = config.address.as_address().to_hex().to_uppercase(); + let http = Arc::new(ScriptedHost { + address: config.address.as_str().to_owned(), + account, + emulations: Mutex::new(emulations(&raw).into()), + requests: Mutex::new(Vec::new()), + cancelled: Mutex::new(Vec::new()), + hold: Mutex::new(None), + }); + let client = WalletClient::new(config, http.clone(), Arc::new(NoSecretHost)) + .expect("client builds"); + Self { client, http } + } + + fn preview(&self, request: SendPreviewRequest) -> Result { + let result = block_on(self.client.preview_send(request)); + assert!( + self.client.lock().expect("state").active_preview.is_none(), + "the preview slot is finished" + ); + result + } + + fn unused_answers(&self) -> usize { + self.http.emulations.lock().expect("emulation lock").len() + } + } + + /// Runs one preview against scripted answers and returns its result and + /// provider calls; every scripted answer must be used. + fn run( + account: Account, + request: SendPreviewRequest, + emulations: impl FnOnce(&str) -> Vec, + ) -> (Result, Scripted) { + let scripted = Scripted::new(account, emulations); + let result = scripted.preview(request); + assert_eq!( + scripted.unused_answers(), + 0, + "every scripted answer is used" + ); + assert!( + scripted + .http + .calls() + .iter() + .all(|call| !matches!(call, Call::Unexpected(_))), + "{:?}", + scripted.http.calls() + ); + (result, scripted) + } + + /// The message shapes of the captured answers. + #[derive(Clone, Copy, Debug)] + enum Shape { + Empty, + Comment, + /// A 32-bit opcode, a 64-bit query id and a referenced text cell. + Payload, + /// A destination `StateInit` with a comment. + StateInit, + } + + fn payload() -> Boc { + let mut text = TonCell::builder(); + text.write_bits(COMMENT.as_bytes(), COMMENT.len() * 8) + .expect("text"); + let text = text.build().expect("text cell"); + let mut body = TonCell::builder(); + body.write_bits([0x12_u8, 0x34, 0x56, 0x78], 32) + .expect("opcode"); + body.write_bits([0_u8, 0, 0, 0, 0, 0, 0, 7], 64) + .expect("query id"); + body.write_ref(text).expect("text reference"); + let body = body.build().expect("payload cell"); + Boc::try_from(body.to_boc().expect("payload BOC")).expect("payload") + } + + fn state_init() -> Boc { + let (_, state_init) = + derive_wallet_public_state(&[7; 32], Network::Testnet).expect("state init derives"); + Boc::try_from(state_init.to_boc().expect("state init BOC")).expect("state init") + } + + fn message(nanograms: u64, send_mode: Option, shape: Shape) -> SendMessage { + SendMessage { + destination: TonAddressString::try_from(DESTINATION).expect("destination"), + amount: SendAmount::exact(nanograms.to_string()).expect("amount"), + body: match shape { + Shape::Empty => SendMessageBody::Empty, + Shape::Comment | Shape::StateInit => SendMessageBody::Comment { + text: COMMENT.to_owned(), + }, + Shape::Payload => SendMessageBody::RawPayload { boc: payload() }, + }, + bounce: false, + state_init: matches!(shape, Shape::StateInit).then(state_init), + send_mode, + } + } + + fn request(messages: Vec, estimate_shortfall: bool) -> SendPreviewRequest { + SendPreviewRequest { + intent: SendIntent { + expiration: SendExpiration::EngineDefault, + messages, + }, + estimate_shortfall, + } + } + + fn single( + nanograms: u64, + send_mode: Option, + shape: Shape, + estimate_shortfall: bool, + ) -> SendPreviewRequest { + request( + vec![message(nanograms, send_mode, shape)], + estimate_shortfall, + ) + } + + /// The fake-signed external message that the default builder makes for + /// `request` from `account` at the scripted provider time. + fn expected_boc(request: &SendPreviewRequest, account: Account) -> Boc { + let config = client_config(); + let fresh = FreshSendAccount { + status: account.status, + seqno: if matches!(account.status, AccountStatus::Active) { + account.seqno + } else { + 0 + }, + }; + let valid_until = resolve_send_expiration( + &request.intent.expiration, + PROVIDER_TIME, + config.send_validity_seconds, + ) + .expect("expiration resolves"); + prepare_transfer_emulation( + &config.address, + &config.public_key, + config.network, + request, + &fresh, + valid_until, + ) + .expect("message builds") + } + + /// One recorded emulation, decoded with the TON readers. + struct Decoded { + boc: Boc, + external: Msg, + wallet: WalletExtMsgBody, + messages: Vec>, + } + + fn decode(body: &serde_json::Value) -> Decoded { + let boc = Boc::try_from(body["boc"].as_str().expect("BOC string")).expect("BOC"); + let root = TonCell::from_boc(boc.as_bytes().to_vec()).expect("BOC parses"); + let external = Msg::::from_cell(&root).expect("external message parses"); + let (wallet, _signature) = + WalletExtMsgBody::read_signed(&mut external.body.value.parser()).expect("request"); + let messages = wallet + .msgs + .iter() + .map(|cell| Msg::::from_cell(cell).expect("internal message parses")) + .collect(); + Decoded { + boc, + external, + wallet, + messages, + } + } + + fn coins(message: &Msg) -> TLBCoins { + let CommonMsgInfo::Int(info) = &message.info else { + panic!("wallet actions are internal messages"); + }; + info.value.coins + } + + /// Asserts that `operation` is the default builder's message for + /// `request` and that `companion` is the same external message with + /// every value 0 and modes 2 and 18 raised to 3 and 19, and nothing else + /// changed. + fn assert_operation_and_companion( + request: &SendPreviewRequest, + account: Account, + operation: &serde_json::Value, + companion: &serde_json::Value, + ) { + let operation = decode(operation); + let companion = decode(companion); + let defaulted = SendPreviewRequest { + estimate_shortfall: false, + ..request.clone() + }; + assert_eq!(operation.boc, expected_boc(&defaulted, account)); + for (message, sent) in request.intent.messages.iter().zip(&operation.messages) { + let SendAmount::Exact { nanograms } = &message.amount else { + panic!("a shortfall operation has exact values"); + }; + let nanograms = nanograms.try_to::().expect("value fits"); + assert_eq!(coins(sent), TLBCoins::new(nanograms)); + } + + assert_eq!(companion.external.info, operation.external.info); + assert_eq!(companion.external.init, operation.external.init); + assert_eq!(companion.wallet.wallet_id, operation.wallet.wallet_id); + assert_eq!(companion.wallet.valid_until, operation.wallet.valid_until); + assert_eq!(companion.wallet.msg_seqno, operation.wallet.msg_seqno); + let raised: Vec = operation + .wallet + .msgs_modes + .iter() + .map(|mode| match mode { + 2 => 3, + 18 => 19, + mode => *mode, + }) + .collect(); + assert_eq!(companion.wallet.msgs_modes, raised); + assert_eq!(companion.wallet.msgs.len(), operation.wallet.msgs.len()); + for (sent, cell) in operation.messages.iter().zip(&companion.wallet.msgs) { + let mut zeroed = sent.clone(); + let CommonMsgInfo::Int(info) = &mut zeroed.info else { + panic!("wallet actions are internal messages"); + }; + assert!(info.value.other.is_empty()); + info.value.coins = TLBCoins::ZERO; + let zeroed = zeroed.to_cell().expect("message serializes"); + assert_eq!( + zeroed.hash().expect("hash"), + cell.hash().expect("hash"), + "the companion message is the operation's with value 0" + ); + } + } + + fn decimal(value: u64) -> UnsignedDecimalString { + UnsignedDecimalString::from(value) + } + + fn short( + account: Account, + value: u64, + fee: Option, + spend: Option, + ) -> WalletClientError { + WalletClientError::InsufficientBalance { + available_nanograms: decimal(account.balance), + requested_nanograms: decimal(value), + operation_fee_nanograms: fee.map(decimal), + operation_spend_nanograms: spend.map(decimal), + } + } + + fn short_for_fees( + account: Account, + value: u64, + estimated: u64, + fee: Option, + spend: Option, + ) -> WalletClientError { + WalletClientError::InsufficientBalanceForFees { + available_nanograms: decimal(account.balance), + requested_nanograms: decimal(value), + estimated_fee_nanograms: decimal(estimated), + operation_fee_nanograms: fee.map(decimal), + operation_spend_nanograms: spend.map(decimal), + } + } + + /// The refusal of a value whose spend does not fit: above the balance + /// the value refusal, otherwise the fee refusal, both with the + /// operation's fee and spend. + fn spend_refusal(account: Account, value: u64, fee: u64, spend: u64) -> WalletClientError { + if value > account.balance { + short(account, value, Some(fee), Some(spend)) + } else { + short_for_fees(account, value, fee, Some(fee), Some(spend)) + } + } + + const SPEND_UNPROVED: &str = "emulation did not establish the wallet's spend beyond the values"; + + fn unproved_spend() -> WalletClientError { + WalletClientError::EmulationFailed { + diagnostic: SPEND_UNPROVED.to_owned(), + } + } + + fn rejected(diagnostic: &str) -> WalletClientError { + WalletClientError::EmulationRejected { + diagnostic: diagnostic.to_owned(), + compute_exit_code: Some(0), + action_result_code: Some(0), + } + } + + const NONE_CREATED: &str = "emulated wallet created none of the messages"; + const ONLY_SOME: &str = "emulated wallet created only some of the messages"; + + fn unreported() -> WalletClientError { + WalletClientError::EmulationFailed { + diagnostic: "emulation did not report the wallet's message delivery".to_owned(), + } + } + + /// The successful preview of `request` from `account` for the answer of + /// `root`, built from the fixture rather than by the engine's parser. + fn expected_preview(request: &SendPreviewRequest, account: Account, root: Root) -> SendPreview { + let config = client_config(); + let raw = config.address.as_address().to_hex().to_uppercase(); + SendPreview { + messages: request.intent.messages.clone(), + valid_until: resolve_send_expiration( + &request.intent.expiration, + PROVIDER_TIME, + config.send_validity_seconds, + ) + .expect("expiration resolves"), + message_boc_base64: expected_boc(request, account), + emulation: SendEmulation { + mc_block_seqno: root.block, + wallet_fees_nanograms: decimal(root.total_fees), + trace_fees_nanograms: decimal(root.total_fees), + transaction_count: 1, + actions: Vec::new(), + transactions: vec![crate::SendEmulationTransaction { + account: TonAddressString::try_from(raw).expect("raw address"), + succeeded: true, + is_root: true, + }], + trace_succeeded: true, + is_incomplete: false, + }, + operation_spend_nanograms: None, + } + } + + /// [`expected_preview`] of a preview that asked for the operation's fee, + /// with the operation's `spend`. + fn expected_quote( + request: &SendPreviewRequest, + account: Account, + root: Root, + spend: u64, + ) -> SendPreview { + let defaulted = SendPreviewRequest { + estimate_shortfall: false, + ..request.clone() + }; + SendPreview { + operation_spend_nanograms: Some(decimal(spend)), + ..expected_preview(&defaulted, account, root) + } + } + + /// The complete requests of a default preview of `request` from an active + /// `account` on a fresh client: the account, the seqno and one unpinned + /// emulation of the default builder's message, with identifiers 1 to 3. + fn expected_requests(request: &SendPreviewRequest, account: Account) -> Vec { + let config = client_config(); + vec![ + build_toncenter_v2_request( + &config, + HttpRequestId { value: 1 }, + "getAddressInformation", + &[("address", config.address.as_str())], + ) + .expect("account request builds"), + build_seqno_request(&config, HttpRequestId { value: 2 }).expect("seqno request builds"), + build_emulation_request( + &config, + HttpRequestId { value: 3 }, + &expected_boc(request, account), + None, + ) + .expect("emulation request builds"), + ] + } + + /// Synthetic: a created two-message answer at `W4`'s block, the + /// one-message capture plus a second empty message's action and + /// forwarding fees; not chain data. + const W4_CREATED_TWO: Root = Root { + total_fees: 443_849, + delivery: (2, 0, 2), + action_fees: 48_888, + forwarding: 146_668, + ..W4_CREATED_EMPTY + }; + + /// A two-message intent for the synthetic two-message answers. + fn batch() -> SendPreviewRequest { + request( + vec![ + message(100_000_000, Some(2), Shape::Empty), + message(100_000_000, None, Shape::Comment), + ], + false, + ) + } + + /// Without the flag a value above the balance still ends after the account read. + #[test] + fn default_preview_above_the_balance_reads_only_the_account() { + let (result, scripted) = run( + W4, + single(1_000_000_000, Some(2), Shape::Empty, false), + |_| Vec::new(), + ); + assert_eq!(result, Err(short(W4, 1_000_000_000, None, None))); + assert_eq!(scripted.http.calls(), [Call::Account]); + } + + /// Above the balance the skipped operation is priced by a zero-value + /// mode-3 companion pinned to the operation's block; the operation + /// itself stays the exact requested message. Its mode-2 spend is the + /// spend that the same block's created mode-2 answer debited. + #[test] + fn a_value_above_the_balance_carries_the_composite_fee() { + let request = single(1_000_000_000, Some(2), Shape::Empty, true); + let (result, scripted) = run(W4, request.clone(), |address| { + vec![ + answer(address, W4_SKIPPED_EMPTY), + answer(address, W4_ZERO_EMPTY), + ] + }); + let fee = W4_SKIPPED_EMPTY.composite(W4_ZERO_EMPTY); + assert_eq!(fee, W4_CREATED_EMPTY.total_fees, "equals the direct quote"); + // Captured mode-2 1e8 answer: 701082553 before, 600687592 after. + let spend = debit_spend(100_000_000, 701_082_553, 600_687_592); + assert_eq!(spend, 394_961); + assert_eq!( + result, + Err(short(W4, 1_000_000_000, Some(fee), Some(spend))) + ); + assert_eq!( + scripted.http.calls(), + with_companion(W4_SKIPPED_EMPTY.block) + ); + let ids: Vec = scripted + .http + .requests() + .iter() + .map(|request| request.id.value) + .collect(); + assert!(ids.windows(2).all(|pair| pair[0] < pair[1]), "{ids:?}"); + + let emulations = scripted.http.emulations(); + assert_operation_and_companion(&request, W4, &emulations[0], &emulations[1]); + assert_eq!(decode(&emulations[0]).wallet.msgs_modes, [2]); + assert_eq!(decode(&emulations[1]).wallet.msgs_modes, [3]); + assert_eq!(decode(&emulations[1]).wallet.msg_seqno, W4.seqno); + } + + /// Each send mode the served path accepts and each captured message + /// shape gets the composite of its own captured answers, which equals + /// the direct quote of an affordable message of the same shape and value + /// length at the same block, and the spend that this direct answer + /// debited from the wallet: the forwarding remainder added under +1, the + /// action fee left out without it. + #[test] + fn every_supported_mode_and_shape_gets_its_exact_composite_fee() { + // Wallet, mode, shape, operation, companion and direct quote, with + // the direct answer's value and captured balances before and after. + // Mode 19 itself was not emulated above the balance; its row reuses + // the skipped answer captured identically for modes 3, 2 and 18. + let rows = [ + ( + W4, + None, + Shape::Empty, + W4_SKIPPED_EMPTY, + W4_ZERO_EMPTY, + W4_CREATED_EMPTY, + (100_000_000, 701_082_553, 600_614_258), + ), + ( + W4, + Some(3), + Shape::Empty, + W4_SKIPPED_EMPTY, + W4_ZERO_EMPTY, + W4_CREATED_EMPTY, + (100_000_000, 701_082_553, 600_614_258), + ), + ( + W4, + Some(2), + Shape::Empty, + W4_SKIPPED_EMPTY, + W4_ZERO_EMPTY, + W4_CREATED_EMPTY, + (100_000_000, 701_082_553, 600_687_592), + ), + ( + W4, + Some(18), + Shape::Empty, + W4_SKIPPED_EMPTY, + W4_ZERO_EMPTY, + W4_CREATED_EMPTY, + (100_000_000, 701_082_553, 600_687_592), + ), + ( + W4, + Some(19), + Shape::Empty, + W4_SKIPPED_EMPTY, + W4_ZERO_EMPTY, + W4_CREATED_EMPTY, + (100_000_000, 701_082_553, 600_614_258), + ), + ( + W4, + None, + Shape::Comment, + W4_SKIPPED_COMMENT, + W4_ZERO_COMMENT, + W4_CREATED_COMMENT, + (100_000_000, 701_082_553, 600_589_724), + ), + ( + W4, + None, + Shape::Payload, + W4_SKIPPED_PAYLOAD, + W4_ZERO_PAYLOAD, + W4_CREATED_PAYLOAD, + (100_000_000, 701_082_553, 600_567_858), + ), + ( + W4, + None, + Shape::StateInit, + W4_SKIPPED_INIT, + W4_ZERO_INIT, + W4_CREATED_INIT, + (100_000_000, 701_082_553, 600_493_324), + ), + ( + W4, + Some(2), + Shape::StateInit, + W4_SKIPPED_INIT, + W4_ZERO_INIT, + W4_CREATED_INIT, + (100_000_000, 701_082_553, 600_626_925), + ), + ( + W5, + Some(18), + Shape::Comment, + W5_SKIPPED_COMMENT, + W5_ZERO_COMMENT, + W5_CREATED_COMMENT, + (5_000_000_000, 100_006_637_868, 95_006_230_127), + ), + ( + W5, + Some(2), + Shape::StateInit, + W5_SKIPPED_INIT, + W5_ZERO_INIT, + W5_CREATED_INIT, + (5_000_000_000, 100_006_637_868, 95_006_181_727), + ), + ]; + for (account, mode, shape, operation, companion, direct, (paid, before, after)) in rows { + // Both values are above the balance and have the captured length. + let value = if account.balance == W4.balance { + 1_000_000_000 + } else { + 500_000_000_000 + }; + let label = format!("{mode:?} {shape:?}"); + let fee = operation.composite(companion); + assert_eq!(fee, direct.total_fees, "{label}"); + let spend = debit_spend(paid, before, after); + let request = single(value, mode, shape, true); + let (result, scripted) = run(account, request.clone(), |address| { + vec![answer(address, operation), answer(address, companion)] + }); + assert_eq!( + result, + Err(short(account, value, Some(fee), Some(spend))), + "{label}" + ); + assert_eq!( + scripted.http.calls(), + with_companion(operation.block), + "{label}" + ); + let emulations = scripted.http.emulations(); + assert_operation_and_companion(&request, account, &emulations[0], &emulations[1]); + } + } + + /// The value's encoded length changes the operation's own import fee and + /// nothing in the companion: on both sides of a byte boundary the + /// companion is byte-identical and the composite follows the operation. + #[test] + fn the_encoded_value_length_changes_only_the_operations_own_fee() { + // (wallet, largest value of n bytes, its operation, the operation of + // n + 1 bytes, companion); the answers of each length were captured + // at another value of that length. + let boundaries = [ + ( + W4, + u64::from(u32::MAX), + W4_SKIPPED_EMPTY, + W4_SKIPPED_EMPTY_5B, + W4_ZERO_EMPTY, + ), + ( + W5, + (1_u64 << 40) - 1, + W5_SKIPPED_EMPTY_5B, + W5_SKIPPED_EMPTY_6B, + W5_ZERO_EMPTY, + ), + ]; + for (account, below, shorter, longer, companion) in boundaries { + let mut companions = Vec::new(); + for (value, operation) in [(below, shorter), (below + 1, longer)] { + let request = single(value, None, Shape::Empty, true); + let (result, scripted) = run(account, request.clone(), |address| { + vec![answer(address, operation), answer(address, companion)] + }); + // Mode 3 adds the companion's forwarding remainder, which + // the value's length does not change. + let fee = operation.composite(companion); + let spend = fee - companion.action_fees + companion.forwarding; + assert_eq!(result, Err(short(account, value, Some(fee), Some(spend)))); + let emulations = scripted.http.emulations(); + assert_operation_and_companion(&request, account, &emulations[0], &emulations[1]); + companions.push(emulations[1]["boc"].clone()); + } + assert_eq!(companions[0], companions[1]); + // One more value byte costs only its import: 8 bits at 66.67. + let delta = longer.composite(companion) - shorter.composite(companion); + assert!((533..=534).contains(&delta), "{delta}"); + } + // The direct quote at 5 bytes on W5 matches its composite exactly, + // and so does the spend that it debited (5e9, captured balances). + assert_eq!( + W5_SKIPPED_EMPTY_5B.composite(W5_ZERO_EMPTY), + W5_CREATED_EMPTY_5B.total_fees + ); + let request = single(500_000_000_000, None, Shape::Empty, true); + let (result, _) = run(W5, request, |address| { + vec![ + answer(address, W5_SKIPPED_EMPTY_5B), + answer(address, W5_ZERO_EMPTY), + ] + }); + let spend = debit_spend(5_000_000_000, 100_006_637_868, 95_006_169_060); + assert_eq!(spend, 468_808); + assert_eq!( + result, + Err(short( + W5, + 500_000_000_000, + Some(W5_CREATED_EMPTY_5B.total_fees), + Some(spend) + )) + ); + // A created 3-byte and 4-byte value differ only by their import fee. + assert_eq!( + W4_CREATED_EMPTY.total_fees - W4_CREATED_EMPTY_3B.total_fees, + 533 + ); + assert_eq!( + W4_CREATED_EMPTY.action_fees, + W4_CREATED_EMPTY_3B.action_fees + ); + } + + /// The captured mode-3 delivery boundary at `W4`'s earlier block, both + /// sides captured at `B = 701082553`: 700614283 is the largest value whose + /// message the wallet created, with the wallet ending at 0, and it is the + /// opt-in success whose spend `S = 468270` meets the balance exactly + /// (`B = V + S`). From 700614284 (`B = V + S - 1`) the wallet skipped the + /// message although `V + F < B`; there the opt-in preview is the funds + /// refusal with the composite fee and spend, no longer a fee-less + /// emulation refusal. The default preview, which used to succeed there + /// with the raw skipped fee, gives the emulation refusal without asking + /// for a companion. + #[test] + fn the_captured_skip_window_is_refused_by_the_spend() { + let fee = W4_EARLIER_SKIPPED.composite(W4_EARLIER_ZERO); + assert_eq!(fee, W4_EARLIER_CREATED.total_fees); + let created = 700_614_283; + // The created answer's balances: 701082553 before, 0 after. + let spend = debit_spend(created, 701_082_553, 0); + assert_eq!(spend, 468_270); + assert_eq!(created + spend, W4.balance); + + let opted = single(created, None, Shape::Empty, true); + let (result, scripted) = run(W4, opted.clone(), |address| { + vec![answer(address, W4_EARLIER_CREATED)] + }); + assert_eq!( + result, + Ok(expected_quote(&opted, W4, W4_EARLIER_CREATED, spend)) + ); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + let default = single(created, None, Shape::Empty, false); + let (result, scripted) = run(W4, default.clone(), |address| { + vec![answer(address, W4_EARLIER_CREATED)] + }); + assert_eq!( + result, + Ok(expected_preview(&default, W4, W4_EARLIER_CREATED)) + ); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + + // The first skipped value and the old `B - F - 1`, where even the + // composite fee fits, and the last value below the raw-fee refusal, + // all captured skipped. + let raw = W4_EARLIER_SKIPPED.total_fees; + for value in [created + 1, W4.balance - fee - 1, W4.balance - raw - 1] { + assert!(value + raw < W4.balance); + let (result, scripted) = run(W4, single(value, None, Shape::Empty, true), |address| { + vec![ + answer(address, W4_EARLIER_SKIPPED), + answer(address, W4_EARLIER_ZERO), + ] + }); + assert_eq!( + result, + Err(short_for_fees(W4, value, fee, Some(fee), Some(spend))), + "{value}" + ); + assert_eq!( + scripted.http.calls(), + with_companion(W4_EARLIER_SKIPPED.block) + ); + + let (default, scripted) = + run(W4, single(value, None, Shape::Empty, false), |address| { + vec![answer(address, W4_EARLIER_SKIPPED)] + }); + assert_eq!(default, Err(rejected(NONE_CREATED)), "{value}"); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + } + } + + /// On the captured skipped rows the composite spend meets the engine's + /// `V + S > B` check exactly: from `B = V + S - 1` down the opt-in preview + /// refuses with the fee and the spend. At `B = V + S` and above the spend + /// fits, and the skipped answer, reused there although the chain created + /// those values (synthetic), stays the fee-less emulation refusal: a skip + /// is never a success. The default preview keeps its funds refusal at its + /// raw skipped fee and above; below it, where it used to succeed, it is + /// the emulation refusal. + #[test] + fn the_engine_equality_holds_on_the_captured_composite_spend() { + let raw = W4_EARLIER_SKIPPED.total_fees; + let fee = W4_EARLIER_SKIPPED.composite(W4_EARLIER_ZERO); + let spend = 468_270; + let funds = |value| spend_refusal(W4, value, fee, spend); + // Value, opt-in result, default result. + let rows = [ + ( + W4.balance - spend - 1, + rejected(NONE_CREATED), + rejected(NONE_CREATED), + ), + ( + W4.balance - spend, + rejected(NONE_CREATED), + rejected(NONE_CREATED), + ), + ( + W4.balance - spend + 1, + funds(W4.balance - spend + 1), + rejected(NONE_CREATED), + ), + ( + W4.balance - fee - 1, + funds(W4.balance - fee - 1), + rejected(NONE_CREATED), + ), + ( + W4.balance - fee, + funds(W4.balance - fee), + rejected(NONE_CREATED), + ), + ( + W4.balance - raw - 1, + funds(W4.balance - raw - 1), + rejected(NONE_CREATED), + ), + ( + W4.balance - raw, + funds(W4.balance - raw), + short_for_fees(W4, W4.balance - raw, raw, None, None), + ), + ( + W4.balance, + funds(W4.balance), + short_for_fees(W4, W4.balance, raw, None, None), + ), + ( + 1_000_000_000, + funds(1_000_000_000), + short(W4, 1_000_000_000, None, None), + ), + ]; + assert_eq!(W4.balance - spend + 1, 700_614_284); + assert_eq!(W4.balance - fee, 700_663_173); + assert_eq!(W4.balance - raw - 1, 700_685_950); + for (value, opted, default) in rows { + let (result, scripted) = run(W4, single(value, None, Shape::Empty, true), |address| { + vec![ + answer(address, W4_EARLIER_SKIPPED), + answer(address, W4_EARLIER_ZERO), + ] + }); + assert_eq!(result, Err(opted), "{value}"); + assert_eq!( + scripted.http.calls(), + with_companion(W4_EARLIER_SKIPPED.block), + "{value}" + ); + + let above = value > W4.balance; + let (result, scripted) = run(W4, single(value, None, Shape::Empty, false), |address| { + if above { + Vec::new() + } else { + vec![answer(address, W4_EARLIER_SKIPPED)] + } + }); + assert_eq!(result, Err(default), "{value}"); + let expected: &[Call] = if above { + &[Call::Account] + } else { + &UNTIL_OPERATION + }; + assert_eq!(scripted.http.calls(), expected, "{value}"); + } + } + + /// Synthetic provider balances around captured answers: a created + /// operation refuses exactly when its value plus its spend exceeds the + /// balance, for each fee kind, with the fee and the spend, and succeeds + /// with the spend at equality and above. A mode-2 or mode-18 message + /// whose balance lies between `V + S` and `V + F` succeeds, which the fee + /// comparison would refuse. A value above the balance carries both + /// amounts. The default preview at the same balances keeps its fee + /// comparison and reports no spend. A skipped operation's composite + /// spend draws the same line: one nanogram short refuses, and where the + /// spend fits the skip stays the emulation refusal. The chain cannot + /// produce these answers at these balances, so the rows check the + /// classifier against the protocol's boundary, not chain behaviour. + #[test] + fn the_engine_equality_boundary_is_the_spend() { + let value = 100_000_000; + let fee = W4_CREATED_EMPTY.total_fees; + // The spends that the captured 1e8 answers debited: 600614258 after + // for modes 3 and 19, 600687592 for modes 2 and 18. + let pays = debit_spend(value, 701_082_553, 600_614_258); + let kept = debit_spend(value, 701_082_553, 600_687_592); + assert_eq!((pays, kept), (468_295, 394_961)); + assert!(kept < fee && fee < pays); + // Balance, whether the opt-in and the default previews succeed. + let paying = [ + (value - 1, false, false), + (value + fee - 1, false, false), + (value + fee, false, false), + (value + fee + 1, false, true), + (value + pays - 1, false, true), + (value + pays, true, true), + (value + pays + 1, true, true), + ]; + let keeping = [ + (value - 1, false, false), + (value + kept - 1, false, false), + (value + kept, true, false), + (value + kept + 1, true, false), + (value + fee - 1, true, false), + (value + fee, true, false), + (value + fee + 1, true, true), + ]; + let modes = [ + (None, pays, &paying), + (Some(3), pays, &paying), + (Some(19), pays, &paying), + (Some(2), kept, &keeping), + (Some(18), kept, &keeping), + ]; + for (mode, spend, rows) in modes { + for &(balance, opted_succeeds, default_succeeds) in rows { + let label = format!("{mode:?} {balance}"); + let account = Account { balance, ..W4 }; + let request = single(value, mode, Shape::Empty, true); + let (opted, scripted) = run(account, request.clone(), |address| { + vec![answer(address, W4_CREATED_EMPTY)] + }); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION, "{label}"); + if opted_succeeds { + assert_eq!( + opted, + Ok(expected_quote(&request, account, W4_CREATED_EMPTY, spend)), + "{label}" + ); + } else { + assert_eq!( + opted, + Err(spend_refusal(account, value, fee, spend)), + "{label}" + ); + } + + let default = single(value, mode, Shape::Empty, false); + let above = balance < value; + let (result, _) = run(account, default.clone(), |address| { + if above { + Vec::new() + } else { + vec![answer(address, W4_CREATED_EMPTY)] + } + }); + let expected = if default_succeeds { + Ok(expected_preview(&default, account, W4_CREATED_EMPTY)) + } else if above { + Err(short(account, value, None, None)) + } else { + Err(short_for_fees(account, value, fee, None, None)) + }; + assert_eq!(result, expected, "{label}"); + } + } + + // Skipped operations priced by their composite, with the spend of + // the same block's created answer: (wallet, mode, shape, value, + // operation, companion, spend). + let composites = [ + ( + W4, + Some(19), + Shape::Empty, + 1_000_000_000, + W4_SKIPPED_EMPTY, + W4_ZERO_EMPTY, + pays, + ), + ( + W4, + Some(2), + Shape::StateInit, + 1_000_000_000, + W4_SKIPPED_INIT, + W4_ZERO_INIT, + debit_spend(value, 701_082_553, 600_626_925), + ), + ( + W5, + Some(18), + Shape::Comment, + 500_000_000_000, + W5_SKIPPED_COMMENT, + W5_ZERO_COMMENT, + debit_spend(5_000_000_000, 100_006_637_868, 95_006_230_127), + ), + ]; + for (wallet, mode, shape, value, operation, companion, spend) in composites { + let fee = operation.composite(companion); + let mut balances = vec![ + (value + spend - 1, false), + (value + spend, true), + (value + spend + 1, true), + ]; + if spend < fee { + // Between `V + S` and `V + F`, where the fee would refuse. + balances.extend([(value + fee - 1, true), (value + fee, true)]); + } + for (balance, fits) in balances { + let label = format!("{mode:?} {shape:?} {balance}"); + let account = Account { balance, ..wallet }; + let (result, scripted) = + run(account, single(value, mode, shape, true), |address| { + vec![answer(address, operation), answer(address, companion)] + }); + let expected = if fits { + rejected(NONE_CREATED) + } else { + spend_refusal(account, value, fee, spend) + }; + assert_eq!(result, Err(expected), "{label}"); + assert_eq!( + scripted.http.calls(), + with_companion(operation.block), + "{label}" + ); + } + } + } + + /// A created affordable operation is the default preview with its spend: + /// the same emulation, fee and requests, with no companion, and the + /// spend that the captured answer debited from the wallet beyond the + /// value, for every fee kind, message shape, wallet and value length. + #[test] + fn a_created_affordable_operation_is_the_default_preview() { + // Wallet, mode, shape, value, answer, and the answer's captured + // balances before and after. + let rows = [ + ( + W4, + None, + Shape::Empty, + 100_000_000, + W4_CREATED_EMPTY, + (701_082_553, 600_614_258), + ), + ( + W4, + Some(3), + Shape::Empty, + 100_000_000, + W4_CREATED_EMPTY, + (701_082_553, 600_614_258), + ), + ( + W4, + Some(2), + Shape::Empty, + 100_000_000, + W4_CREATED_EMPTY, + (701_082_553, 600_687_592), + ), + ( + W4, + Some(18), + Shape::Empty, + 100_000_000, + W4_CREATED_EMPTY, + (701_082_553, 600_687_592), + ), + ( + W4, + Some(19), + Shape::Empty, + 100_000_000, + W4_CREATED_EMPTY, + (701_082_553, 600_614_258), + ), + ( + W4, + None, + Shape::Empty, + 10_000_000, + W4_CREATED_EMPTY_3B, + (701_082_553, 690_614_791), + ), + ( + W4, + None, + Shape::Comment, + 100_000_000, + W4_CREATED_COMMENT, + (701_082_553, 600_589_724), + ), + ( + W4, + None, + Shape::Payload, + 100_000_000, + W4_CREATED_PAYLOAD, + (701_082_553, 600_567_858), + ), + ( + W4, + None, + Shape::StateInit, + 100_000_000, + W4_CREATED_INIT, + (701_082_553, 600_493_324), + ), + ( + W4, + Some(2), + Shape::StateInit, + 100_000_000, + W4_CREATED_INIT, + (701_082_553, 600_626_925), + ), + ( + W4, + None, + Shape::Empty, + 100_000_000, + W4_EARLIER_CREATED, + (701_082_553, 600_614_283), + ), + ( + W5, + None, + Shape::Empty, + 5_000_000_000, + W5_CREATED_EMPTY_5B, + (100_006_637_868, 95_006_169_060), + ), + ( + W5, + Some(18), + Shape::Comment, + 5_000_000_000, + W5_CREATED_COMMENT, + (100_006_637_868, 95_006_230_127), + ), + ( + W5, + Some(2), + Shape::StateInit, + 5_000_000_000, + W5_CREATED_INIT, + (100_006_637_868, 95_006_181_727), + ), + ]; + for (account, mode, shape, value, root, (before, after)) in rows { + let label = format!("{mode:?} {shape:?} {value}"); + let spend = debit_spend(value, before, after); + let opted_request = single(value, mode, shape, true); + let (opted, opted_run) = run(account, opted_request.clone(), |address| { + vec![answer(address, root)] + }); + let default_request = single(value, mode, shape, false); + let (default, default_run) = run(account, default_request.clone(), |address| { + vec![answer(address, root)] + }); + assert_eq!( + opted, + Ok(expected_quote(&opted_request, account, root, spend)), + "{label}" + ); + assert_eq!( + default, + Ok(expected_preview(&default_request, account, root)), + "{label}" + ); + let opted = opted.expect("affordable preview succeeds"); + assert_eq!( + Ok(SendPreview { + operation_spend_nanograms: None, + ..opted + }), + default, + "{label}" + ); + let requests = |scripted: &Scripted| { + scripted + .http + .requests() + .into_iter() + .map(|request| (request.id.value, request.url, request.body)) + .collect::>() + }; + assert_eq!(requests(&opted_run), requests(&default_run), "{label}"); + assert_eq!(opted_run.http.calls(), UNTIL_OPERATION, "{label}"); + } + } + + /// A TON Connect preview never asks for the operation's fee: above the + /// balance it still ends after the account read. + #[test] + fn ton_connect_previews_keep_the_default_route() { + let scripted = Scripted::new(W4, |_| Vec::new()); + let request = SendRequest { + operation_id: NonEmptyString::try_from("ton-connect").expect("operation ID"), + force: false, + intent: single(1_000_000_000, Some(2), Shape::Empty, true).intent, + }; + let result = block_on(scripted.client.preview_ton_connect(request)); + assert_eq!(result, Err(short(W4, 1_000_000_000, None, None))); + assert_eq!(scripted.http.calls(), [Call::Account]); + } + + /// An intent that sends the whole balance ignores the flag and takes the + /// default route in mode 130 with its delivery check: a created answer + /// succeeds with its fee and no spend, and a skipped one, which used to + /// succeed too, is the emulation refusal, with the same requests and no + /// companion either way. The captured mode-3 answers stand in for the + /// whole-balance message (synthetic reuse). + #[test] + fn a_whole_balance_intent_ignores_the_flag() { + let whole = |estimate_shortfall| { + let mut message = message(1, None, Shape::Empty); + message.amount = SendAmount::All; + request(vec![message], estimate_shortfall) + }; + let rows = [ + (W4_EARLIER_CREATED, None), + (W4_EARLIER_SKIPPED, Some(rejected(NONE_CREATED))), + ]; + for (root, refusal) in rows { + let (opted, opted_run) = run(W4, whole(true), |address| vec![answer(address, root)]); + let (default, default_run) = + run(W4, whole(false), |address| vec![answer(address, root)]); + assert_eq!(opted, default); + match refusal { + None => { + let preview = opted.expect("a created whole-balance preview succeeds"); + assert_eq!( + preview.emulation.wallet_fees_nanograms, + decimal(root.total_fees) + ); + assert_eq!(preview.operation_spend_nanograms, None); + } + Some(error) => assert_eq!(opted, Err(error)), + } + assert_eq!( + opted_run.http.requests(), + default_run.http.requests(), + "same requests" + ); + assert_eq!(opted_run.http.calls(), UNTIL_OPERATION); + assert_eq!( + decode(&opted_run.http.emulations()[0]).wallet.msgs_modes, + [130] + ); + } + } + + /// Every value of the measured skip window, from the first skipped value + /// to the last one below the raw-fee refusal, sampled at a fixed stride + /// together with the captured interior values, passes the unchanged funds + /// check and is now the emulation refusal without a fee, after the same + /// three requests and identifiers. The neighbours keep their outcomes: + /// the largest created value previews exactly as before, and `B - raw` + /// keeps the raw-fee funds refusal. + #[test] + fn default_previews_refuse_the_captured_skip_window() { + let raw = W4_EARLIER_SKIPPED.total_fees; + let first = 700_614_284; + let last = W4.balance - raw - 1; + assert_eq!(last, 700_685_950); + let values = (first..=last) + .step_by(7_166) + .chain([700_663_172, 700_663_173, 700_663_174, last]) + .collect::>(); + assert_eq!(values.len(), 15); + for value in values { + // The funds check that runs first lets the value pass. + assert_eq!( + funds_refusal( + &decimal(W4.balance), + &decimal(value), + &decimal(raw), + None, + None + ), + None, + "{value}" + ); + let request = single(value, None, Shape::Empty, false); + let (result, scripted) = run(W4, request.clone(), |address| { + vec![answer(address, W4_EARLIER_SKIPPED)] + }); + assert_eq!(result, Err(rejected(NONE_CREATED)), "{value}"); + assert_eq!( + scripted.http.requests(), + expected_requests(&request, W4), + "{value}" + ); + } + + let created = single(first - 1, None, Shape::Empty, false); + let (result, scripted) = run(W4, created.clone(), |address| { + vec![answer(address, W4_EARLIER_CREATED)] + }); + assert_eq!( + result, + Ok(expected_preview(&created, W4, W4_EARLIER_CREATED)) + ); + assert_eq!(scripted.http.requests(), expected_requests(&created, W4)); + + let value = last + 1; + let request = single(value, None, Shape::Empty, false); + let (result, scripted) = run(W4, request.clone(), |address| { + vec![answer(address, W4_EARLIER_SKIPPED)] + }); + assert_eq!(result, Err(short_for_fees(W4, value, raw, None, None))); + assert_eq!(scripted.http.requests(), expected_requests(&request, W4)); + } + + /// A default preview needs every message created: a partial delivery of + /// one or two messages is refused with the opt-in route's diagnostic, a + /// batch with none created like a single skipped message, and a created + /// batch succeeds. The two-message answers are synthetic. + #[test] + fn default_previews_refuse_a_partial_delivery() { + let one = Root { + delivery: (1, 1, 1), + ..W4_CREATED_EMPTY + }; + for estimate_shortfall in [false, true] { + let (result, scripted) = run( + W4, + single(100_000_000, None, Shape::Empty, estimate_shortfall), + |address| vec![answer(address, one)], + ); + assert_eq!(result, Err(rejected(ONLY_SOME)), "{estimate_shortfall}"); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + } + + let two = batch(); + let rows = [ + ((2, 1, 1), Err(rejected(ONLY_SOME))), + ((2, 0, 1), Err(rejected(ONLY_SOME))), + ((2, 2, 0), Err(rejected(NONE_CREATED))), + ((2, 0, 2), Ok(expected_preview(&two, W4, W4_CREATED_TWO))), + ]; + for (delivery, expected) in rows { + let root = Root { + delivery, + ..W4_CREATED_TWO + }; + let (result, scripted) = run(W4, two.clone(), |address| vec![answer(address, root)]); + assert_eq!(result, expected, "{delivery:?}"); + assert_eq!( + scripted.http.requests(), + expected_requests(&two, W4), + "{delivery:?}" + ); + } + } + + /// A TON Connect batch takes the default route: it succeeds only when the + /// wallet created every message, and the same client previews again + /// after each refusal. The two-message answers are synthetic. + #[test] + fn ton_connect_batches_need_every_message_created() { + let rows = [ + ((2, 0, 2), None), + ((2, 1, 1), Some(rejected(ONLY_SOME))), + ((2, 0, 2), None), + ((2, 2, 0), Some(rejected(NONE_CREATED))), + ((2, 0, 2), None), + ]; + let scripted = Scripted::new(W4, |address| { + rows.iter() + .map(|(delivery, _)| { + answer( + address, + Root { + delivery: *delivery, + ..W4_CREATED_TWO + }, + ) + }) + .collect() + }); + let intent = request( + vec![ + message(100_000_000, None, Shape::Empty), + message(200_000_000, Some(3), Shape::Payload), + ], + false, + ); + for (index, (delivery, refusal)) in rows.into_iter().enumerate() { + let result = block_on(scripted.client.preview_ton_connect(SendRequest { + operation_id: NonEmptyString::try_from("ton-connect").expect("operation ID"), + force: false, + intent: intent.intent.clone(), + })); + assert!( + scripted + .client + .lock() + .expect("state") + .active_preview + .is_none(), + "the preview slot is finished" + ); + match refusal { + None => assert_eq!( + result, + Ok(expected_preview(&intent, W4, W4_CREATED_TWO)), + "{index}" + ), + Some(error) => assert_eq!(result, Err(error), "{index} {delivery:?}"), + } + let calls = scripted.http.calls(); + assert_eq!(calls.len(), (index + 1) * 3); + assert_eq!(calls[index * 3..], UNTIL_OPERATION); + } + assert_eq!(scripted.unused_answers(), 0); + } + + /// Without usable counters the root's `out_msgs` list decides: a list + /// with the request's length is the unchanged preview, an empty or short + /// one is refused, and neither record usable fails. Usable counters + /// decide alone, whatever the list holds. The edited rows are synthetic. + #[test] + fn default_previews_read_the_output_list_only_without_usable_counters() { + type Edit = fn(&mut serde_json::Value); + let request = || single(100_000_000, None, Shape::Empty, false); + let base = Ok(expected_preview(&request(), W4, W4_CREATED_EMPTY)); + let keep: Edit = |_| {}; + let counters: [Edit; 7] = [ + |root| { + let action = root["description"]["action"] + .as_object_mut() + .expect("action"); + for field in ["tot_actions", "skipped_actions", "msgs_created"] { + let _ = action.remove(field); + } + }, + |root| root["description"]["action"]["msgs_created"] = (-1).into(), + |root| root["description"]["action"]["tot_actions"] = "one".into(), + |root| root["description"]["action"]["msgs_created"] = 1.5.into(), + |root| root["description"]["action"]["skipped_actions"] = 65_536.into(), + |root| { + root["description"]["action"]["skipped_actions"] = "18446744073709551616".into(); + }, + |root| root["description"]["action"]["msgs_created"] = serde_json::Value::Null, + ]; + let empty: Edit = |root| root["out_msgs"] = serde_json::json!([]); + let unusable: [Edit; 5] = [ + |root| { + let _ = root.as_object_mut().expect("root").remove("out_msgs"); + }, + |root| root["out_msgs"] = serde_json::Value::Null, + |root| root["out_msgs"] = serde_json::json!({ "0": {} }), + |root| root["out_msgs"] = "[{}]".into(), + |root| root["out_msgs"] = 1.into(), + ]; + let reply = |root: Root, counters: Edit, list: Edit| { + move |address: &str| { + let mut body = answer_json(address, root); + counters(&mut body["transactions"]["root"]); + list(&mut body["transactions"]["root"]); + vec![Reply::Json(200, body)] + } + }; + + for (index, counters) in counters.into_iter().enumerate() { + let (result, _) = run(W4, request(), reply(W4_CREATED_EMPTY, counters, keep)); + assert_eq!(result, base, "counters {index}, created list"); + let (result, _) = run(W4, request(), reply(W4_CREATED_EMPTY, counters, empty)); + assert_eq!( + result, + Err(rejected(NONE_CREATED)), + "counters {index}, empty list" + ); + for (list_index, list) in unusable.into_iter().enumerate() { + let (result, scripted) = + run(W4, request(), reply(W4_CREATED_EMPTY, counters, list)); + assert_eq!( + result, + Err(unreported()), + "counters {index}, list {list_index}" + ); + assert_eq!(scripted.http.requests(), expected_requests(&request(), W4)); + } + } + + // A two-message list one entry short is partial; the full one is + // the created batch. + let short_list: Edit = |root| { + let _ = root["out_msgs"].as_array_mut().expect("list").pop(); + }; + let (result, _) = run(W4, batch(), reply(W4_CREATED_TWO, counters[0], short_list)); + assert_eq!(result, Err(rejected(ONLY_SOME))); + let (result, _) = run(W4, batch(), reply(W4_CREATED_TWO, counters[0], keep)); + assert_eq!(result, Ok(expected_preview(&batch(), W4, W4_CREATED_TWO))); + + // Usable counters decide, with no new veto from an unusable or + // disagreeing list. + for list in unusable.into_iter().chain([empty]) { + let (result, _) = run(W4, request(), reply(W4_CREATED_EMPTY, keep, list)); + assert_eq!(result, base); + } + let skipped = Root { + delivery: SKIPPED, + ..W4_CREATED_EMPTY + }; + let one_entry: Edit = |root| { + root["out_msgs"] = serde_json::json!([{ "destination": DESTINATION }]); + }; + for list in unusable.into_iter().chain([keep, one_entry]) { + let (result, _) = run(W4, request(), reply(skipped, keep, list)); + assert_eq!(result, Err(rejected(NONE_CREATED))); + } + } + + /// Each new refusal finishes the preview: the same client previews a + /// created operation right after it. + #[test] + fn a_preview_after_each_new_refusal_succeeds() { + let missing: fn(&mut serde_json::Value) = |root| { + let action = root["description"]["action"] + .as_object_mut() + .expect("action"); + for field in ["tot_actions", "skipped_actions", "msgs_created"] { + let _ = action.remove(field); + } + let _ = root.as_object_mut().expect("root").remove("out_msgs"); + }; + let scripted = Scripted::new(W4, |address| { + vec![ + answer(address, W4_EARLIER_SKIPPED), + answer(address, W4_CREATED_EMPTY), + answer( + address, + Root { + delivery: (1, 1, 1), + ..W4_CREATED_EMPTY + }, + ), + answer(address, W4_CREATED_EMPTY), + edited(address, W4_CREATED_EMPTY, missing), + answer(address, W4_CREATED_EMPTY), + ] + }); + let created = single(100_000_000, None, Shape::Empty, false); + for refusal in [rejected(NONE_CREATED), rejected(ONLY_SOME), unreported()] { + assert_eq!(scripted.preview(created.clone()), Err(refusal.clone())); + let next = scripted + .preview(created.clone()) + .unwrap_or_else(|error| panic!("after {refusal:?}: {error:?}")); + assert_eq!( + next.emulation.wallet_fees_nanograms, + decimal(W4_CREATED_EMPTY.total_fees) + ); + } + assert_eq!(scripted.http.calls().len(), 18); + assert_eq!(scripted.unused_answers(), 0); + } + + /// A never-deployed zero wallet sends its own `StateInit` with seqno 0 + /// and reads no seqno; the network rejects it before execution, so the + /// refusal carries no fee, never a zero one. A zero value, which is not + /// above the balance, keeps the default preview's emulation error. + #[test] + fn a_never_deployed_zero_wallet_is_refused_without_a_fee() { + for status in [AccountStatus::Uninitialized, AccountStatus::Nonexistent] { + let account = Account { + status, + ..NEVER_DEPLOYED + }; + let request = single(1_000_000_000, None, Shape::Empty, true); + let (result, scripted) = + run(account, request.clone(), |address| vec![rejection(address)]); + assert_eq!( + result, + Err(short(account, 1_000_000_000, None, None)), + "{status:?}" + ); + assert_eq!( + scripted.http.calls(), + [Call::Account, Call::Emulate(None)], + "{status:?}" + ); + let operation = decode(&scripted.http.emulations()[0]); + let config = client_config(); + let (_, own) = derive_wallet_public_state(&config.public_key, config.network) + .expect("state init derives"); + assert_eq!( + operation.external.init.map(|init| init.value), + Some(own), + "{status:?}" + ); + assert_eq!(operation.wallet.msg_seqno, 0); + assert_eq!( + operation.boc, + expected_boc(&single(1_000_000_000, None, Shape::Empty, false), account) + ); + + let (opted, _) = run(account, single(0, None, Shape::Empty, true), |address| { + vec![rejection(address)] + }); + let (default, _) = run(account, single(0, None, Shape::Empty, false), |address| { + vec![rejection(address)] + }); + assert!( + matches!(opted, Err(WalletClientError::EmulationFailed { .. })), + "{opted:?}" + ); + assert_eq!(opted, default); + } + } + + /// A deployed zero wallet sends its actual seqno and no `StateInit`; its + /// rejection carries no fee. + #[test] + fn a_deployed_zero_wallet_is_refused_without_a_fee() { + let request = single(1_000_000_000, None, Shape::Empty, true); + let (result, scripted) = run(DEPLOYED_ZERO, request, |address| vec![rejection(address)]); + assert_eq!(result, Err(short(DEPLOYED_ZERO, 1_000_000_000, None, None))); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + let operation = decode(&scripted.http.emulations()[0]); + assert!(operation.external.init.is_none()); + assert_eq!(operation.wallet.msg_seqno, DEPLOYED_ZERO.seqno); + assert_eq!( + operation.boc, + expected_boc( + &single(1_000_000_000, None, Shape::Empty, false), + DEPLOYED_ZERO + ) + ); + } + + /// No dust band yields a fee: a balance below the flat gas price is + /// rejected before execution (captured text); out of gas fails the + /// compute phase; and a balance that pays for compute but not for the + /// message skips the companion too. The last two are protocol readings, + /// scripted with synthetic answers. + #[test] + fn dust_wallets_are_refused_without_a_fee() { + // Above the balance: the funds refusal without a fee. + let out_of_gas: fn(&mut serde_json::Value) = |root| { + root["total_fees"] = "200000".into(); + root["description"]["compute_ph"]["success"] = false.into(); + root["description"]["compute_ph"]["exit_code"] = (-14).into(); + root["description"]["action"] = serde_json::Value::Null; + }; + let accepted = Account { + balance: 400_000, + ..DUST + }; + let starved = Account { + balance: 200_000, + ..DUST + }; + // Synthetic: the captured skipped answer at a dust balance, and its + // zero-value companion skipped as well. + let skipped_companion = Root { + total_fees: 394_469, + ..W4_EARLIER_SKIPPED + }; + let (result, scripted) = run( + DUST, + single(1_000_000_000, None, Shape::Empty, true), + |address| vec![rejection(address)], + ); + assert_eq!(result, Err(short(DUST, 1_000_000_000, None, None))); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + let (result, scripted) = run( + starved, + single(1_000_000_000, None, Shape::Empty, true), + |address| vec![edited(address, W4_EARLIER_SKIPPED, out_of_gas)], + ); + assert_eq!(result, Err(short(starved, 1_000_000_000, None, None))); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + let (result, scripted) = run( + accepted, + single(1_000_000_000, None, Shape::Empty, true), + |address| { + vec![ + answer(address, W4_EARLIER_SKIPPED), + answer(address, skipped_companion), + ] + }, + ); + assert_eq!(result, Err(short(accepted, 1_000_000_000, None, None))); + assert_eq!( + scripted.http.calls(), + with_companion(W4_EARLIER_SKIPPED.block) + ); + + // Not above the balance: the default preview's error where it fails, + // and the fee-less emulation refusal where it would succeed on a + // skipped message. + let (opted, _) = run(DUST, single(1_000, None, Shape::Empty, true), |address| { + vec![rejection(address)] + }); + let (default, _) = run(DUST, single(1_000, None, Shape::Empty, false), |address| { + vec![rejection(address)] + }); + assert!( + matches!(opted, Err(WalletClientError::EmulationFailed { .. })), + "{opted:?}" + ); + assert_eq!(opted, default); + let (opted, _) = run( + starved, + single(1_000, None, Shape::Empty, true), + |address| vec![edited(address, W4_EARLIER_SKIPPED, out_of_gas)], + ); + let (default, _) = run( + starved, + single(1_000, None, Shape::Empty, false), + |address| vec![edited(address, W4_EARLIER_SKIPPED, out_of_gas)], + ); + assert_eq!( + opted, + Err(WalletClientError::EmulationRejected { + diagnostic: "emulated transfer did not complete successfully".to_owned(), + compute_exit_code: Some(-14), + action_result_code: None, + }) + ); + assert_eq!(opted, default); + let (opted, scripted) = run(accepted, single(1, None, Shape::Empty, true), |address| { + vec![ + answer(address, W4_EARLIER_SKIPPED), + answer(address, skipped_companion), + ] + }); + assert_eq!(opted, Err(rejected(NONE_CREATED))); + assert_eq!( + scripted.http.calls(), + with_companion(W4_EARLIER_SKIPPED.block) + ); + } + + /// An operation emulation that fails, is malformed or cannot prove its + /// delivery never carries a fee or succeeds. Above the balance it is the + /// fee-less funds refusal; otherwise it is the default preview's own error + /// where that fails, and an emulation error where the default preview + /// accepts an answer whose counters do not prove delivery but whose + /// output list does. + #[test] + fn failed_or_malformed_operation_emulations_never_carry_a_fee() { + type Case = (&'static str, fn(&str) -> Reply, Option); + let missing = || WalletClientError::EmulationFailed { + diagnostic: "emulation did not report the wallet's message delivery".to_owned(), + }; + let cases: [Case; 18] = [ + ("rejected before execution", rejection, None), + ( + "not accepted (synthetic diagnostic)", + |_| { + Reply::Json( + 500, + serde_json::json!({ "error": "external message was not accepted" }), + ) + }, + None, + ), + ( + "compute failure", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["compute_ph"]["success"] = false.into(); + root["description"]["compute_ph"]["exit_code"] = 33.into(); + }) + }, + None, + ), + ( + "action failure", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["action"]["success"] = false.into(); + root["description"]["action"]["result_code"] = 37.into(); + }) + }, + None, + ), + ( + "aborted", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["aborted"] = true.into(); + }) + }, + None, + ), + ( + "wrong source", + |_| answer(DESTINATION_B, W4_CREATED_EMPTY), + None, + ), + ( + "missing root", + |address| { + let mut body = answer_json(address, W4_CREATED_EMPTY); + body["trace"]["tx_hash"] = "other".into(); + Reply::Json(200, body) + }, + None, + ), + ("malformed JSON", |_| Reply::Malformed, None), + ("offline", |_| Reply::Offline, None), + ( + "missing fee", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + let _ = root.as_object_mut().expect("root").remove("total_fees"); + }) + }, + None, + ), + ( + "missing counters", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + let action = root["description"]["action"] + .as_object_mut() + .expect("action"); + for field in ["tot_actions", "skipped_actions", "msgs_created"] { + let _ = action.remove(field); + } + }) + }, + Some(missing()), + ), + ( + "negative counter", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["action"]["msgs_created"] = (-1).into(); + }) + }, + Some(missing()), + ), + ( + "non-decimal counter", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["action"]["tot_actions"] = "one".into(); + }) + }, + Some(missing()), + ), + ( + "fractional counter", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["action"]["msgs_created"] = 1.5.into(); + }) + }, + Some(missing()), + ), + ( + "overflowing counter", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["action"]["skipped_actions"] = + "18446744073709551616".into(); + }) + }, + Some(missing()), + ), + ( + "missing action phase", + |address| { + edited(address, W4_CREATED_EMPTY, |root| { + root["description"]["action"] = serde_json::Value::Null; + }) + }, + None, + ), + ( + "zero fee", + |address| { + answer( + address, + Root { + total_fees: 0, + ..W4_CREATED_EMPTY + }, + ) + }, + Some(WalletClientError::EmulationFailed { + diagnostic: "emulated wallet fee is zero".to_owned(), + }), + ), + ( + "only some messages created", + |address| { + answer( + address, + Root { + delivery: (1, 1, 1), + ..W4_CREATED_EMPTY + }, + ) + }, + // The default preview used to accept this answer; both + // previews now give the emulation refusal. + None, + ), + ]; + for (label, reply, below) in cases { + let (result, scripted) = run( + W4, + single(1_000_000_000, None, Shape::Empty, true), + |address| vec![reply(address)], + ); + assert_eq!(result, Err(short(W4, 1_000_000_000, None, None)), "{label}"); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION, "{label}"); + + let (opted, scripted) = run( + W4, + single(100_000_000, None, Shape::Empty, true), + |address| vec![reply(address)], + ); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION, "{label}"); + let (default, _) = run( + W4, + single(100_000_000, None, Shape::Empty, false), + |address| vec![reply(address)], + ); + match below { + None => { + assert!(default.is_err(), "{label}: {default:?}"); + assert_eq!(opted, default, "{label}"); + } + Some(error) => { + assert!(default.is_ok(), "{label}: {default:?}"); + assert_eq!(opted, Err(error), "{label}"); + } + } + } + } + + /// A companion that fails, skips, is malformed or does not match the + /// operation leaves the refusal without a fee, and so does an operation + /// whose own fee components cannot be composed. Below the balance the raw + /// skipped fee keeps only the default refusal at and above it. + #[test] + fn an_unproved_companion_leaves_the_refusal_without_a_fee() { + type Case = (&'static str, fn(&str) -> Reply, Option Reply>); + let cases: [Case; 18] = [ + ( + "companion offline", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|_| Reply::Offline), + ), + ( + "companion rejected before execution", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(rejection), + ), + ( + "companion malformed", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|_| Reply::Malformed), + ), + ( + "companion fee missing", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + edited(a, W4_ZERO_EMPTY, |root| { + let _ = root.as_object_mut().expect("root").remove("total_fees"); + }) + }), + ), + ( + "companion action fee malformed", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + edited(a, W4_ZERO_EMPTY, |root| { + root["description"]["action"]["total_action_fees"] = "-1".into(); + }) + }), + ), + ( + "companion counters missing", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + edited(a, W4_ZERO_EMPTY, |root| { + let _ = root["description"]["action"] + .as_object_mut() + .expect("action") + .remove("msgs_created"); + }) + }), + ), + ( + "companion skipped", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| answer(a, W4_SKIPPED_EMPTY)), + ), + ( + "companion keeping mode 2 skips", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| answer(a, W4_ZERO_EMPTY_KEPT_MODE)), + ), + ( + "companion rejected", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + edited(a, W4_ZERO_EMPTY, |root| { + root["description"]["compute_ph"]["success"] = false.into(); + root["description"]["compute_ph"]["exit_code"] = 33.into(); + }) + }), + ), + ( + "companion of another wallet", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|_| answer(DESTINATION_B, W4_ZERO_EMPTY)), + ), + ( + "gas mismatch", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + answer( + a, + Root { + gas_used: W4_ZERO_EMPTY.gas_used + 1, + ..W4_ZERO_EMPTY + }, + ) + }), + ), + ( + "storage mismatch", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + answer( + a, + Root { + storage_fees: W4_ZERO_EMPTY.storage_fees + 1, + ..W4_ZERO_EMPTY + }, + ) + }), + ), + ( + "block mismatch", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + answer( + a, + Root { + block: W4_ZERO_EMPTY.block + 1, + ..W4_ZERO_EMPTY + }, + ) + }), + ), + ( + "companion storage phase without its fee", + |a| answer(a, W4_SKIPPED_EMPTY), + Some(|a| { + edited(a, W4_ZERO_EMPTY, |root| { + root["description"]["storage_ph"] = + serde_json::json!({ "status_change": "unchanged" }); + }) + }), + ), + ( + "action fee above the operation's total", + |a| { + answer( + a, + Root { + total_fees: 1_000, + ..W4_SKIPPED_EMPTY + }, + ) + }, + Some(|a| answer(a, W4_ZERO_EMPTY)), + ), + ( + "operation gas malformed", + |a| { + edited(a, W4_SKIPPED_EMPTY, |root| { + root["description"]["compute_ph"]["gas_used"] = "3.5e3".into(); + }) + }, + None, + ), + ( + "operation storage phase without its fee", + |a| { + edited(a, W4_SKIPPED_EMPTY, |root| { + root["description"]["storage_ph"] = + serde_json::json!({ "status_change": "unchanged" }); + }) + }, + None, + ), + ( + "operation storage phase malformed", + |a| { + edited(a, W4_SKIPPED_EMPTY, |root| { + root["description"]["storage_ph"] = "26".into(); + }) + }, + None, + ), + ]; + for (label, operation, companion) in cases { + let (result, scripted) = run( + W4, + single(1_000_000_000, None, Shape::Empty, true), + |address| { + let mut replies = vec![operation(address)]; + replies.extend(companion.map(|companion| companion(address))); + replies + }, + ); + assert_eq!(result, Err(short(W4, 1_000_000_000, None, None)), "{label}"); + let expected = if companion.is_some() { + with_companion(W4_SKIPPED_EMPTY.block) + } else { + UNTIL_OPERATION.to_vec() + }; + assert_eq!(scripted.http.calls(), expected, "{label}"); + } + + // Not above the balance, with the captured skipped rows: no fee is + // ever attached; the raw skipped fee keeps the default refusal only. + let raw = W4_EARLIER_SKIPPED.total_fees; + let rows = [ + (700_663_173, rejected(NONE_CREATED)), + ( + W4.balance - raw, + short_for_fees(W4, W4.balance - raw, raw, None, None), + ), + ]; + for (value, expected) in rows { + let (result, scripted) = run(W4, single(value, None, Shape::Empty, true), |address| { + vec![answer(address, W4_EARLIER_SKIPPED), Reply::Offline] + }); + assert_eq!(result, Err(expected), "{value}"); + assert_eq!( + scripted.http.calls(), + with_companion(W4_EARLIER_SKIPPED.block) + ); + } + } + + /// A root fee that is zero or below its own action fee never composes a + /// fee or a spend, while the valid answers of the same operation do: a + /// zero companion total, a companion action fee above its total, and a + /// zero operation total and action fee. Each refusal keeps its existing + /// classification, comparing the raw skipped fee like any unproved + /// companion. The edited rows are synthetic; the captured 1e9 answers + /// are reused at the other values, which have the same value length. + #[test] + fn inconsistent_root_fees_never_compose_a_fee() { + let fee = W4_SKIPPED_EMPTY.composite(W4_ZERO_EMPTY); + assert_eq!(fee, W4_CREATED_EMPTY.total_fees, "the valid control"); + // The mode-3 spend of the same block's created 1e8 answer. + let spend = debit_spend(100_000_000, 701_082_553, 600_614_258); + let raw = W4_SKIPPED_EMPTY.total_fees; + let above = 1_000_000_000; + // Above the balance, the balance itself and the valid fee's boundary. + let values = [above, W4.balance, W4.balance - fee]; + let unproved = |raw: u64| { + [ + short(W4, above, None, None), + short_for_fees(W4, W4.balance, raw, None, None), + rejected(NONE_CREATED), + ] + }; + let rows = [ + ( + "valid control", + W4_SKIPPED_EMPTY, + W4_ZERO_EMPTY, + [ + short(W4, above, Some(fee), Some(spend)), + short_for_fees(W4, W4.balance, fee, Some(fee), Some(spend)), + short_for_fees(W4, W4.balance - fee, fee, Some(fee), Some(spend)), + ], + ), + ( + "zero companion total", + W4_SKIPPED_EMPTY, + Root { + total_fees: 0, + ..W4_ZERO_EMPTY + }, + unproved(raw), + ), + ( + "companion action fee above its total", + W4_SKIPPED_EMPTY, + Root { + total_fees: 1, + ..W4_ZERO_EMPTY + }, + unproved(raw), + ), + ( + "zero operation total and action fee", + Root { + total_fees: 0, + action_fees: 0, + ..W4_SKIPPED_EMPTY + }, + W4_ZERO_EMPTY, + unproved(0), + ), + ]; + for (label, operation, companion, expected) in rows { + for (value, expected) in values.into_iter().zip(expected) { + let (result, scripted) = + run(W4, single(value, None, Shape::Empty, true), |address| { + vec![answer(address, operation), answer(address, companion)] + }); + assert_eq!(result, Err(expected), "{label}: {value}"); + assert_eq!( + scripted.http.calls(), + with_companion(W4_SKIPPED_EMPTY.block), + "{label}: {value}" + ); + } + } + } + + /// Synthetic two-message answers: the composite needs every message + /// skipped by the operation and created by the companion; a partial + /// delivery on either side is never priced. The two messages pay their + /// forwarding fees in different ways (modes 2 and 3), so the composite + /// fee stands without a spend. + #[test] + fn a_short_multi_message_operation_needs_full_delivery_on_both_sides() { + let operation = Root { + total_fees: 398_293, + delivery: (2, 2, 0), + action_fees: 3_332, + ..W4_SKIPPED_EMPTY + }; + let companion = Root { + total_fees: 441_716, + delivery: (2, 0, 2), + action_fees: 48_888, + forwarding: 146_668, + ..W4_ZERO_EMPTY + }; + let two = |values: [u64; 2]| { + request( + vec![ + message(values[0], Some(2), Shape::Empty), + message(values[1], None, Shape::Comment), + ], + true, + ) + }; + let short_request = two([600_000_000, 600_000_000]); + let (result, scripted) = run(W4, short_request.clone(), |address| { + vec![answer(address, operation), answer(address, companion)] + }); + assert_eq!( + result, + Err(short( + W4, + 1_200_000_000, + Some(operation.composite(companion)), + None + )) + ); + let emulations = scripted.http.emulations(); + assert_operation_and_companion(&short_request, W4, &emulations[0], &emulations[1]); + assert_eq!(decode(&emulations[1]).wallet.msgs_modes, [3, 3]); + + for partial in [(2, 1, 1), (2, 2, 1), (1, 1, 0)] { + let (result, scripted) = run(W4, short_request.clone(), |address| { + vec![answer( + address, + Root { + delivery: partial, + ..operation + }, + )] + }); + assert_eq!( + result, + Err(short(W4, 1_200_000_000, None, None)), + "{partial:?}" + ); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION, "{partial:?}"); + + let (result, scripted) = run(W4, short_request.clone(), |address| { + vec![ + answer(address, operation), + answer( + address, + Root { + delivery: partial, + ..companion + }, + ), + ] + }); + assert_eq!( + result, + Err(short(W4, 1_200_000_000, None, None)), + "{partial:?}" + ); + assert_eq!( + scripted.http.calls(), + with_companion(operation.block), + "{partial:?}" + ); + } + + let (result, _) = run(W4, two([100_000_000, 100_000_000]), |address| { + vec![answer( + address, + Root { + delivery: (2, 1, 1), + ..operation + }, + )] + }); + assert_eq!( + result, + Err(rejected( + "emulated wallet created only some of the messages" + )) + ); + } + + /// A created operation whose answer does not establish its spend is no + /// quote: never a success, and neither zero nor the root fee stands in + /// for the spend. The forwarding fees are missing or malformed, below the + /// action fee, the action fee is missing, the root fee is below the + /// action fee, or the spend is zero. The created operation's root fee + /// still decides the fee comparison's funds refusals, above the balance + /// and at `V + F >= B`, reported without a spend. The default preview of + /// the same answer is unchanged. A usable forwarding record prices the + /// created operation without gas or storage fees, which only the + /// composite needs. The edited rows are synthetic. + #[test] + fn an_unestablished_spend_is_never_a_quote() { + type Edit = fn(&mut serde_json::Value); + let keep: Edit = |_| {}; + let at_action_fee = Root { + total_fees: W4_CREATED_EMPTY.action_fees, + ..W4_CREATED_EMPTY + }; + let below_action_fee = Root { + total_fees: W4_CREATED_EMPTY.action_fees - 1, + ..W4_CREATED_EMPTY + }; + // Label, mode, answer and the edit of its root transaction. + let cases: [(&str, Option, Root, Edit); 12] = [ + ("forwarding fees absent", None, W4_CREATED_EMPTY, |root| { + let _ = root["description"]["action"] + .as_object_mut() + .expect("action") + .remove("total_fwd_fees"); + }), + ( + "forwarding fees null, mode 2", + Some(2), + W4_CREATED_EMPTY, + |root| { + root["description"]["action"]["total_fwd_fees"] = serde_json::Value::Null; + }, + ), + ("forwarding fees negative", None, W4_CREATED_EMPTY, |root| { + root["description"]["action"]["total_fwd_fees"] = "-73334".into(); + }), + ( + "forwarding fees fractional", + None, + W4_CREATED_EMPTY, + |root| { + root["description"]["action"]["total_fwd_fees"] = 73_334.5.into(); + }, + ), + ( + "forwarding fees not decimal", + None, + W4_CREATED_EMPTY, + |root| { + root["description"]["action"]["total_fwd_fees"] = "0x11e76".into(); + }, + ), + ("forwarding fees a list", None, W4_CREATED_EMPTY, |root| { + root["description"]["action"]["total_fwd_fees"] = serde_json::json!([73_334]); + }), + ( + "forwarding fees below the action fee", + None, + W4_CREATED_EMPTY, + |root| { + root["description"]["action"]["total_fwd_fees"] = "24443".into(); + }, + ), + ("action fee absent", None, W4_CREATED_EMPTY, |root| { + let _ = root["description"]["action"] + .as_object_mut() + .expect("action") + .remove("total_action_fees"); + }), + ("action fee malformed", Some(18), W4_CREATED_EMPTY, |root| { + root["description"]["action"]["total_action_fees"] = "x".into(); + }), + ( + "action phase without fees", + Some(19), + W4_CREATED_EMPTY, + |root| { + root["description"]["action"] = serde_json::json!({ + "success": true, + "result_code": 0, + "tot_actions": 1, + "skipped_actions": 0, + "msgs_created": 1, + }); + }, + ), + ( + "root fee below the action fee", + None, + below_action_fee, + keep, + ), + ("zero spend", Some(2), at_action_fee, keep), + ]; + let value = 100_000_000; + for (label, mode, root, edit) in cases { + let fee = root.total_fees; + let (opted, scripted) = run(W4, single(value, mode, Shape::Empty, true), |address| { + vec![edited(address, root, edit)] + }); + assert_eq!(opted, Err(unproved_spend()), "{label}"); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION, "{label}"); + let default = single(value, mode, Shape::Empty, false); + let (result, _) = run(W4, default.clone(), |address| { + vec![edited(address, root, edit)] + }); + assert_eq!(result, Ok(expected_preview(&default, W4, root)), "{label}"); + + // The fee comparison with the created root fee, no spend. + let above = 1_000_000_000; + let (result, _) = run(W4, single(above, mode, Shape::Empty, true), |address| { + vec![edited(address, root, edit)] + }); + assert_eq!(result, Err(short(W4, above, Some(fee), None)), "{label}"); + let at_fee = W4.balance - fee; + let (result, _) = run(W4, single(at_fee, mode, Shape::Empty, true), |address| { + vec![edited(address, root, edit)] + }); + assert_eq!( + result, + Err(short_for_fees(W4, at_fee, fee, Some(fee), None)), + "{label}" + ); + } + + // Usable forwarding fees without gas or storage fees still price + // the created operation. + let spend = debit_spend(value, 701_082_553, 600_614_258); + let edits: [Edit; 3] = [ + |root| { + let _ = root["description"]["compute_ph"] + .as_object_mut() + .expect("compute phase") + .remove("gas_used"); + }, + |root| { + let _ = root["description"] + .as_object_mut() + .expect("description") + .remove("storage_ph"); + }, + |root| root["description"]["storage_ph"] = "26".into(), + ]; + for (index, edit) in edits.into_iter().enumerate() { + let request = single(value, None, Shape::Empty, true); + let (result, _) = run(W4, request.clone(), |address| { + vec![edited(address, W4_CREATED_EMPTY, edit)] + }); + assert_eq!( + result, + Ok(expected_quote(&request, W4, W4_CREATED_EMPTY, spend)), + "edit {index}" + ); + } + + // A proved composite fee whose companion does not establish the + // spend keeps the fee comparison with that fee, without a spend. + let fee = W4_SKIPPED_EMPTY.composite(W4_ZERO_EMPTY); + let companions: [Edit; 3] = [ + |root| { + let _ = root["description"]["action"] + .as_object_mut() + .expect("action") + .remove("total_fwd_fees"); + }, + |root| root["description"]["action"]["total_fwd_fees"] = "x".into(), + |root| root["description"]["action"]["total_fwd_fees"] = "24443".into(), + ]; + for (index, edit) in companions.into_iter().enumerate() { + let rows = [ + (1_000_000_000, short(W4, 1_000_000_000, Some(fee), None)), + ( + W4.balance - fee, + short_for_fees(W4, W4.balance - fee, fee, Some(fee), None), + ), + (W4.balance - fee - 1, rejected(NONE_CREATED)), + ]; + for (value, expected) in rows { + let (result, scripted) = + run(W4, single(value, None, Shape::Empty, true), |address| { + vec![ + answer(address, W4_SKIPPED_EMPTY), + edited(address, W4_ZERO_EMPTY, edit), + ] + }); + assert_eq!(result, Err(expected), "companion {index}: {value}"); + assert_eq!( + scripted.http.calls(), + with_companion(W4_SKIPPED_EMPTY.block) + ); + } + } + } + + /// Synthetic two-message answers: messages that share one fee kind are + /// priced together from the aggregate action and forwarding fees, both + /// when the batch was created and when its composite prices a skipped + /// one. Messages whose fee kinds differ get no spend, so their opt-in + /// preview is no quote, while their default preview succeeds as before. + #[test] + fn a_uniform_batch_spends_its_aggregate_forwarding_fees() { + let two = |modes: [Option; 2], value: u64, estimate_shortfall: bool| { + request( + vec![ + message(value, modes[0], Shape::Empty), + message(value, modes[1], Shape::Empty), + ], + estimate_shortfall, + ) + }; + // `W4_CREATED_TWO`: F 443849, A 48888, T 146668, so F - A + T with + // +1 and F - A without it. + let rows = [ + ([None, Some(3)], Some(541_629)), + ([Some(3), Some(19)], Some(541_629)), + ([Some(2), Some(18)], Some(394_961)), + ([Some(2), None], None), + ([Some(18), Some(19)], None), + ]; + for (modes, spend) in rows { + let opted = two(modes, 100_000_000, true); + let (result, _) = run(W4, opted.clone(), |address| { + vec![answer(address, W4_CREATED_TWO)] + }); + let expected = spend.map_or_else( + || Err(unproved_spend()), + |spend| Ok(expected_quote(&opted, W4, W4_CREATED_TWO, spend)), + ); + assert_eq!(result, expected, "{modes:?}"); + let default = two(modes, 100_000_000, false); + let (result, _) = run(W4, default.clone(), |address| { + vec![answer(address, W4_CREATED_TWO)] + }); + assert_eq!( + result, + Ok(expected_preview(&default, W4, W4_CREATED_TWO)), + "{modes:?}" + ); + } + + // Skipped batch, its companion created with the fees above. + let operation = Root { + total_fees: 398_293, + delivery: (2, 2, 0), + action_fees: 3_332, + ..W4_SKIPPED_EMPTY + }; + let companion = Root { + delivery: (2, 0, 2), + ..W4_CREATED_TWO + }; + let fee = operation.composite(companion); + assert_eq!(fee, W4_CREATED_TWO.total_fees); + for (modes, spend) in rows { + let opted = two(modes, 600_000_000, true); + let (result, scripted) = run(W4, opted.clone(), |address| { + vec![answer(address, operation), answer(address, companion)] + }); + assert_eq!( + result, + Err(short(W4, 1_200_000_000, Some(fee), spend)), + "{modes:?}" + ); + let emulations = scripted.http.emulations(); + assert_operation_and_companion(&opted, W4, &emulations[0], &emulations[1]); + } + } + + /// Modes 2 and 18 take the forwarding fee from the message value, so the + /// wallet skips a value below that fee whatever its balance: with the + /// captured zero-value answers at `W4`'s block, the companion prices the + /// operation's spend, yet the preview stays the fee-less emulation refusal + /// where that spend fits, never a success or a funds refusal. Only a + /// (synthetic) balance below the spend makes it the funds refusal. The + /// one-nanogram value reuses the zero-value answers (synthetic). + #[test] + fn a_value_below_its_forwarding_fee_is_never_a_quote() { + let fee = W4_ZERO_EMPTY_KEPT_MODE.composite(W4_ZERO_EMPTY); + assert_eq!(fee, W4_ZERO_EMPTY.total_fees); + // F - A for a message without +1. + let spend = 392_828; + for mode in [Some(2), Some(18)] { + for value in [0, 1] { + let label = format!("{mode:?} {value}"); + let rows = [ + (W4, rejected(NONE_CREATED)), + ( + Account { + balance: value + spend, + ..W4 + }, + rejected(NONE_CREATED), + ), + ( + Account { + balance: value + spend - 1, + ..W4 + }, + spend_refusal( + Account { + balance: value + spend - 1, + ..W4 + }, + value, + fee, + spend, + ), + ), + ]; + for (account, expected) in rows { + let request = single(value, mode, Shape::Empty, true); + let (result, scripted) = run(account, request.clone(), |address| { + vec![ + answer(address, W4_ZERO_EMPTY_KEPT_MODE), + answer(address, W4_ZERO_EMPTY), + ] + }); + assert_eq!(result, Err(expected), "{label} {}", account.balance); + let emulations = scripted.http.emulations(); + assert_operation_and_companion( + &request, + account, + &emulations[0], + &emulations[1], + ); + } + let (result, scripted) = + run(W4, single(value, mode, Shape::Empty, false), |address| { + vec![answer(address, W4_ZERO_EMPTY_KEPT_MODE)] + }); + assert_eq!(result, Err(rejected(NONE_CREATED)), "{label}"); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + } + } + } + + /// The new fields are read leniently: without them, or with unusable + /// values, a default preview gives exactly the preview it gave before. + #[test] + fn default_previews_keep_their_parse_outcome_without_the_new_fields() { + let request = || single(100_000_000, None, Shape::Empty, false); + let (base, _) = run(W4, request(), |address| { + vec![answer(address, W4_CREATED_EMPTY)] + }); + let base = base.expect("the default preview succeeds"); + let edits: [fn(&mut serde_json::Value); 8] = [ + |root| { + let action = root["description"]["action"] + .as_object_mut() + .expect("action"); + for field in [ + "tot_actions", + "skipped_actions", + "msgs_created", + "total_action_fees", + "total_fwd_fees", + ] { + let _ = action.remove(field); + } + }, + |root| { + for field in ["tot_actions", "skipped_actions", "msgs_created"] { + root["description"]["action"][field] = (-1).into(); + } + }, + |root| root["description"]["action"]["total_action_fees"] = 1.5.into(), + |root| root["description"]["action"]["total_fwd_fees"] = "-73334".into(), + |root| root["description"]["action"]["total_fwd_fees"] = serde_json::json!([]), + |root| root["description"]["compute_ph"]["gas_used"] = serde_json::json!([3560]), + |root| { + let _ = root["description"] + .as_object_mut() + .expect("description") + .remove("storage_ph"); + }, + |root| root["description"]["storage_ph"] = "26".into(), + ]; + for (index, edit) in edits.into_iter().enumerate() { + let (result, scripted) = run(W4, request(), |address| { + vec![edited(address, W4_CREATED_EMPTY, edit)] + }); + assert_eq!(result.as_ref(), Ok(&base), "edit {index}"); + assert_eq!(scripted.http.calls(), UNTIL_OPERATION); + } + } + + /// Cancelling the preview while its companion is in flight cancels that + /// request, ends the preview with today's cancellation error, and the + /// same client previews again afterwards. + #[test] + fn cancelling_a_held_companion_cancels_it_and_the_next_preview_runs() { + let scripted = Scripted::new(W4, |address| { + vec![ + answer(address, W4_SKIPPED_EMPTY), + Reply::Held(Box::new(answer(address, W4_ZERO_EMPTY))), + answer(address, W4_CREATED_EMPTY), + ] + }); + let (held_sender, held) = mpsc::channel(); + let (release, release_receiver) = mpsc::channel(); + *scripted.http.hold.lock().expect("hold lock") = Some((held_sender, release_receiver)); + + let client = Arc::clone(&scripted.client); + let preview = std::thread::spawn(move || { + block_on(client.preview_send(single(1_000_000_000, Some(2), Shape::Empty, true))) + }); + let companion = held + .recv_timeout(Duration::from_secs(60)) + .expect("the companion request is held"); + assert_eq!( + scripted.http.calls(), + with_companion(W4_SKIPPED_EMPTY.block) + ); + assert_eq!( + scripted.http.requests().last().map(|request| request.id), + Some(companion) + ); + + block_on(scripted.client.cancel_send_preview()).expect("cancel succeeds"); + assert_eq!(scripted.http.cancelled(), [companion]); + release.send(()).expect("the held request waits"); + assert_eq!( + preview.join().expect("preview thread"), + Err(WalletClientError::StateUnavailable) + ); + assert!( + scripted + .client + .lock() + .expect("state") + .active_preview + .is_none() + ); + + let next = scripted + .preview(single(100_000_000, None, Shape::Empty, true)) + .expect("the next preview succeeds"); + assert_eq!( + next.emulation.wallet_fees_nanograms, + decimal(W4_CREATED_EMPTY.total_fees) + ); + assert_eq!(scripted.http.calls()[4..], UNTIL_OPERATION); + assert_eq!(scripted.http.cancelled(), [companion]); + assert_eq!(scripted.unused_answers(), 0); + } + + /// A frozen or unknown account above the balance keeps the funds refusal + /// without a fee after the account read; below it, the default error. + #[test] + fn frozen_or_unknown_accounts_above_the_balance_are_refused_without_a_fee() { + for status in [AccountStatus::Frozen, AccountStatus::Unknown] { + let account = Account { status, ..W4 }; + let (result, scripted) = run( + account, + single(1_000_000_000, None, Shape::Empty, true), + |_| Vec::new(), + ); + assert_eq!( + result, + Err(short(account, 1_000_000_000, None, None)), + "{status:?}" + ); + assert_eq!(scripted.http.calls(), [Call::Account]); + + let (opted, _) = run(account, single(1, None, Shape::Empty, true), |_| Vec::new()); + let (default, _) = run(account, single(1, None, Shape::Empty, false), |_| { + Vec::new() + }); + assert_eq!( + opted, + Err(WalletClientError::SendAccountUnavailable { status }) + ); + assert_eq!(opted, default); + } + } +} diff --git src/engine/send.rs src/engine/send.rs index 09d374f..6ca9bf7 100644 --- src/engine/send.rs +++ src/engine/send.rs @@ -184,10 +184,13 @@ impl WalletClient { // Reject an impossible value before reading the mnemonic or creating a signed BOC. // Fees are intentionally not estimated here, so equality can still fail on-chain. let available = &account.balance_nanograms; - let Ok(requested) = request.intent.exact_value_total() else { - let error = WalletClientError::InvalidSendRequest; - self.fail_send(generation, error.to_string())?; - return Err(error); + let requested = match request.intent.exact_value_total_for_external() { + Ok(requested) => requested, + Err(error) => { + let error = WalletClientError::from(error); + self.fail_send(generation, error.to_string())?; + return Err(error); + } }; if let Some(nanograms) = &requested && nanograms > available @@ -195,6 +198,8 @@ impl WalletClient { let error = WalletClientError::InsufficientBalance { available_nanograms: available.clone(), requested_nanograms: nanograms.clone(), + operation_fee_nanograms: None, + operation_spend_nanograms: None, }; self.fail_send(generation, error.to_string())?; return Err(error); diff --git src/engine/sign_message.rs src/engine/sign_message.rs index 7ae8e0a..2b949dc 100644 --- src/engine/sign_message.rs +++ src/engine/sign_message.rs @@ -159,8 +159,8 @@ impl WalletClient { }; self.publish_send_workflow(generation, &workflow)?; - if send_request.intent.exact_value_total().is_err() { - let error = WalletClientError::InvalidSendRequest; + if let Err(error) = send_request.intent.exact_value_total() { + let error = WalletClientError::from(error); self.fail_send(generation, error.to_string())?; return Err(error); } diff --git src/lib.rs src/lib.rs index af06abd..463d889 100644 --- src/lib.rs +++ src/lib.rs @@ -47,6 +47,7 @@ mod domain; mod engine; mod ton_connect; +mod ton_connect_tlb; mod transport; mod types; mod wallet; @@ -54,6 +55,9 @@ mod wallet; pub use domain::*; pub use engine::{WalletClient, WalletPlatformHost}; pub use ton_connect::*; +pub use ton_connect_tlb::{ + TonConnectSignDataCellDecoding, TonConnectSignDataCellFailure, TonConnectSignDataCellField, +}; pub use transport::*; pub use types::{ Base64Hash, Base64HashError, Boc, BocError, NonEmptyString, NonEmptyStringError, diff --git src/ton_connect.rs src/ton_connect.rs index fd07126..74081af 100644 --- src/ton_connect.rs +++ src/ton_connect.rs @@ -862,6 +862,7 @@ fn decode_transaction_request( }), bounce: message.address.is_bounceable(), state_init, + send_mode: None, }); } let operation_id = diff --git src/ton_connect/derived.rs src/ton_connect/derived.rs index c08665e..6687fc5 100644 --- src/ton_connect/derived.rs +++ src/ton_connect/derived.rs @@ -422,6 +422,27 @@ impl TonConnectDerivedSession { })) } + /// Decodes a `signData` cell by its TL-B schema for display. + /// + /// Pass the `schema` and `cell` of a `TonConnectSignDataPayload::Cell` exactly as received. + /// The result lists the fields of the schema's last declaration (the root constructor, whose + /// tag the cell must carry) in cell order, or reports the cell as not decodable when the + /// schema uses an unsupported construct or the cell does not match it; it is never a partial + /// list. Addresses are TEP-2 friendly, non-bounceable, and test-only on a testnet session. + /// Signing does not depend on this result. + #[must_use] + pub fn decode_sign_data_cell( + &self, + schema: String, + cell: String, + ) -> crate::TonConnectSignDataCellDecoding { + crate::ton_connect_tlb::decode_sign_data_cell( + &schema, + &cell, + self.network.as_str() == crate::Network::Testnet.global_id(), + ) + } + /// Encrypts the empty-object result of a dApp-initiated disconnect request. pub fn encrypt_disconnect_success( &self, diff --git src/ton_connect_tlb.rs src/ton_connect_tlb.rs new file mode 100644 index 0000000..c280bb4 --- /dev/null +++ src/ton_connect_tlb.rs @@ -0,0 +1,2804 @@ +//! TL-B display decoding of TON Connect `signData` cells. +//! +//! A `signData` request of type `cell` carries a one-root cell `BoC` and the +//! TL-B schema that describes it; the schema's last declaration is the root. +//! [`decode_sign_data_cell`] interprets a bounded subset of TL-B, reads the +//! cell with exactly that declaration (its tag must match; other constructors +//! of the same type serve only nested uses of the type) and lists its fields in +//! cell order for display. Both inputs come from the dApp: +//! every size is checked before a read or an allocation, parsing and decoding +//! are bounded in nesting, work and output, and any failure discards the +//! partial result. Signing never depends on the decoding. +//! +//! Supported: constructor tags `#hex`, `#hex_`, `#_`, `$bits`, `$_` and a bare +//! `_` constructor; fields `name:Type`, `_:Type`, anonymous types and +//! `^[ … ]` cells; conditional fields `flag?Type` and `(flag . bit)?Type`; +//! `{ a op b }` constraints over `+` and `*`; `{n:#}` and `{X:Type}` +//! parameters; `#`, `## n`, `#< n`, `#<= n`, `uintN`, `intN`, `bitsN` and +//! their applied forms; `Bool`, `Maybe`, `Either`, `Both`, `VarUInteger`, +//! `VarInteger`, `Coins`, `Grams`, `MsgAddress`, `MsgAddressInt`, +//! `MsgAddressExt`, `Cell`, `Any`, `^Type`; and every type the schema itself +//! declares, which shadows a builtin of the same name. + +use std::collections::HashSet; +use std::rc::Rc; + +use num_bigint::{BigInt, BigUint}; +use ton::ton_core::cell::{BoC, CellParser, TonCell}; +use ton::ton_core::traits::tlb::TLB as _; +use ton_connect_core::{CellBoc, FriendlyAddress, RawAccountAddress}; + +/// One decoded field of a `signData` cell. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TonConnectSignDataCellField { + /// Nesting level: 0 for the root's fields; entries after a structure entry + /// with a greater depth are its sub-fields. + pub depth: u32, + /// The field name exactly as the schema names it (`_` when unnamed). + pub name: String, + /// The display value; for a structure, its constructor name (empty for `_`). + pub value: String, +} + +/// Why a `signData` cell could not be decoded by its schema. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, uniffi::Enum)] +pub enum TonConnectSignDataCellFailure { + /// The schema is not valid TL-B text. + InvalidSchema, + /// The schema uses a construct the decoder does not support. + UnsupportedSchema, + /// The cell is not a valid one-root `BoC` or contains an exotic cell. + InvalidCell, + /// No constructor tag of a type matches the cell. + TagMismatch, + /// A `{ … }` constraint or a `#<`/`#<=` bound does not hold. + ConstraintViolated, + /// Bits or references remain after the schema is fully read. + TrailingData, + /// The cell ends before the schema is fully read. + TruncatedCell, + /// A size, nesting, work, or output bound was exceeded. + LimitExceeded, +} + +/// The result of decoding a `signData` cell by its TL-B schema. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum TonConnectSignDataCellDecoding { + /// The cell matches the schema exactly. + Decoded { + /// The root declaration's fields in cell order. + fields: Vec, + }, + /// The cell cannot be shown by its schema; no field is reported. + NotDecodable { + /// The typed reason. + failure: TonConnectSignDataCellFailure, + /// A short diagnostic for logs; it echoes at most 32 characters of input. + detail: String, + }, +} + +/// Longest accepted schema text in bytes, checked before lexing. +const MAX_SCHEMA_BYTES: usize = 16_384; +/// Most tokens one schema may contain. +const MAX_TOKENS: usize = 4_096; +/// Most declarations one schema may contain. +const MAX_DECLARATIONS: usize = 128; +/// Most parameters, fields, and constraints one declaration may contain. +const MAX_FIELDS_PER_DECLARATION: usize = 64; +/// Deepest nesting of parentheses, brackets, references, and operators in the schema text. +const MAX_PARSE_NESTING: usize = 32; +/// Deepest nesting of type instantiations while decoding. +const MAX_DECODE_DEPTH: u32 = 32; +/// Decoding steps one call may take (fields, types, constructor probes). +const MAX_STEPS: u32 = 20_000; +/// Most entries one result may contain. +const MAX_FIELDS: usize = 256; +/// Most bytes of names and values one result may contain. +const MAX_OUTPUT_BYTES: usize = 32_768; +/// Most distinct cells one `Cell`/`Any` value may contain, checked before it is serialized. +const MAX_CELL_VALUE_CELLS: usize = 256; +/// Longest constructor tag in bits. +const MAX_TAG_BITS: usize = 64; +/// Widest `uint` in bits. +const MAX_UINT_BITS: u64 = 256; +/// Widest `int` in bits. +const MAX_INT_BITS: u64 = 257; +/// Longest constant `bits` width; a cell holds at most 1023 data bits. +const MAX_BITS: u64 = 1023; +/// Widest `## n` in bits. +const MAX_NAT_BITS: u64 = 64; +/// Largest `n` of `VarUInteger n` and `VarInteger n`. +const MAX_VAR_INTEGER_BYTES: u64 = 32; +/// Most input characters one diagnostic echoes. +const DETAIL_ECHO_CHARS: usize = 32; + +/// Decodes a `signData` cell by the last declaration of its TL-B schema. +/// +/// `schema` and `cell` are the strings of a `cell` payload exactly as received; +/// `testnet` selects the test-only flag of friendly addresses. The result is +/// the full field list or a typed failure, never a partial list. +pub(crate) fn decode_sign_data_cell( + schema: &str, + cell: &str, + testnet: bool, +) -> TonConnectSignDataCellDecoding { + match decode(schema, cell, testnet) { + Ok(fields) => TonConnectSignDataCellDecoding::Decoded { fields }, + Err(Failure { kind, detail }) => TonConnectSignDataCellDecoding::NotDecodable { + failure: kind, + detail, + }, + } +} + +fn decode(schema: &str, cell: &str, testnet: bool) -> Outcome> { + if schema.len() > MAX_SCHEMA_BYTES { + return Err(limit("schema is longer than 16384 bytes")); + } + let tokens = tokenize(schema)?; + let schema = parse_schema(&tokens)?; + let boc = CellBoc::try_from(cell).map_err(|_| invalid_cell("cell is not a one-root BoC"))?; + let root = TonCell::from_boc(boc.as_bytes().to_vec()) + .map_err(|_| invalid_cell("cell is not a one-root BoC"))?; + if root.cell_type().is_exotic() { + return Err(invalid_cell("exotic cells are not decodable")); + } + let mut decoder = Decoder { + schema: &schema, + testnet, + steps: 0, + output: Vec::new(), + output_bytes: 0, + }; + let mut parser = root.parser(); + let root = schema.root()?; + let _ = decoder.decode_constructor( + &mut parser, + root, + &[], + &Env::default(), + Place { + name: "", + depth: 0, + level: 0, + }, + false, + )?; + ensure_empty(&mut parser)?; + Ok(decoder.output) +} + +/// An internal decoding failure; it becomes `NotDecodable`. +#[derive(Debug)] +struct Failure { + kind: TonConnectSignDataCellFailure, + detail: String, +} + +type Outcome = Result; + +fn failure(kind: TonConnectSignDataCellFailure, detail: impl Into) -> Failure { + Failure { + kind, + detail: detail.into(), + } +} + +fn invalid(detail: impl Into) -> Failure { + failure(TonConnectSignDataCellFailure::InvalidSchema, detail) +} + +fn unsupported(detail: impl Into) -> Failure { + failure(TonConnectSignDataCellFailure::UnsupportedSchema, detail) +} + +fn invalid_cell(detail: impl Into) -> Failure { + failure(TonConnectSignDataCellFailure::InvalidCell, detail) +} + +fn truncated(detail: impl Into) -> Failure { + failure(TonConnectSignDataCellFailure::TruncatedCell, detail) +} + +fn limit(detail: impl Into) -> Failure { + failure(TonConnectSignDataCellFailure::LimitExceeded, detail) +} + +fn tag_mismatch(type_name: &str) -> Failure { + failure( + TonConnectSignDataCellFailure::TagMismatch, + format!("tag mismatch in {:?}", echo(type_name)), + ) +} + +fn truncated_tag(type_name: &str) -> Failure { + truncated(format!("cell ends before a tag of {:?}", echo(type_name))) +} + +/// At most `DETAIL_ECHO_CHARS` characters of untrusted input for a diagnostic. +fn echo(text: &str) -> String { + text.chars().take(DETAIL_ECHO_CHARS).collect() +} + +// --------------------------------------------------------------------------- +// Lexer +// --------------------------------------------------------------------------- + +/// A constructor tag: `len` bits holding `bits`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Tag { + bits: u64, + len: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Token { + Ident(String), + Number(u64), + /// A constructor tag written directly after a constructor name. + Tag(Tag), + Colon, + Semicolon, + Equals, + LeftParen, + RightParen, + LeftBracket, + RightBracket, + LeftBrace, + RightBrace, + Caret, + Tilde, + Question, + Dot, + Plus, + Star, + Bang, + Less, + LessEq, + Greater, + GreaterEq, + Hash, + HashHash, + HashLess, + HashLessEq, +} + +fn tokenize(schema: &str) -> Outcome> { + let mut lexer = Lexer { + chars: schema.chars().collect(), + position: 0, + tokens: Vec::new(), + }; + lexer.run()?; + Ok(lexer.tokens) +} + +struct Lexer { + chars: Vec, + position: usize, + tokens: Vec, +} + +impl Lexer { + fn peek(&self, offset: usize) -> Option { + self.position + .checked_add(offset) + .and_then(|index| self.chars.get(index).copied()) + } + + const fn bump(&mut self) { + self.position = self.position.saturating_add(1); + } + + fn push(&mut self, token: Token) -> Outcome<()> { + if self.tokens.len() >= MAX_TOKENS { + return Err(limit("schema has more than 4096 tokens")); + } + self.tokens.push(token); + Ok(()) + } + + fn run(&mut self) -> Outcome<()> { + while let Some(current) = self.peek(0) { + if current.is_whitespace() { + self.bump(); + } else if current == '/' { + self.comment()?; + } else if current.is_ascii_alphabetic() || current == '_' { + self.identifier()?; + } else if current.is_ascii_digit() { + self.number()?; + } else { + self.punctuation(current)?; + } + } + Ok(()) + } + + fn comment(&mut self) -> Outcome<()> { + match self.peek(1) { + Some('/') => { + while let Some(current) = self.peek(0) { + self.bump(); + if current == '\n' { + break; + } + } + Ok(()) + } + Some('*') => { + self.bump(); + self.bump(); + loop { + match (self.peek(0), self.peek(1)) { + (Some('*'), Some('/')) => { + self.bump(); + self.bump(); + return Ok(()); + } + (Some(_), _) => self.bump(), + (None, _) => return Err(invalid("unterminated comment")), + } + } + } + Some(_) | None => Err(invalid("unexpected '/'")), + } + } + + fn identifier(&mut self) -> Outcome<()> { + let mut name = String::new(); + while let Some(current) = self.peek(0) { + if !current.is_ascii_alphanumeric() && current != '_' { + break; + } + name.push(current); + self.bump(); + } + self.push(Token::Ident(name))?; + match self.peek(0) { + Some('#') => self.hex_tag(), + Some('$') => self.binary_tag(), + Some(_) | None => Ok(()), + } + } + + /// `#hex`, `#hex_` (completion tag) or `#_`, directly after a name. + fn hex_tag(&mut self) -> Outcome<()> { + self.bump(); + let mut bits = 0_u64; + let mut len = 0_usize; + while let Some(digit) = self.peek(0).and_then(|current| current.to_digit(16)) { + len = len + .checked_add(4) + .filter(|len| *len <= MAX_TAG_BITS) + .ok_or_else(|| unsupported("constructor tag is longer than 64 bits"))?; + bits = bits.wrapping_shl(4) | u64::from(digit); + self.bump(); + } + let completion = self.peek(0) == Some('_'); + if completion { + self.bump(); + } else if len == 0 { + return Err(unsupported("implicit constructor tags are not supported")); + } + if completion && len > 0 { + if bits == 0 { + return Err(invalid("completion tag has no end bit")); + } + let strip = bits.trailing_zeros().saturating_add(1); + bits = bits.checked_shr(strip).unwrap_or(0); + len = usize::try_from(strip) + .ok() + .and_then(|strip| len.checked_sub(strip)) + .ok_or_else(|| invalid("completion tag has no end bit"))?; + } + self.push(Token::Tag(Tag { bits, len })) + } + + /// `$bits` or `$_`, directly after a name. + fn binary_tag(&mut self) -> Outcome<()> { + self.bump(); + if self.peek(0) == Some('_') { + self.bump(); + return self.push(Token::Tag(Tag { bits: 0, len: 0 })); + } + let mut bits = 0_u64; + let mut len = 0_usize; + while let Some(digit) = self.peek(0).and_then(|current| current.to_digit(2)) { + len = len + .checked_add(1) + .filter(|len| *len <= MAX_TAG_BITS) + .ok_or_else(|| unsupported("constructor tag is longer than 64 bits"))?; + bits = bits.wrapping_shl(1) | u64::from(digit); + self.bump(); + } + if len == 0 { + return Err(invalid("'$' must be followed by binary digits or '_'")); + } + self.push(Token::Tag(Tag { bits, len })) + } + + fn number(&mut self) -> Outcome<()> { + let mut value = 0_u64; + while let Some(digit) = self.peek(0).and_then(|current| current.to_digit(10)) { + value = value + .checked_mul(10) + .and_then(|value| value.checked_add(u64::from(digit))) + .ok_or_else(|| limit("number in schema is too large"))?; + self.bump(); + } + self.push(Token::Number(value)) + } + + fn punctuation(&mut self, current: char) -> Outcome<()> { + let next = self.peek(1); + let (token, width) = match current { + ':' => (Token::Colon, 1), + ';' => (Token::Semicolon, 1), + '=' => (Token::Equals, 1), + '(' => (Token::LeftParen, 1), + ')' => (Token::RightParen, 1), + '[' => (Token::LeftBracket, 1), + ']' => (Token::RightBracket, 1), + '{' => (Token::LeftBrace, 1), + '}' => (Token::RightBrace, 1), + '^' => (Token::Caret, 1), + '~' => (Token::Tilde, 1), + '?' => (Token::Question, 1), + '.' => (Token::Dot, 1), + '+' => (Token::Plus, 1), + '*' => (Token::Star, 1), + '!' => (Token::Bang, 1), + '<' if next == Some('=') => (Token::LessEq, 2), + '<' => (Token::Less, 1), + '>' if next == Some('=') => (Token::GreaterEq, 2), + '>' => (Token::Greater, 1), + '#' if next == Some('#') => (Token::HashHash, 2), + '#' if next == Some('<') && self.peek(2) == Some('=') => (Token::HashLessEq, 3), + '#' if next == Some('<') => (Token::HashLess, 2), + '#' => (Token::Hash, 1), + other => return Err(invalid(format!("unexpected character {other:?}"))), + }; + for _ in 0..width { + self.bump(); + } + self.push(token) + } +} + +// --------------------------------------------------------------------------- +// Schema +// --------------------------------------------------------------------------- + +struct Schema { + /// Never empty; the last one is the root. + declarations: Vec, +} + +impl Schema { + /// The root: exactly the last declaration, not every constructor of its type. + fn root(&self) -> Outcome<&Declaration> { + self.declarations + .last() + .ok_or_else(|| invalid("schema has no declarations")) + } + + fn declares(&self, name: &str) -> bool { + self.declarations + .iter() + .any(|declaration| declaration.result == name) + } +} + +struct Declaration { + constructor: String, + tag: Tag, + params: Vec, + items: Vec, + result: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ParamKind { + Nat, + Type, +} + +struct Param { + name: String, + kind: ParamKind, +} + +enum Item { + Field(Field), + Constraint(Constraint), + /// An anonymous `^[ … ]` cell whose fields belong to the enclosing level. + Inline(Vec), +} + +struct Field { + name: String, + condition: Option, + ty: TypeExpr, +} + +/// `flag?T` (`bit` is `None`) or `(flag . bit)?T`. +struct Condition { + flag: String, + bit: Option, +} + +struct Constraint { + left: NatExpr, + relation: Relation, + right: NatExpr, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Relation { + Equal, + Less, + LessEqual, + Greater, + GreaterEqual, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SizedKind { + /// `uint n`, `uintN`, `#`. + Uint, + /// `int n`, `intN`. + Int, + /// `bits n`, `bitsN`. + Bits, + /// `## n`. + NatBits, + /// `#< n`. + NatLess, + /// `#<= n`. + NatLessEqual, +} + +enum TypeExpr { + Named(String, Vec), + Ref(Box), + /// A named field's `^[ … ]` cell. + InlineCell(Vec), + Sized(SizedKind, NatExpr), +} + +enum Arg { + Type(TypeExpr), + Nat(NatExpr), +} + +enum NatExpr { + Const(u64), + Var(String), + Add(Box, Box), + Mul(Box, Box), +} + +/// Rejects widths the decoder cannot read; `constant` widths of `bits` must fit a cell. +fn check_width(kind: SizedKind, width: u64, constant: bool) -> Outcome<()> { + let supported = match kind { + SizedKind::Uint => width <= MAX_UINT_BITS, + SizedKind::Int => (1..=MAX_INT_BITS).contains(&width), + SizedKind::Bits => !constant || width <= MAX_BITS, + SizedKind::NatBits => width <= MAX_NAT_BITS, + SizedKind::NatLess => width > 0, + SizedKind::NatLessEqual => true, + }; + if supported { + Ok(()) + } else { + Err(unsupported(format!("unsupported width {width}"))) + } +} + +/// `uintN`, `intN` and `bitsN` names. +fn sized_name(name: &str) -> Outcome> { + for (prefix, kind) in [ + ("uint", SizedKind::Uint), + ("int", SizedKind::Int), + ("bits", SizedKind::Bits), + ] { + let Some(digits) = name.strip_prefix(prefix) else { + continue; + }; + if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) { + continue; + } + let width = digits + .parse::() + .map_err(|_| unsupported(format!("unsupported type {:?}", echo(name))))?; + check_width(kind, width, true)?; + return Ok(Some((kind, width))); + } + Ok(None) +} + +fn parse_schema(tokens: &[Token]) -> Outcome { + let mut parser = Parser { + tokens, + position: 0, + nesting: 0, + items: 0, + nat_names: Vec::new(), + }; + let mut declarations = Vec::new(); + while parser.peek(0).is_some() { + if declarations.len() >= MAX_DECLARATIONS { + return Err(limit("schema has more than 128 declarations")); + } + declarations.push(parser.declaration()?); + } + let schema = Schema { declarations }; + if !schema.root()?.params.is_empty() { + return Err(unsupported("the root type has parameters")); + } + Ok(schema) +} + +enum Braced { + Param(Param), + Constraint(Constraint), +} + +struct Parser<'t> { + tokens: &'t [Token], + position: usize, + nesting: usize, + /// Items of the current declaration. + items: usize, + /// Names that denote numbers in the current declaration. + nat_names: Vec<&'t str>, +} + +impl<'t> Parser<'t> { + fn peek(&self, offset: usize) -> Option<&'t Token> { + self.position + .checked_add(offset) + .and_then(|index| self.tokens.get(index)) + } + + const fn advance(&mut self, count: usize) { + self.position = self.position.saturating_add(count); + } + + fn next(&mut self) -> Option<&'t Token> { + let token = self.peek(0); + if token.is_some() { + self.advance(1); + } + token + } + + fn expect(&mut self, expected: &Token, what: &str) -> Outcome<()> { + if self.next() == Some(expected) { + Ok(()) + } else { + Err(invalid(format!("expected {what}"))) + } + } + + fn enter(&mut self) -> Outcome<()> { + self.nesting = self.nesting.saturating_add(1); + if self.nesting > MAX_PARSE_NESTING { + return Err(limit("schema nesting is deeper than 32")); + } + Ok(()) + } + + const fn leave(&mut self) { + self.nesting = self.nesting.saturating_sub(1); + } + + fn count_item(&mut self) -> Outcome<()> { + self.items = self.items.saturating_add(1); + if self.items > MAX_FIELDS_PER_DECLARATION { + return Err(limit("declaration has more than 64 fields")); + } + Ok(()) + } + + fn is_nat_name(&self, name: &str) -> bool { + self.nat_names.contains(&name) + } + + fn declaration(&mut self) -> Outcome { + self.items = 0; + self.nat_names.clear(); + let constructor = match self.next() { + Some(Token::Ident(name)) => name.clone(), + Some(Token::Bang) => return Err(unsupported("special constructors")), + Some(_) | None => return Err(invalid("expected a constructor name")), + }; + let tag = if let Some(Token::Tag(tag)) = self.peek(0) { + self.advance(1); + *tag + } else if constructor == "_" { + Tag { bits: 0, len: 0 } + } else { + return Err(unsupported("implicit constructor tags are not supported")); + }; + let mut params = Vec::new(); + let items = self.items_until(&Token::Equals, Some(&mut params))?; + let result = match self.next() { + Some(Token::Ident(name)) => name.clone(), + Some(Token::Tilde) => return Err(unsupported("deduced parameters")), + Some(_) | None => return Err(invalid("expected a type name after '='")), + }; + let mut result_args = Vec::new(); + loop { + match self.next() { + Some(Token::Semicolon) | None => break, + Some(Token::Ident(name)) => result_args.push(name.as_str()), + Some(Token::Tilde) => return Err(unsupported("deduced parameters")), + Some(Token::LeftParen | Token::Number(_) | Token::Plus | Token::Star) => { + return Err(unsupported("computed type arguments")); + } + Some(_) => return Err(invalid("unexpected token in a type")), + } + } + let declared = params.iter().map(|param: &Param| param.name.as_str()); + if !result_args.iter().copied().eq(declared) { + return Err(unsupported( + "type arguments must be the declared parameters in order", + )); + } + Ok(Declaration { + constructor, + tag, + params, + items, + result, + }) + } + + /// Items up to `end`; `params` is `None` inside a `^[ … ]` cell. + fn items_until( + &mut self, + end: &Token, + mut params: Option<&mut Vec>, + ) -> Outcome> { + let mut items = Vec::new(); + loop { + match self.peek(0) { + None => return Err(invalid("declaration is incomplete")), + Some(token) if token == end => { + self.advance(1); + return Ok(items); + } + Some(Token::LeftBrace) => { + self.advance(1); + self.count_item()?; + match self.braced()? { + Braced::Param(param) => { + let Some(params) = params.as_deref_mut() else { + return Err(unsupported("parameters inside a cell")); + }; + params.push(param); + } + Braced::Constraint(constraint) => { + items.push(Item::Constraint(constraint)); + } + } + } + Some(_) => { + self.count_item()?; + items.push(self.item()?); + } + } + } + } + + /// `{n:#}`, `{X:Type}` or a constraint; the `{` is consumed. + fn braced(&mut self) -> Outcome { + if let (Some(Token::Ident(name)), Some(Token::Colon)) = (self.peek(0), self.peek(1)) { + let kind = match self.peek(2) { + Some(Token::Hash) => ParamKind::Nat, + Some(Token::Ident(kind)) if kind == "Type" => ParamKind::Type, + Some(_) | None => return Err(unsupported("unsupported parameter kind")), + }; + self.advance(3); + self.expect(&Token::RightBrace, "'}'")?; + if kind == ParamKind::Nat { + self.nat_names.push(name); + } + return Ok(Braced::Param(Param { + name: name.clone(), + kind, + })); + } + let left = self.nat_sum()?; + let relation = match self.next() { + Some(Token::Equals) => Relation::Equal, + Some(Token::Less) => Relation::Less, + Some(Token::LessEq) => Relation::LessEqual, + Some(Token::Greater) => Relation::Greater, + Some(Token::GreaterEq) => Relation::GreaterEqual, + Some(Token::Tilde) => return Err(unsupported("deduced parameters")), + Some(_) | None => return Err(invalid("expected a comparison")), + }; + let right = self.nat_sum()?; + self.expect(&Token::RightBrace, "'}'")?; + Ok(Braced::Constraint(Constraint { + left, + relation, + right, + })) + } + + fn item(&mut self) -> Outcome { + match (self.peek(0), self.peek(1)) { + (Some(Token::Ident(name)), Some(Token::Colon)) => { + self.advance(2); + let condition = self.condition()?; + let ty = self.type_term()?; + if name != "_" { + self.nat_names.push(name); + } + Ok(Item::Field(Field { + name: name.clone(), + condition, + ty, + })) + } + (Some(Token::Caret), Some(Token::LeftBracket)) => { + self.advance(2); + Ok(Item::Inline(self.inline_items()?)) + } + (Some(Token::LeftBracket), _) => Err(unsupported("records without '^'")), + (Some(Token::Tilde), _) => Err(unsupported("deduced parameters")), + _ => Ok(Item::Field(Field { + name: "_".to_owned(), + condition: None, + ty: self.type_term()?, + })), + } + } + + /// The items of `^[ … ]`; the `^[` is consumed. + fn inline_items(&mut self) -> Outcome> { + self.enter()?; + let items = self.items_until(&Token::RightBracket, None); + self.leave(); + items + } + + fn condition(&mut self) -> Outcome> { + if let (Some(Token::Ident(flag)), Some(Token::Question)) = (self.peek(0), self.peek(1)) { + self.advance(2); + return Ok(Some(Condition { + flag: flag.clone(), + bit: None, + })); + } + if let ( + Some(Token::LeftParen), + Some(Token::Ident(flag)), + Some(Token::Dot), + Some(Token::Number(bit)), + Some(Token::RightParen), + Some(Token::Question), + ) = ( + self.peek(0), + self.peek(1), + self.peek(2), + self.peek(3), + self.peek(4), + self.peek(5), + ) { + let bit = u32::try_from(*bit) + .ok() + .filter(|bit| *bit < u64::BITS) + .ok_or_else(|| unsupported("condition bit is above 63"))?; + self.advance(6); + return Ok(Some(Condition { + flag: flag.clone(), + bit: Some(bit), + })); + } + Ok(None) + } + + fn type_term(&mut self) -> Outcome { + self.enter()?; + let term = self.type_term_inner(); + self.leave(); + term + } + + fn type_term_inner(&mut self) -> Outcome { + match self.next() { + Some(Token::Caret) => { + if self.peek(0) == Some(&Token::LeftBracket) { + self.advance(1); + Ok(TypeExpr::InlineCell(self.inline_items()?)) + } else { + Ok(TypeExpr::Ref(Box::new(self.type_term()?))) + } + } + Some(Token::LeftParen) => { + let term = self.applied()?; + self.expect(&Token::RightParen, "')'")?; + Ok(term) + } + Some(Token::Hash) => Ok(TypeExpr::Sized(SizedKind::Uint, NatExpr::Const(32))), + Some(Token::HashHash) => self.sized(SizedKind::NatBits, false), + Some(Token::HashLess) => self.sized(SizedKind::NatLess, false), + Some(Token::HashLessEq) => self.sized(SizedKind::NatLessEqual, false), + Some(Token::Ident(name)) => Ok(match sized_name(name)? { + Some((kind, width)) => TypeExpr::Sized(kind, NatExpr::Const(width)), + None => TypeExpr::Named(name.clone(), Vec::new()), + }), + Some(Token::LeftBracket) => Err(unsupported("records without '^'")), + Some(Token::Tilde) => Err(unsupported("deduced parameters")), + Some(_) | None => Err(invalid("expected a type")), + } + } + + /// A sized builtin; `whole` takes the whole expression up to `)`. + fn sized(&mut self, kind: SizedKind, whole: bool) -> Outcome { + let width = if whole { + self.nat_sum()? + } else { + self.nat_primary()? + }; + if let NatExpr::Const(width) = width { + check_width(kind, width, true)?; + } + Ok(TypeExpr::Sized(kind, width)) + } + + /// The inside of `( … )`; the `(` is consumed. + fn applied(&mut self) -> Outcome { + match (self.peek(0), self.peek(1)) { + (Some(Token::HashHash), _) => { + self.advance(1); + return self.sized(SizedKind::NatBits, true); + } + (Some(Token::HashLess), _) => { + self.advance(1); + return self.sized(SizedKind::NatLess, true); + } + (Some(Token::HashLessEq), _) => { + self.advance(1); + return self.sized(SizedKind::NatLessEqual, true); + } + (Some(Token::Ident(head)), Some(next)) + if matches!(head.as_str(), "uint" | "int" | "bits") + && next != &Token::RightParen => + { + let kind = match head.as_str() { + "uint" => SizedKind::Uint, + "int" => SizedKind::Int, + _ => SizedKind::Bits, + }; + self.advance(1); + return self.sized(kind, true); + } + (Some(Token::Number(_)), _) | (Some(Token::Ident(_)), Some(Token::Star)) => { + return Err(unsupported("tuples")); + } + _ => {} + } + let head = self.type_term()?; + let mut args = Vec::new(); + while !matches!(self.peek(0), Some(Token::RightParen) | None) { + if args.len() >= MAX_FIELDS_PER_DECLARATION { + return Err(limit("type has more than 64 arguments")); + } + args.push(self.arg()?); + } + if args.is_empty() { + return Ok(head); + } + if let TypeExpr::Named(name, existing) = head + && existing.is_empty() + { + return Ok(TypeExpr::Named(name, args)); + } + Err(invalid("only a type name takes arguments")) + } + + fn arg(&mut self) -> Outcome { + match self.peek(0) { + Some(Token::Number(_)) => Ok(Arg::Nat(self.nat_primary()?)), + Some(Token::Ident(name)) if self.is_nat_name(name) => Ok(Arg::Nat(self.nat_primary()?)), + Some(Token::LeftParen) if self.parenthesized_nat() => Ok(Arg::Nat(self.nat_primary()?)), + Some(_) | None => Ok(Arg::Type(self.type_term()?)), + } + } + + /// Whether the parenthesized argument at the cursor is arithmetic. + fn parenthesized_nat(&self) -> bool { + let mut offset = 0_usize; + while self.peek(offset) == Some(&Token::LeftParen) { + offset = offset.saturating_add(1); + } + match self.peek(offset) { + Some(Token::Number(_)) => true, + Some(Token::Ident(name)) if self.is_nat_name(name) => matches!( + self.peek(offset.saturating_add(1)), + Some(Token::Plus | Token::Star | Token::RightParen) + ), + Some(_) | None => false, + } + } + + fn nat_sum(&mut self) -> Outcome { + self.nat_chain(&Token::Plus) + } + + fn nat_product(&mut self) -> Outcome { + self.nat_chain(&Token::Star) + } + + /// A left-associative chain; every operator counts as one nesting level. + fn nat_chain(&mut self, operator: &Token) -> Outcome { + let operand = |parser: &mut Self| { + if operator == &Token::Plus { + parser.nat_product() + } else { + parser.nat_primary() + } + }; + let mut left = operand(self)?; + let mut entered = 0_usize; + let mut result = Ok(()); + while self.peek(0) == Some(operator) { + self.advance(1); + if let Err(error) = self.enter() { + result = Err(error); + entered = entered.saturating_add(1); + break; + } + entered = entered.saturating_add(1); + match operand(self) { + Ok(right) => { + left = if operator == &Token::Plus { + NatExpr::Add(Box::new(left), Box::new(right)) + } else { + NatExpr::Mul(Box::new(left), Box::new(right)) + }; + } + Err(error) => { + result = Err(error); + break; + } + } + } + for _ in 0..entered { + self.leave(); + } + result.map(|()| left) + } + + fn nat_primary(&mut self) -> Outcome { + self.enter()?; + let primary = match self.next() { + Some(Token::Number(value)) => Ok(NatExpr::Const(*value)), + Some(Token::Ident(name)) => Ok(NatExpr::Var(name.clone())), + Some(Token::LeftParen) => self + .nat_sum() + .and_then(|sum| self.expect(&Token::RightParen, "')'").map(|()| sum)), + Some(Token::Tilde) => Err(unsupported("deduced parameters")), + Some(_) | None => Err(invalid("expected a number or a name")), + }; + self.leave(); + primary + } +} + +// --------------------------------------------------------------------------- +// Decoder +// --------------------------------------------------------------------------- + +/// A type argument bound to a parameter, with the environment it is read in. +#[derive(Clone)] +struct Bound<'s> { + ty: &'s TypeExpr, + env: Rc>, +} + +/// Numbers and types visible to one constructor instance. +#[derive(Clone, Default)] +struct Env<'s> { + nats: Vec<(&'s str, u64)>, + types: Vec<(&'s str, Bound<'s>)>, +} + +impl<'s> Env<'s> { + fn nat(&self, name: &str) -> Option { + self.nats + .iter() + .rev() + .find(|(known, _)| *known == name) + .map(|(_, value)| *value) + } + + fn ty(&self, name: &str) -> Option<&Bound<'s>> { + self.types + .iter() + .rev() + .find(|(known, _)| *known == name) + .map(|(_, bound)| bound) + } + + fn eval(&self, expr: &NatExpr) -> Outcome { + match expr { + NatExpr::Const(value) => Ok(*value), + NatExpr::Var(name) => self + .nat(name) + .ok_or_else(|| unsupported(format!("{:?} is not a bound number", echo(name)))), + NatExpr::Add(left, right) => self + .eval(left)? + .checked_add(self.eval(right)?) + .ok_or_else(|| unsupported("arithmetic overflow")), + NatExpr::Mul(left, right) => self + .eval(left)? + .checked_mul(self.eval(right)?) + .ok_or_else(|| unsupported("arithmetic overflow")), + } + } +} + +/// Where a decoded value goes: its name, its display depth and its decode nesting. +#[derive(Clone, Copy)] +struct Place<'n> { + name: &'n str, + depth: u32, + level: u32, +} + +impl<'n> Place<'n> { + /// The same entry one decode level deeper. + const fn deeper(self) -> Self { + Place { + level: self.level.saturating_add(1), + ..self + } + } + + /// A sub-field of this entry. + const fn child(self, name: &'n str) -> Self { + Place { + name, + depth: self.depth.saturating_add(1), + level: self.level.saturating_add(1), + } + } +} + +/// Which `MsgAddress` constructors a type admits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum AddressKinds { + Any, + Internal, + External, +} + +struct Decoder<'s> { + schema: &'s Schema, + testnet: bool, + steps: u32, + output: Vec, + output_bytes: usize, +} + +impl<'s> Decoder<'s> { + fn step(&mut self) -> Outcome<()> { + self.steps = self.steps.saturating_add(1); + if self.steps > MAX_STEPS { + return Err(limit("decoding takes more than 20000 steps")); + } + Ok(()) + } + + fn ensure_room(&self, bytes: usize) -> Outcome<()> { + if self.output.len() >= MAX_FIELDS { + return Err(limit("result has more than 256 fields")); + } + if self + .output_bytes + .checked_add(bytes) + .is_none_or(|total| total > MAX_OUTPUT_BYTES) + { + return Err(limit("result is longer than 32768 bytes")); + } + Ok(()) + } + + fn push(&mut self, place: Place<'_>, value: String) -> Outcome<()> { + let bytes = place.name.len().saturating_add(value.len()); + self.ensure_room(bytes)?; + self.output_bytes = self.output_bytes.saturating_add(bytes); + self.output.push(TonConnectSignDataCellField { + depth: place.depth, + name: place.name.to_owned(), + value, + }); + Ok(()) + } + + /// Decodes one value of `ty`; returns its number when it binds one. + fn decode_type( + &mut self, + parser: &mut CellParser<'_>, + ty: &'s TypeExpr, + env: &Env<'s>, + place: Place<'_>, + ) -> Outcome> { + self.step()?; + if place.level > MAX_DECODE_DEPTH { + return Err(limit("cell nesting is deeper than 32")); + } + match ty { + TypeExpr::Sized(kind, width) => { + let width = env.eval(width)?; + self.decode_sized(parser, *kind, width, place) + } + TypeExpr::Ref(inner) => { + let child = next_ref(parser)?; + let mut child_parser = child.parser(); + let value = self.decode_type(&mut child_parser, inner, env, place.deeper())?; + ensure_empty(&mut child_parser)?; + Ok(value) + } + TypeExpr::InlineCell(items) => { + self.push(place, String::new())?; + let child = next_ref(parser)?; + let mut child_parser = child.parser(); + let mut scope = env.clone(); + self.decode_items(&mut child_parser, items, &mut scope, "_", place.child(""))?; + ensure_empty(&mut child_parser)?; + Ok(None) + } + TypeExpr::Named(name, args) => { + if args.is_empty() + && let Some(bound) = env.ty(name) + { + let bound = bound.clone(); + return self.decode_type(parser, bound.ty, &bound.env, place.deeper()); + } + if self.schema.declares(name) { + return self.decode_declared(parser, name, args, env, place, true); + } + self.decode_builtin(parser, name, args, env, place) + } + } + } + + /// Decodes a schema-declared type; `emit` pushes its structure entry. + fn decode_declared( + &mut self, + parser: &mut CellParser<'_>, + type_name: &str, + args: &'s [Arg], + env: &Env<'s>, + place: Place<'_>, + emit: bool, + ) -> Outcome> { + let bits_left = bits_left(parser)?; + let mut chosen = None; + let mut fits = false; + for declaration in &self.schema.declarations { + if declaration.result != type_name { + continue; + } + self.step()?; + if declaration.tag.len > bits_left { + continue; + } + fits = true; + let mut probe = parser.clone(); + if read_u64(&mut probe, declaration.tag.len)? != declaration.tag.bits { + continue; + } + if chosen.is_some() { + return Err(unsupported(format!( + "ambiguous constructor tags in {:?}", + echo(type_name) + ))); + } + chosen = Some(declaration); + } + let Some(declaration) = chosen else { + return Err(if fits { + tag_mismatch(type_name) + } else { + truncated_tag(type_name) + }); + }; + self.decode_constructor(parser, declaration, args, env, place, emit) + } + + /// Reads the tag of `declaration`, then its items; `emit` pushes its structure entry. + fn decode_constructor( + &mut self, + parser: &mut CellParser<'_>, + declaration: &'s Declaration, + args: &'s [Arg], + env: &Env<'s>, + place: Place<'_>, + emit: bool, + ) -> Outcome> { + let type_name = declaration.result.as_str(); + if declaration.tag.len > bits_left(parser)? { + return Err(truncated_tag(type_name)); + } + if read_u64(parser, declaration.tag.len)? != declaration.tag.bits { + return Err(tag_mismatch(type_name)); + } + if args.len() != declaration.params.len() { + return Err(unsupported(format!( + "wrong number of arguments for {:?}", + echo(type_name) + ))); + } + let mut inner = Env::default(); + let mut captured: Option>> = None; + for (param, arg) in declaration.params.iter().zip(args) { + match (param.kind, arg) { + (ParamKind::Nat, Arg::Nat(expr)) => { + inner.nats.push((param.name.as_str(), env.eval(expr)?)); + } + (ParamKind::Type, Arg::Type(ty)) => { + self.step()?; + let env = Rc::clone(captured.get_or_insert_with(|| Rc::new(env.clone()))); + inner.types.push((param.name.as_str(), Bound { ty, env })); + } + (ParamKind::Nat, Arg::Type(_)) | (ParamKind::Type, Arg::Nat(_)) => { + return Err(unsupported(format!( + "argument kind mismatch for {:?}", + echo(type_name) + ))); + } + } + } + let items_place = if emit { + let constructor = if declaration.constructor == "_" { + String::new() + } else { + declaration.constructor.clone() + }; + self.push(place, constructor)?; + place.child("") + } else { + place.deeper() + }; + self.decode_items( + parser, + &declaration.items, + &mut inner, + &declaration.constructor, + items_place, + )?; + Ok(None) + } + + /// Decodes the items of one constructor at `place.depth`. + fn decode_items( + &mut self, + parser: &mut CellParser<'_>, + items: &'s [Item], + env: &mut Env<'s>, + constructor: &str, + place: Place<'_>, + ) -> Outcome<()> { + for item in items { + self.step()?; + match item { + Item::Field(field) => { + if let Some(condition) = &field.condition + && !condition_holds(condition, env)? + { + continue; + } + let field_place = Place { + name: &field.name, + ..place + }; + let value = self.decode_type(parser, &field.ty, env, field_place)?; + if let Some(value) = value + && field.name != "_" + { + env.nats.push((field.name.as_str(), value)); + } + } + Item::Constraint(constraint) => { + if !constraint_holds(constraint, env)? { + return Err(failure( + TonConnectSignDataCellFailure::ConstraintViolated, + format!("constraint failed in {:?}", echo(constructor)), + )); + } + } + Item::Inline(items) => { + if place.level >= MAX_DECODE_DEPTH { + return Err(limit("cell nesting is deeper than 32")); + } + let child = next_ref(parser)?; + let mut child_parser = child.parser(); + self.decode_items(&mut child_parser, items, env, constructor, place.deeper())?; + ensure_empty(&mut child_parser)?; + } + } + } + Ok(()) + } + + fn decode_sized( + &mut self, + parser: &mut CellParser<'_>, + kind: SizedKind, + width: u64, + place: Place<'_>, + ) -> Outcome> { + check_width(kind, width, false)?; + match kind { + SizedKind::Uint | SizedKind::NatBits => { + let (text, value) = read_uint(parser, width_of(width)?)?; + self.push(place, text)?; + Ok(value) + } + SizedKind::Int => { + let text = read_int(parser, width_of(width)?)?; + self.push(place, text)?; + Ok(None) + } + SizedKind::Bits => { + let text = read_bit_string(parser, width_of(width)?)?; + self.push(place, text)?; + Ok(None) + } + SizedKind::NatLess | SizedKind::NatLessEqual => { + let bound = if kind == SizedKind::NatLess { + width.saturating_sub(1) + } else { + width + }; + let value = read_u64(parser, bits_for(bound)?)?; + if value > bound { + return Err(failure( + TonConnectSignDataCellFailure::ConstraintViolated, + format!("{value} is above the bound {bound}"), + )); + } + self.push(place, value.to_string())?; + Ok(Some(value)) + } + } + } + + fn decode_builtin( + &mut self, + parser: &mut CellParser<'_>, + type_name: &str, + args: &'s [Arg], + env: &Env<'s>, + place: Place<'_>, + ) -> Outcome> { + match (type_name, args) { + ("Bool", []) => { + let value = if read_u64(parser, 1)? == 1 { + "true" + } else { + "false" + }; + self.push(place, value.to_owned())?; + Ok(None) + } + ("Maybe", [Arg::Type(inner)]) => { + if read_u64(parser, 1)? == 1 { + let _ = self.decode_type(parser, inner, env, place.deeper())?; + } else { + self.push(place, "none".to_owned())?; + } + Ok(None) + } + ("Either", [Arg::Type(left), Arg::Type(right)]) => { + let inner = if read_u64(parser, 1)? == 1 { + right + } else { + left + }; + let _ = self.decode_type(parser, inner, env, place.deeper())?; + Ok(None) + } + ("Both", [Arg::Type(first), Arg::Type(second)]) => { + self.push(place, "pair".to_owned())?; + let _ = self.decode_type(parser, first, env, place.child("first"))?; + let _ = self.decode_type(parser, second, env, place.child("second"))?; + Ok(None) + } + ("VarUInteger", [Arg::Nat(bytes)]) => { + self.decode_var_integer(parser, env.eval(bytes)?, false, place) + } + ("VarInteger", [Arg::Nat(bytes)]) => { + self.decode_var_integer(parser, env.eval(bytes)?, true, place) + } + ("Coins" | "Grams", []) => self.decode_var_integer(parser, 16, false, place), + ("MsgAddress", []) => self.decode_address(parser, AddressKinds::Any, place), + ("MsgAddressInt", []) => self.decode_address(parser, AddressKinds::Internal, place), + ("MsgAddressExt", []) => self.decode_address(parser, AddressKinds::External, place), + ("Cell" | "Any", []) => { + let rest = parser + .read_remaining() + .map_err(|_| truncated("cell ends early"))?; + self.check_cell_value(&rest, place.name.len())?; + let bytes = BoC::new(rest) + .to_bytes(false) + .map_err(|_| invalid_cell("cell cannot be serialized"))?; + let length = bytes + .len() + .checked_mul(2) + .and_then(|length| length.checked_add(place.name.len())) + .ok_or_else(|| limit("result is longer than 32768 bytes"))?; + self.ensure_room(length)?; + self.push(place, hex(&bytes))?; + Ok(None) + } + _ => Err(unsupported(format!( + "unsupported type {:?}", + echo(type_name) + ))), + } + } + + /// Bounds a `Cell`/`Any` value before it is serialized. + /// + /// `BoC` serialization is quadratic in the cell count for some DAG shapes, + /// so this linear walk over the distinct cells (by their memoized hashes) + /// charges one step per cell and refuses the value once it has more than + /// `MAX_CELL_VALUE_CELLS` cells or its estimated hex no longer fits the + /// output. The estimate is 2 descriptor bytes, the data bytes and 4 bytes + /// per reference for every distinct cell. + fn check_cell_value(&mut self, value: &TonCell, name_bytes: usize) -> Outcome<()> { + let mut seen = HashSet::new(); + let mut pending = vec![value]; + let mut bytes = 0_usize; + while let Some(cell) = pending.pop() { + let hash = cell + .hash() + .map_err(|_| invalid_cell("cell cannot be hashed"))?; + if !seen.insert(hash) { + continue; + } + self.step()?; + if seen.len() > MAX_CELL_VALUE_CELLS { + return Err(limit("cell value has more than 256 cells")); + } + let refs = cell.refs(); + bytes = refs + .len() + .checked_mul(4) + .and_then(|refs| refs.checked_add(2)) + .and_then(|size| size.checked_add(cell.data_len_bits().div_ceil(8))) + .and_then(|size| size.checked_add(bytes)) + .ok_or_else(|| limit("result is longer than 32768 bytes"))?; + let length = bytes + .checked_mul(2) + .and_then(|length| length.checked_add(name_bytes)) + .ok_or_else(|| limit("result is longer than 32768 bytes"))?; + self.ensure_room(length)?; + pending.extend(refs); + } + Ok(()) + } + + /// `VarUInteger n` / `VarInteger n`: a `#< n` byte length, then that many bytes. + fn decode_var_integer( + &mut self, + parser: &mut CellParser<'_>, + bytes: u64, + signed: bool, + place: Place<'_>, + ) -> Outcome> { + if !(1..=MAX_VAR_INTEGER_BYTES).contains(&bytes) { + return Err(unsupported(format!( + "unsupported variable integer size {bytes}" + ))); + } + let length = read_u64(parser, bits_for(bytes.saturating_sub(1))?)?; + let width = length + .checked_mul(8) + .ok_or_else(|| unsupported("arithmetic overflow"))?; + let width = width_of(width)?; + if signed { + let text = if width == 0 { + "0".to_owned() + } else { + read_int(parser, width)? + }; + self.push(place, text)?; + Ok(None) + } else { + let (text, value) = read_uint(parser, width)?; + self.push(place, text)?; + Ok(value) + } + } + + fn decode_address( + &mut self, + parser: &mut CellParser<'_>, + kinds: AddressKinds, + place: Place<'_>, + ) -> Outcome> { + let external = matches!(kinds, AddressKinds::Any | AddressKinds::External); + let internal = matches!(kinds, AddressKinds::Any | AddressKinds::Internal); + let text = match read_u64(parser, 2)? { + 0b00 if external => "addr_none".to_owned(), + 0b01 if external => { + let length = read_u64(parser, 9)?; + let bits = read_bit_string(parser, width_of(length)?)?; + format!("addr_extern:{bits}") + } + 0b10 if internal => { + if read_u64(parser, 1)? == 1 { + return Err(unsupported("anycast addresses")); + } + let workchain = read_u64(parser, 8)?; + let workchain = u8::try_from(workchain) + .map(|byte| i8::from_be_bytes([byte])) + .map_err(|_| invalid_cell("workchain does not fit 8 bits"))?; + require_bits(parser, 256)?; + let hash = parser + .read_bits(256) + .map_err(|_| truncated("cell ends early"))?; + let hash = <[u8; 32]>::try_from(hash.as_slice()) + .map_err(|_| truncated("cell ends early"))?; + FriendlyAddress::from_raw( + RawAccountAddress::new(i32::from(workchain), hash), + false, + self.testnet, + ) + .map_or_else( + |_| format!("{workchain}:{}", hex(&hash)), + |address| address.as_str().to_owned(), + ) + } + 0b11 if internal => return Err(unsupported("addr_var addresses")), + _ => { + return Err(failure( + TonConnectSignDataCellFailure::TagMismatch, + "address kind does not match its type", + )); + } + }; + self.push(place, text)?; + Ok(None) + } +} + +fn condition_holds(condition: &Condition, env: &Env<'_>) -> Outcome { + let flag = env + .nat(&condition.flag) + .ok_or_else(|| unsupported(format!("{:?} is not a bound number", echo(&condition.flag))))?; + Ok(match condition.bit { + None => flag != 0, + Some(bit) => flag.checked_shr(bit).unwrap_or(0) & 1 == 1, + }) +} + +fn constraint_holds(constraint: &Constraint, env: &Env<'_>) -> Outcome { + let left = env.eval(&constraint.left)?; + let right = env.eval(&constraint.right)?; + Ok(match constraint.relation { + Relation::Equal => left == right, + Relation::Less => left < right, + Relation::LessEqual => left <= right, + Relation::Greater => left > right, + Relation::GreaterEqual => left >= right, + }) +} + +/// A runtime width as `usize`; a width no cell can hold reads as truncation. +fn width_of(width: u64) -> Outcome { + usize::try_from(width).map_err(|_| truncated("cell ends early")) +} + +/// Bits needed to write every value up to `value`. +fn bits_for(value: u64) -> Outcome { + let bits = u64::BITS.saturating_sub(value.leading_zeros()); + usize::try_from(bits).map_err(|_| unsupported("unsupported width")) +} + +fn bits_left(parser: &mut CellParser<'_>) -> Outcome { + parser + .data_bits_left() + .map_err(|_| invalid_cell("cell cannot be read")) +} + +/// Fails with `TruncatedCell` unless `width` bits remain; every read calls it first. +fn require_bits(parser: &mut CellParser<'_>, width: usize) -> Outcome<()> { + let left = bits_left(parser)?; + if width > left { + return Err(truncated(format!( + "cell ends early: {width} bits needed, {left} left" + ))); + } + Ok(()) +} + +/// Reads at most 64 bits as an unsigned number. +fn read_u64(parser: &mut CellParser<'_>, width: usize) -> Outcome { + if width > 64 { + return Err(unsupported("unsupported width")); + } + require_bits(parser, width)?; + parser + .read_num::(width) + .map_err(|_| truncated("cell ends early")) +} + +/// Reads an unsigned number of up to 256 bits as decimal, with its value when it fits `u64`. +fn read_uint(parser: &mut CellParser<'_>, width: usize) -> Outcome<(String, Option)> { + if width <= 64 { + let value = read_u64(parser, width)?; + return Ok((value.to_string(), Some(value))); + } + require_bits(parser, width)?; + let value = parser + .read_num::(width) + .map_err(|_| truncated("cell ends early"))?; + Ok((value.to_string(), u64::try_from(&value).ok())) +} + +/// Reads a two's-complement number of 1 to 257 bits as decimal. +fn read_int(parser: &mut CellParser<'_>, width: usize) -> Outcome { + require_bits(parser, width)?; + let value = parser + .read_num::(width) + .map_err(|_| truncated("cell ends early"))?; + Ok(value.to_string()) +} + +fn read_bit_string(parser: &mut CellParser<'_>, width: usize) -> Outcome { + require_bits(parser, width)?; + let bytes = parser + .read_bits(width) + .map_err(|_| truncated("cell ends early"))?; + Ok(hex_bits(&bytes, width)) +} + +/// The next reference, refused when missing or exotic. +fn next_ref(parser: &mut CellParser<'_>) -> Outcome { + if parser.refs_left() == 0 { + return Err(truncated("cell ends before a reference")); + } + let child = parser + .read_next_ref() + .map_err(|_| truncated("cell ends before a reference"))? + .clone(); + if child.cell_type().is_exotic() { + return Err(invalid_cell("exotic cells are not decodable")); + } + Ok(child) +} + +fn ensure_empty(parser: &mut CellParser<'_>) -> Outcome<()> { + let bits = bits_left(parser)?; + let refs = parser.refs_left(); + if bits == 0 && refs == 0 { + return Ok(()); + } + Err(failure( + TonConnectSignDataCellFailure::TrailingData, + format!("{bits} bits and {refs} refs left"), + )) +} + +fn hex_digit(nibble: u8) -> char { + char::from_digit(u32::from(nibble), 16).unwrap_or('0') +} + +/// Lowercase hex of whole bytes. +fn hex(bytes: &[u8]) -> String { + let mut text = String::with_capacity(bytes.len().saturating_mul(2)); + for byte in bytes { + text.push(hex_digit(byte.wrapping_shr(4))); + text.push(hex_digit(byte & 0x0f)); + } + text +} + +/// Hex of the first `len` bits of `bytes` (zero-padded as `read_bits` returns them). +/// +/// A length that is not a multiple of 4 uses the Fift form: the last nibble +/// carries a completion `1` bit after the data bits, followed by `_`. +fn hex_bits(bytes: &[u8], len: usize) -> String { + let mut nibbles = bytes + .iter() + .flat_map(|byte| [byte.wrapping_shr(4), byte & 0x0f]) + .collect::>(); + nibbles.truncate(len.div_ceil(4)); + let completion = match len & 3 { + 1 => 0b0100, + 2 => 0b0010, + 3 => 0b0001, + _ => 0, + }; + if completion != 0 + && let Some(last) = nibbles.last_mut() + { + *last |= completion; + } + let mut text = nibbles.into_iter().map(hex_digit).collect::(); + if completion != 0 { + text.push('_'); + } + text +} + +#[cfg(test)] +mod tests { + use std::panic::catch_unwind; + use std::str::FromStr as _; + use std::time::{Duration, Instant}; + + use base64::{Engine as _, engine::general_purpose::STANDARD}; + use ton::ton_core::cell::CellBuilder; + use ton::ton_core::errors::TonCoreError; + use ton::ton_core::types::TonAddress; + + use super::*; + use TonConnectSignDataCellFailure as F; + + const DEMO_SCHEMA: &str = "message#_ len:uint7 {len <= 127} text:(bits len * 8) = Message;"; + /// The demo dApp's cell exactly as `@ton/core` `toBoc()` sends it (with CRC-32C). + const DEMO_MESSAGE_CELL: &str = "te6cckEBAQEAFwAAKSioyuboQNrK5ubCzspA0txAxsrY2Whv0fw="; + const DEMO_TEXT: &str = "Test message in cell"; + + const WALLET_SCHEMA: &str = "wallet_body#_ signature:bits512 subwallet_id:uint32 valid_until:uint32 seqno:uint32 = WalletBody;"; + const SIGNATURE: &str = "2bfcd9ad9768087dbbb5e70623edb351842a0dd039ef3a2521e62f081c8dc66fd5a0c1ad403a5660a102230652ce7bf07f08095d26786dc3152aa0849008910c"; + + const ORDER_SCHEMA: &str = "// comment +memo#_ text:(bits 40) urgent:Bool = Memo; +point$_ x:int8 y:(## 4) = Point; +order#1234abcd query_id:uint64 amount:Coins to:MsgAddress at:Point memo:^Memo extra:(Maybe ^Cell) = Order;"; + + const NON_BOUNCEABLE: &str = "UQCKWpx7cNMpvmcN5ObM5lLUZHZRFKqYA4xmw9jOry0ZsAKJ"; + const DESTINATION_RAW: &str = + "0:8a5a9c7b70d329be670de4e6cce652d464765114aa98038c66c3d8ceaf2d19b0"; + + const PROMPT: Duration = Duration::from_secs(2); + + fn cell(build: impl FnOnce(&mut CellBuilder) -> Result<(), TonCoreError>) -> TonCell { + let mut builder = TonCell::builder(); + build(&mut builder).expect("cell builds"); + builder.build().expect("cell builds") + } + + fn boc(cell: TonCell) -> String { + STANDARD.encode(BoC::new(cell).to_bytes(false).expect("BoC serializes")) + } + + fn hex_of(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() + } + + fn decoded(schema: &str, cell: &str, testnet: bool) -> Vec<(u32, String, String)> { + match decode_sign_data_cell(schema, cell, testnet) { + TonConnectSignDataCellDecoding::Decoded { fields } => fields + .into_iter() + .map(|field| (field.depth, field.name, field.value)) + .collect(), + TonConnectSignDataCellDecoding::NotDecodable { failure, detail } => { + panic!("not decodable: {failure:?} {detail}") + } + } + } + + fn entries(expected: &[(u32, &str, &str)]) -> Vec<(u32, String, String)> { + expected + .iter() + .map(|(depth, name, value)| (*depth, (*name).to_owned(), (*value).to_owned())) + .collect() + } + + /// The failure of a not-decodable cell; a field list fails the test. + fn failure_of(schema: &str, cell: &str) -> (F, String) { + match decode_sign_data_cell(schema, cell, false) { + TonConnectSignDataCellDecoding::NotDecodable { failure, detail } => (failure, detail), + TonConnectSignDataCellDecoding::Decoded { fields } => { + panic!("unexpectedly decoded: {fields:?}") + } + } + } + + fn failure(schema: &str, cell: &str) -> F { + failure_of(schema, cell).0 + } + + /// Asserts a failure category and that the call returned within `PROMPT`. + fn prompt_failure(schema: &str, cell: &str) -> (F, String) { + let start = Instant::now(); + let result = failure_of(schema, cell); + assert!(start.elapsed() < PROMPT, "took {:?}", start.elapsed()); + result + } + + fn demo_cell(len: u8, text: &[u8]) -> TonCell { + cell(|builder| { + builder.write_num(&len, 7)?; + builder.write_bits(text, text.len() * 8) + }) + } + + fn demo_boc() -> String { + boc(demo_cell(20, DEMO_TEXT.as_bytes())) + } + + fn signature_bytes() -> Vec { + SIGNATURE + .as_bytes() + .chunks(2) + .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()) + .collect() + } + + fn wallet_cell(with_seqno: bool) -> TonCell { + let signature = signature_bytes(); + cell(|builder| { + builder.write_bits(&signature, 512)?; + builder.write_num(&698_983_191_u32, 32)?; + builder.write_num(&1_740_048_389_u32, 32)?; + if with_seqno { + builder.write_num(&123_u32, 32)?; + } + Ok(()) + }) + } + + fn destination_hash() -> [u8; 32] { + *TonAddress::from_str(DESTINATION_RAW) + .unwrap() + .hash + .as_slice_sized() + } + + fn write_std_address(builder: &mut CellBuilder, anycast: bool) -> Result<(), TonCoreError> { + builder.write_num(&0b10_u8, 2)?; + builder.write_bit(anycast)?; + builder.write_num(&0_u8, 8)?; + builder.write_bits(destination_hash(), 256) + } + + fn memo_cell(extra_bit: bool) -> TonCell { + cell(|builder| { + builder.write_bits(b"hello", 40)?; + builder.write_bit(true)?; + if extra_bit { + builder.write_bit(false)?; + } + Ok(()) + }) + } + + /// The order cell of `ORDER_SCHEMA`; `memo` is its reference (if any), `extra` the `Maybe ^Cell`. + fn order_cell(memo: Option, extra: Option) -> TonCell { + cell(|builder| { + builder.write_num(&0x1234_abcd_u32, 32)?; + builder.write_num(&7_u64, 64)?; + builder.write_num(&4_u8, 4)?; + builder.write_num(&1_000_000_000_u32, 32)?; + write_std_address(builder, false)?; + builder.write_num(&(-5_i8), 8)?; + builder.write_num(&9_u8, 4)?; + if let Some(memo) = memo { + builder.write_ref(memo)?; + } + builder.write_bit(extra.is_some())?; + if let Some(extra) = extra { + builder.write_ref(extra)?; + } + Ok(()) + }) + } + + fn expected_order(address: &str, extra: &str) -> Vec<(u32, String, String)> { + entries(&[ + (0, "query_id", "7"), + (0, "amount", "1000000000"), + (0, "to", address), + (0, "at", "point"), + (1, "x", "-5"), + (1, "y", "9"), + (0, "memo", "memo"), + (1, "text", "68656c6c6f"), + (1, "urgent", "true"), + (0, "extra", extra), + ]) + } + + #[test] + fn demo_message_decodes_into_len_and_text() { + let text_hex = hex_of(DEMO_TEXT.as_bytes()); + assert_eq!(text_hex, "54657374206d65737361676520696e2063656c6c"); + let expected = entries(&[(0, "len", "20"), (0, "text", &text_hex)]); + let built = demo_cell(20, DEMO_TEXT.as_bytes()); + assert_eq!( + STANDARD.encode(BoC::new(built.clone()).to_bytes(true).unwrap()), + DEMO_MESSAGE_CELL + ); + assert_eq!(decoded(DEMO_SCHEMA, DEMO_MESSAGE_CELL, false), expected); + assert_eq!(decoded(DEMO_SCHEMA, &boc(built), true), expected); + } + + #[test] + fn wallet_style_body_decodes_into_its_four_fields() { + assert_eq!(hex_of(&signature_bytes()), SIGNATURE); + assert_eq!( + decoded(WALLET_SCHEMA, &boc(wallet_cell(true)), false), + entries(&[ + (0, "signature", SIGNATURE), + (0, "subwallet_id", "698983191"), + (0, "valid_until", "1740048389"), + (0, "seqno", "123"), + ]) + ); + // Control: the same cell under a mismatching schema is not decodable. + assert_eq!( + failure(DEMO_SCHEMA, &boc(wallet_cell(true))), + F::TrailingData + ); + } + + #[test] + fn referenced_cell_and_declared_sub_type_decode_as_nested_fields() { + let address = TonAddress::from_str(DESTINATION_RAW).unwrap(); + let mainnet = address.to_base64(true, false, true); + let testnet = address.to_base64(false, false, true); + assert_eq!(mainnet, NON_BOUNCEABLE); + assert!(testnet.starts_with("0Q"), "{testnet}"); + assert_ne!(mainnet, testnet); + + let order = boc(order_cell(Some(memo_cell(false)), None)); + assert_eq!( + decoded(ORDER_SCHEMA, &order, false), + expected_order(NON_BOUNCEABLE, "none") + ); + assert_eq!( + decoded(ORDER_SCHEMA, &order, true), + expected_order(&testnet, "none") + ); + + let extra = cell(|builder| builder.write_num(&0xff_u8, 8)); + let extra_hex = hex_of(&BoC::new(extra.clone()).to_bytes(false).unwrap()); + let order = boc(order_cell(Some(memo_cell(false)), Some(extra))); + assert_eq!( + decoded(ORDER_SCHEMA, &order, false), + expected_order(NON_BOUNCEABLE, &extra_hex) + ); + // Control: the same cell under a mismatching schema is not decodable. + assert_eq!(failure(WALLET_SCHEMA, &order), F::TruncatedCell); + } + + #[test] + fn parameterized_and_standard_types() { + let schema = " + opt_none$0 {X:Type} = Opt X; + opt_some$1 {X:Type} value:X = Opt X; + blob$_ {n:#} data:(bits n) = Blob n; + yes$1 = YN; no$0 = YN; + t#_ a:(Opt uint8) b:(Opt uint8) c:(Blob 16) e:(Either uint8 ^Cell) + f:(Either uint8 ^Cell) flag:(## 1) x:flag?uint8 flag2:(## 1) y:flag2?uint8 + mode:(## 8) z:(mode . 2)?uint8 w:(mode . 1)?uint8 + big:(VarUInteger 32) small:(VarInteger 2) none:MsgAddress ext:MsgAddressExt + odd:(bits 5) pair:(Both uint8 Bool) yn:YN nyn:YN lt:(#< 5) le:(#<= 5) = T;"; + let referenced = cell(|builder| builder.write_num(&0xab_u8, 8)); + let referenced_hex = hex_of(&BoC::new(referenced.clone()).to_bytes(false).unwrap()); + let big = BigUint::from(u64::MAX) + 1_u32; + let built = cell(|builder| { + builder.write_bit(false)?; // a: opt_none + builder.write_bit(true)?; // b: opt_some + builder.write_num(&42_u8, 8)?; + builder.write_num(&0xbeef_u16, 16)?; // c + builder.write_bit(false)?; // e: left + builder.write_num(&7_u8, 8)?; + builder.write_bit(true)?; // f: right + builder.write_ref(referenced)?; + builder.write_num(&0_u8, 1)?; // flag + builder.write_num(&1_u8, 1)?; // flag2 + builder.write_num(&9_u8, 8)?; // y + builder.write_num(&4_u8, 8)?; // mode: bit 2 set, bit 1 clear + builder.write_num(&10_u8, 8)?; // z + builder.write_num(&9_u8, 5)?; // big: 9 bytes + builder.write_num(&big, 72)?; + builder.write_num(&1_u8, 1)?; // small: 1 byte + builder.write_num(&(-3_i8), 8)?; + builder.write_num(&0_u8, 2)?; // none: addr_none + builder.write_num(&1_u8, 2)?; // ext: addr_extern + builder.write_num(&12_u16, 9)?; + builder.write_num(&0xabc_u16, 12)?; + builder.write_num(&0b10101_u8, 5)?; // odd + builder.write_num(&1_u8, 8)?; // pair.first + builder.write_bit(true)?; // pair.second + builder.write_bit(true)?; // yn + builder.write_bit(false)?; // nyn + builder.write_num(&4_u8, 3)?; // lt: #< 5 is 3 bits + builder.write_num(&5_u8, 3)?; // le: #<= 5 is 3 bits + Ok(()) + }); + assert_eq!( + decoded(schema, &boc(built), false), + entries(&[ + (0, "a", "opt_none"), + (0, "b", "opt_some"), + (1, "value", "42"), + (0, "c", "blob"), + (1, "data", "beef"), + (0, "e", "7"), + (0, "f", &referenced_hex), + (0, "flag", "0"), + (0, "flag2", "1"), + (0, "y", "9"), + (0, "mode", "4"), + (0, "z", "10"), + (0, "big", "18446744073709551616"), + (0, "small", "-3"), + (0, "none", "addr_none"), + (0, "ext", "addr_extern:abc"), + (0, "odd", "ac_"), + (0, "pair", "pair"), + (1, "first", "1"), + (1, "second", "true"), + (0, "yn", "yes"), + (0, "nyn", "no"), + (0, "lt", "4"), + (0, "le", "5"), + ]) + ); + } + + #[test] + fn bit_strings_use_hex_or_the_fift_form() { + assert_eq!(hex_bits(&[], 0), ""); + assert_eq!(hex_bits(&[0b1010_1000], 5), "ac_"); + assert_eq!(hex_bits(&[0b1000_0000], 1), "c_"); + assert_eq!(hex_bits(&[0b1100_0000], 2), "e_"); + assert_eq!(hex_bits(&[0b1110_0000], 3), "f_"); + assert_eq!(hex_bits(&[0xab, 0xc0], 12), "abc"); + assert_eq!(hex_bits(&[0xab], 8), "ab"); + } + + #[test] + fn unsupported_constructs_are_not_decodable() { + let one_byte = boc(cell(|builder| builder.write_num(&1_u8, 8))); + for schema in [ + "message len:uint7 = Message;", + "message# len:uint7 = Message;", + "d#_ m:(HashmapE 32 uint8) = D;", + "t#_ x:(3 * uint8) = T;", + "t#_ {n:#} x:(n * uint8) = T;", + "a#_ {n:#} x:(## n) = A ~n;", + "a#_ x:(## 8) {~x = 1} = A;", + "!a#_ x:uint8 = A;", + "a#_ x:[ y:uint8 ] = A;", + "a#_ {n:#} x:(## n) = A n;", + "a#_ x:uint300 = A;", + "a#_ x:int258 = A;", + "a#_ x:bits1024 = A;", + "a#_ x:(## 65) = A;", + "a#_ x:int0 = A;", + "a#_ x:y?uint8 = A;", + "a$_ = A; b$_ = A; c#_ x:A y:uint8 = C;", + ] { + assert_eq!(failure(schema, &one_byte), F::UnsupportedSchema, "{schema}"); + } + let address = |anycast: bool, var: bool| { + boc(cell(|builder| { + if var { + builder.write_num(&0b11_u8, 2)?; + builder.write_bit(false)?; + builder.write_num(&8_u16, 9)?; + builder.write_num(&0_u32, 32)?; + builder.write_num(&0_u8, 8) + } else { + write_std_address(builder, anycast) + } + })) + }; + let schema = "a#_ to:MsgAddress = A;"; + assert_eq!(failure(schema, &address(true, false)), F::UnsupportedSchema); + assert_eq!(failure(schema, &address(false, true)), F::UnsupportedSchema); + assert_eq!( + decoded(schema, &address(false, false), false), + entries(&[(0, "to", NON_BOUNCEABLE)]) + ); + } + + #[test] + fn tag_mismatches_are_not_decodable() { + let two_bytes = boc(cell(|builder| builder.write_num(&0x0205_u16, 16))); + assert_eq!(failure("a#01 x:uint8 = A;", &two_bytes), F::TagMismatch); + assert_eq!( + decoded("a#02 x:uint8 = A;", &two_bytes, false), + entries(&[(0, "x", "5")]) + ); + let two_bits = boc(cell(|builder| builder.write_num(&0b01_u8, 2))); + let schema = "a$11 = T; b$10 = T; w#_ t:T = W;"; + assert_eq!(failure(schema, &two_bits), F::TagMismatch); + let matching = boc(cell(|builder| builder.write_num(&0b10_u8, 2))); + assert_eq!(decoded(schema, &matching, false), entries(&[(0, "t", "b")])); + // A completion tag: `#a_` (`1010`) is the two bits `10`. + let completion = boc(cell(|builder| builder.write_num(&0b10_u8, 2))); + assert_eq!(decoded("x#a_ = X;", &completion, false), entries(&[])); + // An internal address type refuses `addr_none`. + let none = boc(cell(|builder| builder.write_num(&0_u8, 2))); + assert_eq!(failure("a#_ to:MsgAddressInt = A;", &none), F::TagMismatch); + } + + #[test] + fn the_root_is_the_last_declaration() { + let schema = "approve#01 amount:uint8 = Op; revoke#02 amount:uint8 = Op;"; + let approve = boc(cell(|builder| builder.write_num(&0x0105_u16, 16))); + let revoke = boc(cell(|builder| builder.write_num(&0x0205_u16, 16))); + assert_eq!( + decoded(schema, &revoke, false), + entries(&[(0, "amount", "5")]) + ); + assert_eq!(failure(schema, &approve), F::TagMismatch); + let short = boc(cell(|builder| builder.write_num(&0b0010_u8, 4))); + assert_eq!(failure(schema, &short), F::TruncatedCell); + + // Control: every constructor of the type still serves a nested use. + let nested = format!("{schema} w#_ op:Op = W;"); + assert_eq!( + decoded(&nested, &approve, false), + entries(&[(0, "op", "approve"), (1, "amount", "5")]) + ); + assert_eq!( + decoded(&nested, &revoke, false), + entries(&[(0, "op", "revoke"), (1, "amount", "5")]) + ); + } + + #[test] + fn violated_constraints_are_not_decodable() { + let demo = demo_boc(); + let strict = "message#_ len:uint7 {len <= 16} text:(bits len * 8) = Message;"; + assert_eq!(failure(strict, &demo), F::ConstraintViolated); + let larger = "message#_ len:uint7 {len >= 21} text:(bits len * 8) = Message;"; + assert_eq!(failure(larger, &demo), F::ConstraintViolated); + assert_eq!(decoded(DEMO_SCHEMA, &demo, false).len(), 2); + let bounded = boc(cell(|builder| builder.write_num(&5_u8, 3))); + assert_eq!( + failure("a#_ x:(#< 5) = A;", &bounded), + F::ConstraintViolated + ); + } + + #[test] + fn trailing_data_is_not_decodable() { + let extra_bit = boc(cell(|builder| { + builder.write_num(&20_u8, 7)?; + builder.write_bits(DEMO_TEXT.as_bytes(), 160)?; + builder.write_bit(false) + })); + assert_eq!(failure(DEMO_SCHEMA, &extra_bit), F::TrailingData); + let extra_ref = boc(cell(|builder| { + builder.write_num(&20_u8, 7)?; + builder.write_bits(DEMO_TEXT.as_bytes(), 160)?; + builder.write_ref(TonCell::empty().clone()) + })); + assert_eq!(failure(DEMO_SCHEMA, &extra_ref), F::TrailingData); + let child_extra = boc(order_cell(Some(memo_cell(true)), None)); + assert_eq!(failure(ORDER_SCHEMA, &child_extra), F::TrailingData); + } + + #[test] + fn truncated_cells_are_not_decodable() { + let short_text = boc(demo_cell(20, &DEMO_TEXT.as_bytes()[..19])); + assert_eq!(failure(DEMO_SCHEMA, &short_text), F::TruncatedCell); + assert_eq!( + failure(WALLET_SCHEMA, &boc(wallet_cell(false))), + F::TruncatedCell + ); + let no_memo = boc(order_cell(None, None)); + assert_eq!(failure(ORDER_SCHEMA, &no_memo), F::TruncatedCell); + } + + #[test] + fn schemas_that_fail_to_parse_are_not_decodable() { + let cell = demo_boc(); + for schema in [ + "", + " // only a comment", + "message#_ len:uint7 {len <= 127 text:(bits len * 8) = Message;", + "message#_ len:uint7", + "/* unterminated", + "a#_ x:uint8 = A; @", + "a#_ x:(uint8 = A;", + "a#_ x:uint8 = ;", + "a$ x:uint8 = A;", + ] { + assert_eq!(failure(schema, &cell), F::InvalidSchema, "{schema:?}"); + } + } + + #[test] + fn invalid_cells_are_not_decodable() { + assert_eq!(failure(DEMO_SCHEMA, "not a boc"), F::InvalidCell); + let root = demo_cell(20, DEMO_TEXT.as_bytes()); + let two_roots = STANDARD.encode( + BoC::from_roots([root, TonCell::empty().clone()]) + .to_bytes(false) + .unwrap(), + ); + assert_eq!(failure(DEMO_SCHEMA, &two_roots), F::InvalidCell); + } + + #[test] + fn no_progress_recursion_is_bounded() { + let one_byte = boc(cell(|builder| builder.write_num(&1_u8, 8))); + let (kind, _) = prompt_failure("a$_ x:A = A;", &one_byte); + assert_eq!(kind, F::LimitExceeded); + } + + /// A list of `length` cells, each `v:uint8` then `Maybe ^R`. + fn chain(length: usize) -> String { + let mut next: Option = None; + for index in 0..length { + let previous = next.take(); + next = Some(cell(|builder| { + builder.write_num(&u8::try_from(index % 256).unwrap(), 8)?; + builder.write_bit(previous.is_some())?; + if let Some(previous) = previous { + builder.write_ref(previous)?; + } + Ok(()) + })); + } + boc(next.unwrap()) + } + + #[test] + fn deep_reference_chains_are_bounded() { + let schema = "r$_ v:uint8 next:(Maybe ^R) = R;"; + let (kind, detail) = prompt_failure(schema, &chain(64)); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("nesting"), "{detail}"); + + let fields = decoded(schema, &chain(5), false); + let depths = fields + .iter() + .filter(|(_, name, _)| name == "next") + .map(|(depth, _, _)| *depth) + .collect::>(); + assert_eq!(depths, [0, 1, 2, 3, 4]); + + // Each list level costs three decode levels (`Maybe`, `^`, `R`), so + // 11 cells are the longest chain within `MAX_DECODE_DEPTH`. + assert!(matches!( + decode_sign_data_cell(schema, &chain(11), false), + TonConnectSignDataCellDecoding::Decoded { .. } + )); + assert_eq!(failure(schema, &chain(12)), F::LimitExceeded); + } + + #[test] + fn shared_reference_fan_out_is_bounded() { + let schema = "n$_ a:(Maybe ^N) b:(Maybe ^N) c:(Maybe ^N) d:(Maybe ^N) = N;"; + let mut level = cell(|builder| builder.write_num(&0_u8, 4)); + for _ in 0..6 { + let child = level.clone(); + level = cell(|builder| { + builder.write_num(&0b1111_u8, 4)?; + for _ in 0..4 { + builder.write_ref(child.clone())?; + } + Ok(()) + }); + } + let (kind, _) = prompt_failure(schema, &boc(level)); + assert_eq!(kind, F::LimitExceeded); + } + + #[test] + fn huge_sizes_are_bounded() { + let all_ones = boc(cell(|builder| builder.write_num(&u64::MAX, 64))); + let (kind, _) = prompt_failure("x#_ len:(## 64) data:(bits len) = X;", &all_ones); + assert_eq!(kind, F::TruncatedCell); + let (kind, _) = prompt_failure("x#_ data:(bits 99999999999999999999) = X;", &all_ones); + assert_eq!(kind, F::LimitExceeded); + let overflow = boc(cell(|builder| { + builder.write_num(&(1_u64 << 40), 64)?; + builder.write_num(&(1_u64 << 40), 64) + })); + let (kind, _) = prompt_failure("x#_ a:(## 64) b:(## 64) data:(bits a * b) = X;", &overflow); + assert_eq!(kind, F::UnsupportedSchema); + let huge_uint = boc(cell(|builder| { + builder.write_num(&255_u8, 8)?; + builder.write_num(&0_u8, 8) + })); + let (kind, _) = prompt_failure("x#_ n:uint8 v:(uint n * 2) = X;", &huge_uint); + assert_eq!(kind, F::UnsupportedSchema); + } + + /// A one-root `BoC` of `cells` (data bytes, reference indices) listed parents first. + fn raw_boc(cells: &[(Vec, Vec)]) -> String { + let mut body = Vec::new(); + for (data, refs) in cells { + body.push(u8::try_from(refs.len()).unwrap()); + body.push(u8::try_from(data.len() * 2).unwrap()); + body.extend_from_slice(data); + for index in refs { + body.extend_from_slice(&u16::try_from(*index).unwrap().to_be_bytes()); + } + } + let mut bytes = vec![0xb5, 0xee, 0x9c, 0x72, 0x02, 0x04]; + bytes.extend_from_slice(&u16::try_from(cells.len()).unwrap().to_be_bytes()); + bytes.extend_from_slice(&[0, 1, 0, 0]); + bytes.extend_from_slice(&u32::try_from(body.len()).unwrap().to_be_bytes()); + bytes.extend_from_slice(&[0, 0]); + bytes.extend_from_slice(&body); + STANDARD.encode(bytes) + } + + /// A DAG of `2 * length + 1` cells whose breadth-first order is not + /// topological: root -> [d1, c1], c_i -> [c_i+1, d_i], d_i -> [d_i+1]. + /// `wrapped` puts it behind one reference of an empty root cell. + fn non_topological_dag(length: usize, wrapped: bool) -> String { + let offset = usize::from(wrapped); + let root = offset; + let c = |index: usize| offset + index; + let d = |index: usize| offset + length + index; + let data = |index: usize| u16::try_from(index).unwrap().to_be_bytes().to_vec(); + let mut cells = Vec::new(); + if wrapped { + cells.push((Vec::new(), vec![root])); + } + cells.push((data(0), vec![d(1), c(1)])); + for index in 1..=length { + let refs = if index < length { + vec![c(index + 1), d(index)] + } else { + vec![d(index)] + }; + cells.push((data(index), refs)); + } + for index in 1..=length { + let refs = if index < length { + vec![d(index + 1)] + } else { + Vec::new() + }; + cells.push((data(length + index), refs)); + } + raw_boc(&cells) + } + + #[test] + fn large_cell_values_are_bounded() { + // The DAG is 1 002 levels deep; drop it on a thread with room for that. + std::thread::Builder::new() + .stack_size(256 << 20) + .spawn(|| { + for (schema, wrapped) in [("a#_ c:^Cell = A;", true), ("a#_ c:Any = A;", false)] { + let dag = non_topological_dag(1_000, wrapped); + let (kind, detail) = prompt_failure(schema, &dag); + assert_eq!(kind, F::LimitExceeded, "{schema}: {detail}"); + assert!(detail.contains("256 cells"), "{schema}: {detail}"); + let too_deep = non_topological_dag(4_000, wrapped); + assert_eq!( + failure_of(schema, &too_deep), + (F::InvalidCell, "cell is not a one-root BoC".to_owned()) + ); + } + // Control: a small DAG of the same shape is shown in full. + let small = non_topological_dag(3, true); + let fields = decoded("a#_ c:^Cell = A;", &small, false); + assert_eq!(fields.len(), 1); + assert!(fields[0].2.starts_with("b5ee9c72"), "{fields:?}"); + }) + .unwrap() + .join() + .unwrap(); + } + + #[test] + fn long_schemas_are_bounded() { + let cell = demo_boc(); + let long = format!("{DEMO_SCHEMA}{}", " ".repeat(MAX_SCHEMA_BYTES)); + let (kind, detail) = prompt_failure(&long, &cell); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("bytes"), "{detail}"); + + let tokens = format!("a#_ {}= A;", "_:# ".repeat(1_700)); + let (kind, detail) = prompt_failure(&tokens, &cell); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("tokens"), "{detail}"); + + let declarations = "a$_ = A;".repeat(129); + let (kind, detail) = prompt_failure(&declarations, &cell); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("declarations"), "{detail}"); + + let nested = format!("a#_ x:{}uint8{} = A;", "(".repeat(40), ")".repeat(40)); + let (kind, detail) = prompt_failure(&nested, &cell); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("nesting"), "{detail}"); + + let very_nested = format!("a#_ x:{}uint8 = A;", "(".repeat(10_000)); + let (kind, detail) = prompt_failure(&very_nested, &cell); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("tokens"), "{detail}"); + + let fields = format!("a#_ {}= A;", "_:bits0 ".repeat(65)); + let (kind, detail) = prompt_failure(&fields, &cell); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("fields"), "{detail}"); + + let chain = format!("a#_ x:(bits {}1) = A;", "1 + ".repeat(40)); + let (kind, detail) = prompt_failure(&chain, &cell); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("nesting"), "{detail}"); + } + + #[test] + fn output_is_bounded() { + let names = (0..64) + .map(|index| format!("f{index}:bits0 ")) + .collect::(); + let schema = + format!("leaf$_ {names}= Leaf; root$_ a:^Leaf b:^Leaf c:^Leaf d:^Leaf = Root;"); + let root = cell(|builder| { + for _ in 0..4 { + builder.write_ref(TonCell::empty().clone())?; + } + Ok(()) + }); + let (kind, detail) = prompt_failure(&schema, &boc(root)); + assert_eq!(kind, F::LimitExceeded); + assert!(detail.contains("256 fields"), "{detail}"); + } + + #[test] + fn details_echo_little_input() { + let one_byte = boc(cell(|builder| builder.write_num(&1_u8, 8))); + let name = "H".repeat(1_000); + let (kind, detail) = failure_of(&format!("a#_ x:{name} = A;"), &one_byte); + assert_eq!(kind, F::UnsupportedSchema); + assert!(detail.len() < 80, "{detail}"); + } + + proptest::proptest! { + #[test] + fn arbitrary_schemas_and_cells_never_panic( + schema in "[a-zA-Z0-9#$_:;=()\\[\\]{}^~?.+*!<> /\n]{0,512}", + tail in proptest::collection::vec(proptest::prelude::any::(), 0..64), + ) { + let mut raw = vec![0xb5, 0xee, 0x9c, 0x72]; + raw.extend_from_slice(&tail); + let cells = [ + DEMO_MESSAGE_CELL.to_owned(), + boc(wallet_cell(true)), + boc(TonCell::empty().clone()), + STANDARD.encode(raw), + ]; + for cell in &cells { + let schema = schema.clone(); + let cell = cell.clone(); + proptest::prop_assert!( + catch_unwind(move || decode_sign_data_cell(&schema, &cell, false)).is_ok() + ); + } + } + + #[test] + fn mutated_demo_cells_never_panic( + len in 0_u8..128, + text in proptest::collection::vec(proptest::prelude::any::(), 0..120), + extra_bits in 0_usize..8, + flip in proptest::prelude::any::(), + ) { + let built = cell(|builder| { + builder.write_num(&len, 7)?; + builder.write_bits(&text, text.len() * 8)?; + if extra_bits > 0 { + let extra = u8::try_from(flip % 256).unwrap() >> (8 - extra_bits); + builder.write_num(&extra, extra_bits)?; + } + Ok(()) + }); + let encoded = boc(built); + for schema in [DEMO_SCHEMA, WALLET_SCHEMA, ORDER_SCHEMA] { + let cell = encoded.clone(); + let result = catch_unwind(move || decode_sign_data_cell(schema, &cell, true)); + proptest::prop_assert!(result.is_ok()); + } + } + } +} + +#[cfg(test)] +mod session_tests { + //! The decoder as Telegram reaches it: through `TonConnectDerivedSession`. + + use std::str::FromStr as _; + use std::sync::Arc; + + use base64::{Engine as _, engine::general_purpose::STANDARD}; + use ton::ton_core::cell::{BoC, TonCell}; + use ton::ton_core::traits::tlb::TLB as _; + use ton::ton_core::types::TonAddress; + use ton_connect_core::{ClientId, NetworkId, RawAccountAddress, test_boc}; + use zeroize::Zeroizing; + + use super::{TonConnectSignDataCellDecoding, TonConnectSignDataCellFailure}; + use crate::TonConnectDerivedSession; + + type TestResult = Result<(), Box>; + + /// Decoded `signData` cell entries as `(depth, name, value)`. + type CellFields = Vec<(u32, String, String)>; + + /// The dApp client id of the derived-session fixed vector. + const PEER: &str = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"; + + const SESSION_ADDRESS: &str = + "0:1111111111111111111111111111111111111111111111111111111111111111"; + + const TESTNET: &str = "-3"; + const MAINNET: &str = "-239"; + + const SIGN_DATA_SCHEMA: &str = + "message#_ len:uint7 {len <= 127} text:(bits len * 8) = Message;"; + + /// The demo dApp's `Message` cell (`len` 20, "Test message in cell") as it sends it. + const DEMO_MESSAGE_CELL: &str = "te6cckEBAQEAFwAAKSioyuboQNrK5ubCzspA0txAxsrY2Whv0fw="; + + /// The demo dApp's current cell payload: 32 zero bits and "Hello!". + const DEMO_PAYLOAD: &str = "te6cckEBAQEADAAAFAAAAABIZWxsbyGVgYQo"; + + /// The demo dApp's destination and its mainnet non-bounceable form. + const DESTINATION_RAW: &str = + "0:8a5a9c7b70d329be670de4e6cce652d464765114aa98038c66c3d8ceaf2d19b0"; + const NON_BOUNCEABLE: &str = "UQCKWpx7cNMpvmcN5ObM5lLUZHZRFKqYA4xmw9jOry0ZsAKJ"; + + fn session(network: &str) -> Arc { + TonConnectDerivedSession::new( + Zeroizing::new([5_u8; 32]), + PEER.parse::().expect("fixed client id"), + [7_u8; 32], + RawAccountAddress::from_str(SESSION_ADDRESS).expect("raw address parses"), + NetworkId::try_from(network).expect("network id"), + ) + } + + fn decoded_cell_fields( + decoding: TonConnectSignDataCellDecoding, + ) -> Result> { + match decoding { + TonConnectSignDataCellDecoding::Decoded { fields } => Ok(fields + .into_iter() + .map(|field| (field.depth, field.name, field.value)) + .collect()), + TonConnectSignDataCellDecoding::NotDecodable { failure, detail } => { + Err(format!("cell is not decodable: {failure:?} {detail}").into()) + } + } + } + + /// A standard base64 `BoC` of `levels` data-less cells, each referencing the next one. + fn deep_chain_cell(levels: usize) -> String { + STANDARD.encode(test_boc::chain(levels)) + } + + /// Runs `job` on a 512 KiB stack: Telegram decrypts and decodes requests on a + /// default `std::thread`, which gets 512 KiB on macOS. + fn on_worker_stack(job: impl FnOnce() -> TestResult + Send + 'static) -> TestResult { + std::thread::Builder::new() + .name("wallet-worker-512k".into()) + .stack_size(512 * 1024) + .spawn(move || job().map_err(|error| error.to_string())) + .expect("spawn") + .join() + .expect("the job must not panic")?; + Ok(()) + } + + #[test] + fn sign_data_cells_decode_through_the_session() -> TestResult { + let testnet = session(TESTNET); + assert_eq!( + decoded_cell_fields( + testnet.decode_sign_data_cell( + SIGN_DATA_SCHEMA.to_owned(), + DEMO_MESSAGE_CELL.to_owned() + ) + )?, + [ + (0, "len".to_owned(), "20".to_owned()), + ( + 0, + "text".to_owned(), + "54657374206d65737361676520696e2063656c6c".to_owned() + ), + ] + ); + + let destination = TonAddress::from_str(DESTINATION_RAW)?; + let mut builder = TonCell::builder(); + builder.write_num(&0b100_u8, 3)?; + builder.write_num(&0_u8, 8)?; + builder.write_bits(destination.hash.as_slice(), 256)?; + let cell = STANDARD.encode(BoC::new(builder.build()?).to_bytes(false)?); + let schema = "a#_ to:MsgAddress = A;"; + + let fields = + decoded_cell_fields(testnet.decode_sign_data_cell(schema.to_owned(), cell.clone()))?; + let expected = destination.to_base64(false, false, true); + assert!(expected.starts_with("0Q"), "{expected}"); + assert_eq!(fields, [(0, "to".to_owned(), expected)]); + + let fields = + decoded_cell_fields(session(MAINNET).decode_sign_data_cell(schema.to_owned(), cell))?; + assert_eq!(fields, [(0, "to".to_owned(), NON_BOUNCEABLE.to_owned())]); + Ok(()) + } + + #[test] + fn the_existing_demo_payload_is_not_a_message_cell() { + // 32 zero bits and "Hello!": `len` reads 0, then 73 bits are left over. + assert!(matches!( + session(TESTNET) + .decode_sign_data_cell(SIGN_DATA_SCHEMA.to_owned(), DEMO_PAYLOAD.to_owned()), + TonConnectSignDataCellDecoding::NotDecodable { + failure: TonConnectSignDataCellFailure::TrailingData, + .. + } + )); + } + + #[test] + fn deep_sign_data_cells_stay_bounded_in_the_decoder_on_a_512_kib_stack() -> TestResult { + on_worker_stack(|| { + let session = session(TESTNET); + assert_eq!( + session.decode_sign_data_cell(SIGN_DATA_SCHEMA.to_owned(), deep_chain_cell(5000)), + TonConnectSignDataCellDecoding::NotDecodable { + failure: TonConnectSignDataCellFailure::InvalidCell, + detail: "cell is not a one-root BoC".to_owned(), + } + ); + + let schema = "c#_ v:^Cell = C;"; + let TonConnectSignDataCellDecoding::NotDecodable { failure, detail } = + session.decode_sign_data_cell(schema.to_owned(), deep_chain_cell(1000)) + else { + return Err("a 1 000-level cell value must reach the decoder's cap".into()); + }; + assert_eq!( + failure, + TonConnectSignDataCellFailure::LimitExceeded, + "{detail}" + ); + assert!(detail.contains("256 cells"), "{detail}"); + + let short = deep_chain_cell(250); + let fields = decoded_cell_fields( + session.decode_sign_data_cell(schema.to_owned(), short.clone()), + )?; + let [(0, name, hex)] = fields.as_slice() else { + return Err(format!("one root field expected: {fields:?}").into()); + }; + assert_eq!(name, "v"); + assert!(hex.starts_with("b5ee9c72"), "{hex}"); + let bytes = hex + .as_bytes() + .chunks(2) + .map(|pair| Ok(u8::from_str_radix(std::str::from_utf8(pair)?, 16)?)) + .collect::, Box>>()?; + let root = TonCell::from_boc(STANDARD.decode(&short)?)?; + assert_eq!(TonCell::from_boc(bytes)?.hash()?, root.refs()[0].hash()?); + Ok(()) + }) + } +} diff --git src/wallet/mod.rs src/wallet/mod.rs index 8843ccb..bb1b8f6 100644 --- src/wallet/mod.rs +++ src/wallet/mod.rs @@ -16,6 +16,7 @@ pub(crate) mod slip_0010; pub(crate) mod transfer; pub use mnemonic_scheme::{MnemonicScheme, detect_mnemonic_schemes, rotation_mnemonic_public_key}; +pub use transfer::build_contract_state_init; use std::sync::Arc; diff --git src/wallet/nft_transfer.rs src/wallet/nft_transfer.rs index e9a343c..2ef40fa 100644 --- src/wallet/nft_transfer.rs +++ src/wallet/nft_transfer.rs @@ -91,6 +91,7 @@ pub(crate) fn canonicalize_nft_transfer( body: SendMessageBody::RawPayload { boc: body }, bounce: true, state_init: None, + send_mode: None, }], }, }) diff --git src/wallet/send.rs src/wallet/send.rs index caf4a9d..25598b0 100644 --- src/wallet/send.rs +++ src/wallet/send.rs @@ -1800,6 +1800,8 @@ mod tests { .expect("the empty-cell BOC fixture is valid"), ); }), + // Mode 3 signs like no mode, but the bound message must still match. + Box::new(|prepared| prepared.messages[0].send_mode = Some(3)), Box::new(|prepared| prepared.seqno = 8), Box::new(|prepared| prepared.needs_state_init = true), ]; @@ -1861,6 +1863,7 @@ mod tests { body: SendMessageBody::Empty, bounce: false, state_init: None, + send_mode: None, }], }, } @@ -1903,6 +1906,7 @@ mod tests { body: SendMessageBody::Empty, bounce: false, state_init: None, + send_mode: None, }], seqno: 7, needs_state_init: false, diff --git src/wallet/transfer.rs src/wallet/transfer.rs index 2737a9e..74a51c2 100644 --- src/wallet/transfer.rs +++ src/wallet/transfer.rs @@ -122,7 +122,7 @@ pub(crate) fn prepare_transfer( if account.needs_state_init() && !wallet.is_pre_rotation() { return Err(TransferError::RotatedWalletRequiresActiveAccount); } - let _ = request.intent.exact_value_total()?; + let _ = request.intent.exact_value_total_for_external()?; let messages = request.intent.messages.clone(); let (internal, send_modes) = build_internal_messages(&messages)?; @@ -226,12 +226,19 @@ pub(crate) fn prepare_internal_signed_transfer( } /// Builds both supported delivery forms from one account snapshot and expiry. +/// +/// The internal form signs `gasless_request` when given, otherwise `request`. +#[allow( + clippy::too_many_arguments, + reason = "both delivery forms must be signed from one explicit account snapshot and expiry" +)] pub(crate) fn prepare_transfer_pair( mnemonic_bytes: &[u8], record_id: &NonEmptyString, source: &TonAddressString, network: Network, request: &SendRequest, + gasless_request: Option<&SendRequest>, account: &FreshSendAccount, valid_until: u64, ) -> Result<(PreparedTransfer, PreparedTransfer), TransferError> { @@ -249,7 +256,7 @@ pub(crate) fn prepare_transfer_pair( record_id, source, network, - request, + gasless_request.unwrap_or(request), account, valid_until, )?; @@ -269,7 +276,7 @@ pub(crate) fn prepare_transfer_emulation( account: &FreshSendAccount, valid_until: u64, ) -> Result { - let _ = request.intent.exact_value_total()?; + let _ = request.intent.exact_value_total_for_external()?; let (internal, send_modes) = build_internal_messages(&request.intent.messages)?; let wallet_id = match network { Network::Mainnet => WALLET_SUBWALLET_ID_DEFAULT, @@ -322,6 +329,24 @@ pub(crate) fn prepare_transfer_emulation( .map_err(TransferError::InvalidBoc) } +/// Composes a contract `StateInit` from serialized `code` and `data` cells. +/// +/// Each argument must be one single-root BOC. The result holds exactly these +/// two cells, with no split depth, special flag or library, and can be passed +/// as [`SendMessage::state_init`]. The message destination is not derived from +/// it. Returns `None` when an argument or the composed `StateInit` is not a +/// valid single-root BOC. +#[uniffi::export] +#[must_use] +pub fn build_contract_state_init(code: Vec, data: Vec) -> Option { + let code = Boc::try_from(code).ok()?; + let data = Boc::try_from(data).ok()?; + let code = TonCell::from_boc(code.as_bytes().to_vec()).ok()?; + let data = TonCell::from_boc(data.as_bytes().to_vec()).ok()?; + let state_init = StateInit::new(code, data); + Boc::try_from(state_init.to_boc().ok()?).ok() +} + /// Serializes one ordered message batch and selects each wallet send mode. fn build_internal_messages( send_messages: &[SendMessage], @@ -338,7 +363,8 @@ fn build_internal_messages( /// Serializes one complete send message and selects its wallet send mode. fn build_internal_message(send_message: &SendMessage) -> Result<(TonCell, u8), TransferError> { - let (amount_nanograms, send_mode) = match &send_message.amount { + let explicit_mode = send_message.explicit_send_mode()?; + let (amount_nanograms, default_mode) = match &send_message.amount { SendAmount::Exact { nanograms } => { let amount = nanograms .try_to::() @@ -347,6 +373,7 @@ fn build_internal_message(send_message: &SendMessage) -> Result<(TonCell, u8), T } SendAmount::All => (0, ALL_BALANCE_SEND_MODE), }; + let send_mode = explicit_mode.unwrap_or(default_mode); let mut info = CommonMsgInfoInt::new( send_message.destination.as_address().to_msg_address(), TLBCoins::new(amount_nanograms), @@ -397,11 +424,17 @@ pub(crate) fn derive_source( mod tests { use std::str::FromStr; + use crate::SendModeRefusal::{ + self, CarryAllBalance, CarryInboundValue, DestroyAccount, MissingIgnoreErrors, OutOfRange, + UndefinedFlag, + }; use crate::{SendExpiration, SendIntent}; use ed25519_dalek::{Signature, VerifyingKey}; use ton::block_tlb::CommonMsgInfo; + use ton::ton_core::cell::BoC; use ton::ton_core::types::tlb_core::MsgAddress; use ton::ton_wallet::WalletExtMsgBody; + use ton_connect_core::test_boc::REFERENCE_PAST_THE_LAST_CELL; use super::*; @@ -575,6 +608,7 @@ mod tests { None, )], }, + estimate_shortfall: false, }; let account = FreshSendAccount { status: crate::AccountStatus::Uninitialized, @@ -611,6 +645,7 @@ mod tests { expiration: SendExpiration::EngineDefault, messages: vec![send_message(amount, SendMessageBody::Empty, None)], }, + estimate_shortfall: false, }; let mut payload = TonCell::builder(); payload @@ -635,6 +670,7 @@ mod tests { }], ..plain.intent.clone() }, + estimate_shortfall: false, }; let with_state_init = SendPreviewRequest { intent: SendIntent { @@ -644,6 +680,7 @@ mod tests { }], ..plain.intent.clone() }, + estimate_shortfall: false, }; let emulate = |request: &SendPreviewRequest| { @@ -760,6 +797,7 @@ mod tests { &source, Network::Testnet, &request, + None, &account, valid_until, ) @@ -792,6 +830,519 @@ mod tests { assert_eq!(external_body.valid_until, valid_until as u32); } + /// Signed BOCs captured from the serializer before explicit send modes existed. + /// + /// Order: exact raw-payload message with a ready `StateInit` as the external + /// and internal form, whole-balance message as the external and internal + /// form, then the exact message's external emulation. Never regenerate them. + const LEGACY_GOLDEN_BOCS: [&str; 5] = [ + "te6ccgEBBgEAvQABRYgAZ4xQk4U3opHAuJR05zBkP9ox03AUWUCLZzGptmq5eCIMAQGiCvtOSMqMAgxnDujt/c+fM8zATFlTerh+iSFerml8ldYgCNHYA6LNjf7Ct+nfKZkqXgt4ZIBKw53oUfnuOua2AmOJbnV//3/9cT+zAAAAAAcDAgNpYgARERERERERERERERERERERERERERERERERERERERERESHc1lAIAAAAAAAAAAAAAAAAAjYDBAUAAhEAAioAAmM=", + "te6ccgEBBgEAygABYEIAGeMUJOFN6KRwLiUdOcwZD/aMdNwFFlAi2cxqbZquXgiAAAAAAAAAAAAAAAAAAQEBojB1jdYxO0+m+mGITmCv5bE7jjCTsWvGeuU0LGm8iScNSj5aL6frtw+DxtLAx2QxD8XEi8mEXDbQaCthWNqiEQZjiW50f/9//XE/swAAAAAHAwIDaWIAEREREREREREREREREREREREREREREREREREREREREREh3NZQCAAAAAAAAAAAAAAAAAI2AwQFAAIRAAIqAAJj", + "te6ccgEBBAEArwABRYgAZ4xQk4U3opHAuJR05zBkP9ox03AUWUCLZzGptmq5eCIMAQGiMa8/Kfv0j6JLKUejvwMMYoVGIWkqnsZrQ7GEdRVHDtWRU+s6Pf+HQGToRuNv50Di7zhA0Ez14WX0+07SPeQpDmOJbnV//3/9cT+zAAAAAAeCAgFgQgAREREREREREREREREREREREREREREREREREREREREREQAAAAAAAAAAAAAAAAABAwAA", + "te6ccgEBBAEAvAABYEIAGeMUJOFN6KRwLiUdOcwZD/aMdNwFFlAi2cxqbZquXgiAAAAAAAAAAAAAAAAAAQEBouE4y1xwwelg6AoN/TMPXavLO/no5qumOZpmFoCCXY79rAEGDE+pyiErxmU/bX/E4A/hgUUYyVDFWc25PfHrDg1jiW50f/9//XE/swAAAAAHggIBYEIAEREREREREREREREREREREREREREREREREREREREREREAAAAAAAAAAAAAAAAAAQMAAA==", + "te6ccgEBBgEAvQABRYgAZ4xQk4U3opHAuJR05zBkP9ox03AUWUCLZzGptmq5eCIMAQGiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGOJbnV//3/9cT+zAAAAAAcDAgNpYgARERERERERERERERERERERERERERERERERERERERERESHc1lAIAAAAAAAAAAAAAAAAAjYDBAUAAhEAAioAAmM=", + ]; + + #[test] + fn mode_less_messages_keep_their_legacy_signed_bocs() { + let wallet = derive_wallet(PRE_ROTATION_MNEMONIC, Network::Testnet) + .expect("fixture mnemonic derives a wallet"); + let public_key = wallet.key_pair.public_key; + let source = TonAddressString::from_address(&wallet.address, Network::Testnet); + let record_id = NonEmptyString::try_from("record").expect("record id is valid"); + let account = FreshSendAccount { + status: crate::AccountStatus::Active, + seqno: 7, + }; + let valid_until = 1_900_000_000; + let one_byte_boc = |value: u8| { + let mut cell = TonCell::builder(); + cell.write_num(&value, 8).expect("one byte fits"); + let cell = cell.build().expect("cell builds"); + Boc::try_from(cell.to_boc().expect("cell BOC encodes")).expect("cell BOC validates") + }; + let state_init = StateInit::new( + TonCell::from_boc(one_byte_boc(17).as_bytes().to_vec()).expect("code decodes"), + TonCell::from_boc(one_byte_boc(42).as_bytes().to_vec()).expect("data decodes"), + ); + let state_init = Boc::try_from(state_init.to_boc().expect("StateInit BOC encodes")) + .expect("StateInit BOC validates"); + let mut exact = send_message( + SendAmount::exact("1000000001").expect("valid exact amount"), + SendMessageBody::RawPayload { + boc: one_byte_boc(99), + }, + Some(state_init), + ); + exact.bounce = true; + let whole_balance = send_message(SendAmount::All, SendMessageBody::Empty, None); + let request = |message: SendMessage| SendRequest { + operation_id: NonEmptyString::try_from("golden").expect("operation id is valid"), + force: false, + intent: SendIntent { + expiration: SendExpiration::Exact { + unix_timestamp: valid_until, + }, + messages: vec![message], + }, + }; + let sign = |request: &SendRequest| { + let external = prepare_transfer( + PRE_ROTATION_MNEMONIC.as_bytes(), + &record_id, + &source, + Network::Testnet, + request, + &account, + valid_until, + ) + .expect("external form signs"); + let internal = prepare_internal_signed_transfer( + PRE_ROTATION_MNEMONIC.as_bytes(), + &record_id, + &source, + Network::Testnet, + request, + &account, + valid_until, + ) + .expect("internal form signs"); + ( + external.signed_boc.to_base64(), + internal.signed_boc.to_base64(), + ) + }; + + let (exact_external, exact_internal) = sign(&request(exact.clone())); + let (all_external, all_internal) = sign(&request(whole_balance)); + let exact_emulation = prepare_transfer_emulation( + &source, + &public_key, + Network::Testnet, + &SendPreviewRequest { + intent: request(exact).intent, + estimate_shortfall: false, + }, + &account, + valid_until, + ) + .expect("external emulation builds") + .to_base64(); + + assert_eq!( + [ + exact_external, + exact_internal, + all_external, + all_internal, + exact_emulation, + ], + LEGACY_GOLDEN_BOCS + ); + } + + /// Explicit modes given to the real signers, with the refusal expected for + /// an external and for an internal request; `None` means it is signed. + const SIGNING_MODE_CASES: [(i32, Option, Option); 16] = [ + (-1, Some(OutOfRange), Some(OutOfRange)), + (0, Some(MissingIgnoreErrors), None), + (1, Some(MissingIgnoreErrors), None), + (2, None, None), + (3, None, None), + (4, Some(UndefinedFlag), Some(UndefinedFlag)), + (8, Some(UndefinedFlag), Some(UndefinedFlag)), + (16, Some(MissingIgnoreErrors), None), + (17, Some(MissingIgnoreErrors), None), + (18, None, None), + (19, None, None), + (32, Some(DestroyAccount), Some(DestroyAccount)), + (64, Some(CarryInboundValue), Some(CarryInboundValue)), + (128, Some(CarryAllBalance), Some(CarryAllBalance)), + (130, Some(CarryAllBalance), Some(CarryAllBalance)), + (256, Some(OutOfRange), Some(OutOfRange)), + ]; + + /// Signs each accepted explicit mode exactly and names each refused one. + #[test] + fn explicit_send_modes_are_signed_exactly_or_refused_by_name_in_each_form() { + let fixture = SigningFixture::new(); + let mut external_modes = Vec::new(); + let mut internal_modes = Vec::new(); + let mut pair_modes = Vec::new(); + + for (mode, external_refusal, internal_refusal) in SIGNING_MODE_CASES { + let served = [Served::call(Some(mode))]; + let request = served_request(&served); + + let external = refusal(fixture.external(&request)).map(|prepared| { + fixture.signed_modes(&prepared.signed_boc, Delivery::External, &served) + }); + assert_eq!( + external, + expected_signing(mode, external_refusal), + "external form, mode {mode}" + ); + let internal = refusal(fixture.internal(&request)).map(|prepared| { + fixture.signed_modes(&prepared.signed_boc, Delivery::Internal, &served) + }); + assert_eq!( + internal, + expected_signing(mode, internal_refusal), + "internal form, mode {mode}" + ); + // The pair always builds an external BOC as well, so it follows the external rule. + let pair = refusal(fixture.pair(&request)).map(|(external, internal)| { + let modes = fixture.signed_modes(&external.signed_boc, Delivery::External, &served); + assert_eq!( + fixture.signed_modes(&internal.signed_boc, Delivery::Internal, &served), + modes + ); + modes + }); + assert_eq!( + pair, + expected_signing(mode, external_refusal), + "pair, mode {mode}" + ); + + for (outcome, accepted) in [ + (external.is_ok(), &mut external_modes), + (internal.is_ok(), &mut internal_modes), + (pair.is_ok(), &mut pair_modes), + ] { + if outcome { + accepted.push(mode); + } + } + } + + assert_eq!(external_modes, [2, 3, 18, 19]); + assert_eq!(internal_modes, [0, 1, 2, 3, 16, 17, 18, 19]); + assert_eq!(pair_modes, [2, 3, 18, 19]); + } + + /// Signs an explicit mode 3 byte-for-byte like a message without a mode. + #[test] + fn explicit_mode_three_signs_the_same_bytes_as_no_mode() { + let fixture = SigningFixture::new(); + let mode_less = [Served::call(None)]; + let mode_less_request = served_request(&mode_less); + let explicit_request = served_request(&[Served::call(Some(3))]); + + let external = fixture + .external(&mode_less_request) + .expect("mode-less external request signs"); + let internal = fixture + .internal(&mode_less_request) + .expect("mode-less internal request signs"); + + assert_eq!( + fixture + .external(&explicit_request) + .expect("explicit external request signs") + .signed_boc, + external.signed_boc + ); + assert_eq!( + fixture + .internal(&explicit_request) + .expect("explicit internal request signs") + .signed_boc, + internal.signed_boc + ); + assert_eq!( + fixture + .emulation(&explicit_request) + .expect("explicit request emulates"), + fixture + .emulation(&mode_less_request) + .expect("mode-less request emulates") + ); + assert_eq!( + fixture.signed_modes(&external.signed_boc, Delivery::External, &mode_less), + [3] + ); + assert_eq!( + fixture.signed_modes(&internal.signed_boc, Delivery::Internal, &mode_less), + [3] + ); + } + + /// Keeps each action's own mode and served fields in batch order. + #[test] + fn ordered_batches_carry_each_message_mode_in_both_forms() { + let fixture = SigningFixture::new(); + let mixed = [ + Served::new(DESTINATION, 1_000, false, 0x0000_0001, None), + Served::new(OTHER_DESTINATION, 2_000, true, 0x0000_0002, Some(2)), + Served::new(THIRD_DESTINATION, 3_000, false, 0x0000_0003, Some(19)), + ]; + let request = served_request(&mixed); + + let (external, internal) = fixture + .pair(&request) + .expect("mixed batch signs in both forms"); + assert_eq!( + fixture.signed_modes(&external.signed_boc, Delivery::External, &mixed), + [3, 2, 19] + ); + assert_eq!( + fixture.signed_modes(&internal.signed_boc, Delivery::Internal, &mixed), + [3, 2, 19] + ); + let preview = fixture.emulation(&request).expect("mixed batch emulates"); + assert_eq!( + fixture.signed_modes(&preview, Delivery::External, &mixed), + [3, 2, 19] + ); + + // Four actions span two message-array chunks of the bulk request. + let internal_only = [ + Served::new(DESTINATION, 4_000, true, 0x0000_0004, Some(0)), + Served::new(OTHER_DESTINATION, 5_000, false, 0x0000_0005, Some(1)), + Served::new(THIRD_DESTINATION, 6_000, true, 0x0000_0006, Some(16)), + Served::new(DESTINATION, 7_000, false, 0x0000_0007, Some(17)), + ]; + let request = served_request(&internal_only); + + let internal = fixture + .internal(&request) + .expect("internal-only modes sign as an internal request"); + assert_eq!( + fixture.signed_modes(&internal.signed_boc, Delivery::Internal, &internal_only), + [0, 1, 16, 17] + ); + let first_without_ignore_errors = Some(SendIntentError::UnsupportedSendMode { + mode: 0, + reason: MissingIgnoreErrors, + }); + assert_eq!( + refusal(fixture.external(&request)).err(), + first_without_ignore_errors + ); + assert_eq!( + refusal(fixture.pair(&request)).err(), + first_without_ignore_errors + ); + assert_eq!( + refusal(fixture.emulation(&request)).err(), + first_without_ignore_errors + ); + } + + /// Refuses a whole batch when only its second message names a refused mode. + #[test] + fn a_refused_second_message_refuses_the_batch_in_every_form() { + let fixture = SigningFixture::new(); + let request = served_request(&[ + Served::call(Some(3)), + Served::new(OTHER_DESTINATION, 2_000, false, 0x0000_0002, Some(64)), + ]); + let carries_inbound_value = Some(SendIntentError::UnsupportedSendMode { + mode: 64, + reason: CarryInboundValue, + }); + assert_eq!( + refusal(fixture.external(&request)).err(), + carries_inbound_value + ); + assert_eq!( + refusal(fixture.internal(&request)).err(), + carries_inbound_value + ); + assert_eq!(refusal(fixture.pair(&request)).err(), carries_inbound_value); + assert_eq!( + refusal(fixture.emulation(&request)).err(), + carries_inbound_value + ); + + let internal_only_second = [ + Served::call(Some(2)), + Served::new(OTHER_DESTINATION, 2_000, false, 0x0000_0002, Some(17)), + ]; + let request = served_request(&internal_only_second); + let lacks_ignore_errors = Some(SendIntentError::UnsupportedSendMode { + mode: 17, + reason: MissingIgnoreErrors, + }); + assert_eq!( + refusal(fixture.external(&request)).err(), + lacks_ignore_errors + ); + assert_eq!(refusal(fixture.pair(&request)).err(), lacks_ignore_errors); + assert_eq!( + refusal(fixture.emulation(&request)).err(), + lacks_ignore_errors + ); + let internal = fixture + .internal(&request) + .expect("an internal request accepts mode 17"); + assert_eq!( + fixture.signed_modes( + &internal.signed_boc, + Delivery::Internal, + &internal_only_second + ), + [2, 17] + ); + } + + /// Emulates each accepted external mode exactly and names every other value. + #[test] + fn external_emulation_carries_accepted_modes_and_refuses_every_other_value() { + let fixture = SigningFixture::new(); + let mut emulated = Vec::new(); + + for mode in (-1..=256).chain([i32::MIN, 1024, i32::MAX]) { + let served = [Served::call(Some(mode))]; + match refusal(fixture.emulation(&served_request(&served))) { + Ok(preview) => { + assert_eq!( + fixture.signed_modes(&preview, Delivery::External, &served), + [mode] + ); + emulated.push(mode); + } + Err(error) => { + let SendIntentError::UnsupportedSendMode { mode: refused, .. } = error else { + panic!("mode {mode}: unexpected refusal {error:?}"); + }; + assert_eq!(refused, mode); + } + } + } + + assert_eq!(emulated, [2, 3, 18, 19]); + } + + /// Composes a `StateInit` cell holding exactly the served code and data. + #[test] + fn contract_state_init_holds_exactly_the_served_code_and_data_cells() { + let (code, data) = served_contract_cells(); + let state_init = build_contract_state_init( + code.to_boc().expect("code BOC encodes"), + data.to_boc().expect("data BOC encodes"), + ) + .expect("valid code and data compose"); + + let root = TonCell::from_boc(state_init.as_bytes().to_vec()).expect("helper BOC parses"); + assert_eq!(root.data_len_bits(), 5); + assert_eq!(root.refs().len(), 2); + let mut parser = root.parser(); + let flags = (0..5) + .map(|_| parser.read_bit().expect("flag bit")) + .collect::>(); + // No split depth, no special flags, code present, data present, no library. + assert_eq!(flags, [false, false, true, true, false]); + assert_eq!(parser.read_next_ref().expect("code reference"), &code); + assert_eq!(parser.read_next_ref().expect("data reference"), &data); + parser + .ensure_empty() + .expect("nothing follows the code and data references"); + assert_eq!(root.refs()[0].refs().len(), 2, "code keeps its children"); + } + + /// Signs the composed deployment to the served destination in both forms. + #[test] + fn contract_state_init_is_signed_with_the_served_destination_in_both_forms() { + let fixture = SigningFixture::new(); + let (code, data) = served_contract_cells(); + let state_init = build_contract_state_init( + code.to_boc().expect("code BOC encodes"), + data.to_boc().expect("data BOC encodes"), + ) + .expect("valid code and data compose"); + let state_init_root = + TonCell::from_boc(state_init.as_bytes().to_vec()).expect("helper BOC parses"); + let derived = TonAddress::new( + 0, + state_init_root + .hash() + .expect("StateInit cell hashes") + .clone(), + ); + assert_ne!( + TonAddress::from_str(ESCROW_DESTINATION).expect("served destination parses"), + derived, + "the served destination must differ from the hash-derived one" + ); + let served = Served { + state_init: Some(state_init), + ..Served::new( + ESCROW_DESTINATION, + 1_234_567_891, + true, + 0x7362_d09c, + Some(18), + ) + }; + + let (external, internal) = fixture + .pair(&served_request(std::slice::from_ref(&served))) + .expect("the deployment signs in both forms"); + + for (boc, delivery) in [ + (&external.signed_boc, Delivery::External), + (&internal.signed_boc, Delivery::Internal), + ] { + let actions = decode_wallet_actions(boc, &fixture.source, delivery); + let [(mode, action)] = actions.as_slice() else { + panic!("{delivery:?} form must carry exactly one action"); + }; + assert_eq!(*mode, 18, "{delivery:?}"); + served.assert_carried_by(action); + + let init = &action + .init + .as_ref() + .expect("the action carries the StateInit") + .value; + assert_eq!(init.split_depth, None, "{delivery:?}"); + assert_eq!(init.tick_tock, None, "{delivery:?}"); + assert_eq!(init.code.as_deref(), Some(&code), "{delivery:?}"); + assert_eq!(init.data.as_deref(), Some(&data), "{delivery:?}"); + assert!(init.library.is_empty(), "{delivery:?}"); + assert_eq!( + init.to_cell().expect("attached StateInit serializes"), + state_init_root, + "{delivery:?}" + ); + } + } + + /// Refuses an empty, malformed or multi-root BOC in either argument. + #[test] + fn contract_state_init_refuses_an_invalid_code_or_data_argument() { + let (code, data) = served_contract_cells(); + let two_roots = BoC::from_roots([code.clone(), TonCell::empty().clone()]) + .to_bytes(false) + .expect("two-root BOC encodes"); + let code = code.to_boc().expect("code BOC encodes"); + let data = data.to_boc().expect("data BOC encodes"); + let invalid = [ + ("empty", Vec::new()), + ("not a BOC", b"not a boc".to_vec()), + ("truncated", code[..code.len() - 1].to_vec()), + ( + "reference past the last cell", + REFERENCE_PAST_THE_LAST_CELL.to_vec(), + ), + ("two roots", two_roots), + ]; + + assert!(build_contract_state_init(code.clone(), data.clone()).is_some()); + for (name, bytes) in invalid { + assert!( + build_contract_state_init(bytes.clone(), data.clone()).is_none(), + "code: {name}" + ); + assert!( + build_contract_state_init(code.clone(), bytes).is_none(), + "data: {name}" + ); + } + } + #[test] fn rotated_wallet_requests_use_the_signing_key_and_anchor_address() { let source = derive_source(ROTATED_MNEMONIC.as_bytes(), Network::Testnet) @@ -943,6 +1494,303 @@ mod tests { body, bounce: false, state_init, + send_mode: None, + } + } + + /// Fixed expiry shared by the explicit-mode signing tests. + const VALID_UNTIL: u64 = 1_900_000_000; + const OTHER_DESTINATION: &str = + "0:3333333333333333333333333333333333333333333333333333333333333333"; + const THIRD_DESTINATION: &str = + "0:4444444444444444444444444444444444444444444444444444444444444444"; + const ESCROW_DESTINATION: &str = + "0:5555555555555555555555555555555555555555555555555555555555555555"; + + /// The throwaway pre-rotation wallet on an active account at seqno 7. + struct SigningFixture { + source: TonAddressString, + public_key: [u8; 32], + record_id: NonEmptyString, + account: FreshSendAccount, + } + + impl SigningFixture { + fn new() -> Self { + let wallet = derive_wallet(PRE_ROTATION_MNEMONIC, Network::Testnet) + .expect("fixture mnemonic derives a wallet"); + Self { + source: TonAddressString::from_address(&wallet.address, Network::Testnet), + public_key: wallet.key_pair.public_key, + record_id: NonEmptyString::try_from("record").expect("record id is valid"), + account: FreshSendAccount { + status: crate::AccountStatus::Active, + seqno: 7, + }, + } + } + + fn external(&self, request: &SendRequest) -> Result { + prepare_transfer( + PRE_ROTATION_MNEMONIC.as_bytes(), + &self.record_id, + &self.source, + Network::Testnet, + request, + &self.account, + VALID_UNTIL, + ) + } + + fn internal(&self, request: &SendRequest) -> Result { + prepare_internal_signed_transfer( + PRE_ROTATION_MNEMONIC.as_bytes(), + &self.record_id, + &self.source, + Network::Testnet, + request, + &self.account, + VALID_UNTIL, + ) + } + + fn pair( + &self, + request: &SendRequest, + ) -> Result<(PreparedTransfer, PreparedTransfer), TransferError> { + prepare_transfer_pair( + PRE_ROTATION_MNEMONIC.as_bytes(), + &self.record_id, + &self.source, + Network::Testnet, + request, + None, + &self.account, + VALID_UNTIL, + ) + } + + fn emulation(&self, request: &SendRequest) -> Result { + prepare_transfer_emulation( + &self.source, + &self.public_key, + Network::Testnet, + &SendPreviewRequest { + intent: request.intent.clone(), + estimate_shortfall: false, + }, + &self.account, + VALID_UNTIL, + ) + } + + /// Decodes `boc`, checks each action against `served` in order, and + /// returns the action modes. + fn signed_modes(&self, boc: &Boc, delivery: Delivery, served: &[Served]) -> Vec { + let actions = decode_wallet_actions(boc, &self.source, delivery); + assert_eq!(actions.len(), served.len(), "{delivery:?} action count"); + for ((_, action), served) in actions.iter().zip(served) { + served.assert_carried_by(action); + } + actions + .into_iter() + .map(|(mode, _)| i32::from(mode)) + .collect() + } + } + + /// A served message described by literals, independent of the signer. + #[derive(Clone)] + struct Served { + destination: &'static str, + nanograms: u128, + bounce: bool, + body: TonCell, + state_init: Option, + mode: Option, + } + + impl Served { + /// A bounceable contract call with a raw body and the given `mode`. + fn call(mode: Option) -> Self { + Self::new(DESTINATION, 1_000_000_001, true, 0x0f8a_7ea5, mode) + } + + /// A message whose raw body is the 32-bit `opcode`. + fn new( + destination: &'static str, + nanograms: u128, + bounce: bool, + opcode: u32, + mode: Option, + ) -> Self { + let mut body = TonCell::builder(); + body.write_num(&opcode, 32).expect("opcode fits"); + Self { + destination, + nanograms, + bounce, + body: body.build().expect("body cell builds"), + state_init: None, + mode, + } + } + + /// The engine message a caller builds from these served fields. + fn message(&self) -> SendMessage { + SendMessage { + destination: TonAddressString::try_from(self.destination) + .expect("served destination is valid"), + amount: SendAmount::exact(self.nanograms.to_string()) + .expect("served value is valid"), + body: SendMessageBody::RawPayload { + boc: Boc::try_from(self.body.to_boc().expect("body BOC encodes")) + .expect("body BOC validates"), + }, + bounce: self.bounce, + state_init: self.state_init.clone(), + send_mode: self.mode, + } + } + + /// Asserts that a decoded wallet action carries exactly these fields. + fn assert_carried_by(&self, action: &Msg) { + let CommonMsgInfo::Int(info) = &action.info else { + panic!("a wallet action must be an internal message"); + }; + assert_eq!( + info.dst, + TonAddress::from_str(self.destination) + .expect("served destination parses") + .to_msg_address() + ); + assert_eq!(info.value.coins, TLBCoins::new(self.nanograms)); + assert_eq!(info.bounce, self.bounce); + assert_eq!(action.body.value, self.body); + if self.state_init.is_none() { + assert!(action.init.is_none(), "no StateInit was served"); + } + } + } + + /// Builds one fixed-expiry request carrying `served` in order. + fn served_request(served: &[Served]) -> SendRequest { + SendRequest { + operation_id: NonEmptyString::try_from("served").expect("operation id is valid"), + force: false, + intent: SendIntent { + expiration: SendExpiration::Exact { + unix_timestamp: VALID_UNTIL, + }, + messages: served.iter().map(Served::message).collect(), + }, + } + } + + /// Delivery form of a signed wallet request. + #[derive(Debug, Clone, Copy)] + enum Delivery { + /// An incoming external message, as normal submission and emulation use. + External, + /// An owner-signed internal message, as gasless submission uses. + Internal, + } + + /// Decodes a complete signed wallet BOC with the vendored readers alone. + /// + /// The envelope must address `source` and deploy nothing; each action + /// message must be consumed completely. Returns every action's mode and + /// message in request order. + fn decode_wallet_actions( + boc: &Boc, + source: &TonAddressString, + delivery: Delivery, + ) -> Vec<(u8, Msg)> { + let root = TonCell::from_boc(boc.as_bytes().to_vec()).expect("signed BOC parses"); + let envelope = read_whole_message(&root); + assert!(envelope.init.is_none(), "an active wallet is not deployed"); + let mut body = envelope.body.value.parser(); + let (modes, messages) = match delivery { + Delivery::External => { + let CommonMsgInfo::ExtIn(info) = &envelope.info else { + panic!("an external request must use an external envelope"); + }; + assert_eq!(info.dst, source.as_address().to_msg_address_int()); + let (request, _) = WalletExtMsgBody::read_signed(&mut body) + .expect("external wallet request decodes"); + (request.msgs_modes, request.msgs) + } + Delivery::Internal => { + let CommonMsgInfo::Int(info) = &envelope.info else { + panic!("an internal request must use an internal envelope"); + }; + assert_eq!(info.dst, source.as_address().to_msg_address()); + let (request, _) = + ton::ton_wallet::WalletInternalSignedBody::read_signed(&mut body) + .expect("internal wallet request decodes"); + (request.msgs_modes, request.msgs) + } + }; + assert_eq!(modes.len(), messages.len()); + modes + .into_iter() + .zip(messages.iter().map(read_whole_message)) + .collect() + } + + /// Reads one message cell and requires that nothing follows the message. + fn read_whole_message(cell: &TonCell) -> Msg { + let mut parser = cell.parser(); + let message = Msg::::read(&mut parser).expect("message decodes"); + parser + .ensure_empty() + .expect("message has no trailing bits or references"); + message + } + + /// Keeps a signer's intent refusal and fails on any other signing error. + fn refusal(result: Result) -> Result { + result.map_err(|error| { + let TransferError::InvalidIntent(refusal) = error else { + panic!("unexpected signing error: {error}"); + }; + refusal + }) + } + + /// The outcome expected from signing one served `mode`: its exact mode, or + /// the named refusal. + fn expected_signing( + mode: i32, + refusal: Option, + ) -> Result, SendIntentError> { + refusal.map_or_else( + || Ok(vec![mode]), + |reason| Err(SendIntentError::UnsupportedSendMode { mode, reason }), + ) + } + + /// A served contract's code cell, with children, and its distinct data cell. + fn served_contract_cells() -> (TonCell, TonCell) { + let code = bytes_cell( + &[0xc0, 0xde], + vec![ + bytes_cell(&[0x01], Vec::new()), + bytes_cell(&[0x02], vec![bytes_cell(&[0x6c], Vec::new())]), + ], + ); + let data = bytes_cell(&[0xda, 0x7a], vec![bytes_cell(&[0x03], Vec::new())]); + (code, data) + } + + /// Builds an ordinary cell from whole bytes and child references. + fn bytes_cell(bytes: &[u8], children: Vec) -> TonCell { + let mut cell = TonCell::builder(); + cell.write_bits(bytes, bytes.len() * 8) + .expect("bytes fit one cell"); + for child in children { + cell.write_ref(child).expect("child reference fits"); } + cell.build().expect("cell builds") } } diff --git tests/scenarios/send.rs tests/scenarios/send.rs index 86292f7..c64046e 100644 --- tests/scenarios/send.rs +++ tests/scenarios/send.rs @@ -216,6 +216,8 @@ fn preview_rejects_an_amount_larger_than_the_fresh_balance() { WalletClientError::InsufficientBalance { available_nanograms: decimal(grams(1).as_nanograms()), requested_nanograms: decimal(grams(100).as_nanograms()), + operation_fee_nanograms: None, + operation_spend_nanograms: None, }, )) .then(protected_secret_was_not_read()) @@ -530,6 +532,8 @@ fn exact_preview_rejects_a_value_that_leaves_no_balance_for_fees() { available_nanograms: decimal("1000000000"), requested_nanograms: decimal("1000000000"), estimated_fee_nanograms: decimal("1000000"), + operation_fee_nanograms: None, + operation_spend_nanograms: None, }, )) .then(protected_secret_was_not_read()) @@ -555,6 +559,8 @@ fn exact_preview_requires_a_positive_remainder_after_the_estimated_fee() { available_nanograms: decimal("1000000000"), requested_nanograms: decimal("999000000"), estimated_fee_nanograms: decimal("1000000"), + operation_fee_nanograms: None, + operation_spend_nanograms: None, }, )) .then(protected_secret_was_not_read()) @@ -1433,6 +1439,8 @@ fn zero_balance_is_reported_as_insufficient_for_a_positive_transfer() { WalletClientError::InsufficientBalance { available_nanograms: decimal("0"), requested_nanograms: decimal("1"), + operation_fee_nanograms: None, + operation_spend_nanograms: None, }, )) .run(); @@ -1526,6 +1534,8 @@ fn amount_larger_than_the_fresh_balance_fails_before_signing() { WalletClientError::InsufficientBalance { available_nanograms: decimal(grams(1).as_nanograms()), requested_nanograms: decimal(grams(100).as_nanograms()), + operation_fee_nanograms: None, + operation_spend_nanograms: None, }, )) .then(snapshot().send_phase(SendPhase::Failed)) diff --git tests/support/host.rs tests/support/host.rs index 8bc0f85..f8c977e 100644 --- tests/support/host.rs +++ tests/support/host.rs @@ -496,6 +496,17 @@ impl ScenarioHttpHost { } let rejected = state.emulation_rejected; drop(state); + let mut action = json!({ + "success": !rejected, + "result_code": if rejected { 34 } else { 0 } + }); + if !rejected { + // A created transfer reports the delivery of its message; every + // scenario preview sends exactly one. + action["tot_actions"] = json!(1); + action["skipped_actions"] = json!(0); + action["msgs_created"] = json!(1); + } Ok(response( request, json!({ @@ -512,10 +523,7 @@ impl ScenarioHttpHost { "success": !rejected, "exit_code": if rejected { 33 } else { 0 } }, - "action": { - "success": !rejected, - "result_code": if rejected { 34 } else { 0 } - } + "action": action } } }, diff --git tests/support/scenario.rs tests/support/scenario.rs index 67d7e7d..e91dbd9 100644 --- tests/support/scenario.rs +++ tests/support/scenario.rs @@ -1719,8 +1719,10 @@ impl ScenarioRunner { }), bounce: false, state_init: None, + send_mode: None, }], }, + estimate_shortfall: false, }; std::thread::spawn(move || { let result = block_on(client.preview_send(request)); @@ -1750,6 +1752,7 @@ impl ScenarioRunner { }), bounce: false, state_init: None, + send_mode: None, }], }, }; diff --git tests/support/ton_connect_scenario.rs tests/support/ton_connect_scenario.rs index a5f9ef2..7be884c 100644 --- tests/support/ton_connect_scenario.rs +++ tests/support/ton_connect_scenario.rs @@ -1769,6 +1769,7 @@ impl ScenarioRunner { .as_ref() .map(|value| Boc::try_from(value.as_bytes().to_vec())) .transpose()?, + send_mode: None, }) }) .collect::>>()?; diff --git tests/support/wallet_lifecycle_scenario.rs tests/support/wallet_lifecycle_scenario.rs index 2fd9f50..669ba87 100644 --- tests/support/wallet_lifecycle_scenario.rs +++ tests/support/wallet_lifecycle_scenario.rs @@ -682,6 +682,7 @@ pub(crate) fn execute_key_rotation_shares_send_slot_on_localnet() -> Result<(), body: SendMessageBody::Empty, bounce: false, state_init: None, + send_mode: None, }], }, }; diff --git vendor/ton/src/block_tlb/state_init.rs vendor/ton/src/block_tlb/state_init.rs index 43f7877..856afa4 100644 --- vendor/ton/src/block_tlb/state_init.rs +++ vendor/ton/src/block_tlb/state_init.rs @@ -4,12 +4,22 @@ use crate::tlb_adapters::TLBHashMapE; use crate::ton_core::types::tlb_core::adapters::ConstLen; use std::collections::HashMap; use ton_core::TLB; -use ton_core::cell::{TonCell, TonHash}; +use ton_core::bail_ton_core_data; +use ton_core::cell::{CellBuilder, CellParser, TonCell, TonHash}; use ton_core::errors::TonCoreError; use ton_core::traits::tlb::TLB; use ton_core::types::TonAddress; use ton_core::types::tlb_core::TLBRef; +/// Libraries a `StateInit` may carry when it is written. +/// +/// Reading is bound by the dictionary walk budget alone, chain data is parsed whatever it +/// carries. Writing builds the dictionary again from the parsed map, a new cell tree per +/// entry (about 3.7 KB and 3.4 us each), and a wallet request attaches a caller-supplied +/// `StateInit` to each of up to 255 messages: a 97-byte dictionary of shared cells would be +/// written back as 32768 entries per message. A deployment carries none, rarely a few. +pub const STATE_INIT_MAX_WRITTEN_LIBS: usize = 16; + // https://github.com/ton-blockchain/ton/blob/59a8cf0ae5c3062d14ec4c89a04fee80b5fd05c1/crypto/block/block.tlb#L281 #[derive(Debug, Clone, PartialEq, TLB)] pub struct StateInit { @@ -18,10 +28,37 @@ pub struct StateInit { pub tick_tock: Option, pub code: Option>, pub data: Option>, - #[tlb(adapter = "TLBHashMapE::>::new(256)")] + #[tlb(adapter = "StateInitLibs")] pub library: HashMap, } +/// `library:(HashmapE 256 SimpleLib)` that refuses to write more than the limit above. +struct StateInitLibs; + +impl StateInitLibs { + fn dict() -> TLBHashMapE> { + TLBHashMapE::new(256) + } + + fn read(&self, parser: &mut CellParser) -> Result, TonCoreError> { + Self::dict().read(parser) + } + + fn write( + &self, + builder: &mut CellBuilder, + libs: &HashMap, + ) -> Result<(), TonCoreError> { + if libs.len() > STATE_INIT_MAX_WRITTEN_LIBS { + bail_ton_core_data!( + "StateInit with {} libraries can't be written: limit is {STATE_INIT_MAX_WRITTEN_LIBS}", + libs.len() + ); + } + Self::dict().write(builder, libs) + } +} + #[derive(Debug, Clone, PartialEq, TLB)] pub struct SimpleLib { pub public: bool, @@ -57,8 +94,10 @@ impl StateInit { #[cfg(test)] mod tests { use super::*; + use crate::block_tlb::{CommonMsgInfoInt, Msg}; use std::str::FromStr; use ton_core::cell::TonCell; + use ton_core::types::tlb_core::{EitherRefLayout, TLBEitherRef}; #[test] fn test_state_init_regular_contract() -> anyhow::Result<()> { @@ -96,4 +135,67 @@ mod tests { assert_eq!(address, exp_addr); Ok(()) } + + fn state_init_with_libs(count: usize) -> anyhow::Result { + let mut state_init = StateInit::new(TonCell::empty().clone(), TonCell::empty().clone()); + for index in 0..count as u32 { + let mut builder = TonCell::builder(); + builder.write_num(&index, 32)?; + let root = builder.build()?; + let lib = SimpleLib { + public: index % 2 == 0, + root: root.clone().into(), + }; + assert!( + state_init + .library + .insert(root.hash()?.clone(), lib) + .is_none() + ); + } + Ok(state_init) + } + + #[test] + fn test_state_init_written_libs_limit() -> anyhow::Result<()> { + let at_limit = state_init_with_libs(STATE_INIT_MAX_WRITTEN_LIBS)?; + assert_eq!(StateInit::from_boc(at_limit.to_boc()?)?, at_limit); + + let over_limit = state_init_with_libs(STATE_INIT_MAX_WRITTEN_LIBS + 1)?; + let err = over_limit.to_cell().unwrap_err().to_string(); + assert!(err.contains("17 libraries can't be written"), "{err}"); + assert!(over_limit.to_boc().is_err()); + assert!(over_limit.cell_hash().is_err()); + + // the message that would carry it is refused as a whole, inline or by reference + let mut msg = Msg::new(CommonMsgInfoInt::default(), TonCell::empty().clone()); + msg.init = Some(TLBEitherRef::new(over_limit.clone())); + assert!(msg.to_cell().is_err()); + msg.init = Some(TLBEitherRef::new_with_layout( + over_limit.clone(), + EitherRefLayout::ToRef, + )); + assert!(msg.to_cell().is_err()); + msg.init = Some(TLBEitherRef::new(at_limit)); + assert_eq!(Msg::::from_cell(&msg.to_cell()?)?.init, msg.init); + Ok(()) + } + + #[test] + fn test_state_init_reads_more_libs_than_it_writes() -> anyhow::Result<()> { + // chain data: _ split_depth:(Maybe (## 5)) special:(Maybe TickTock) code:(Maybe ^Cell) + // data:(Maybe ^Cell) library:(HashmapE 256 SimpleLib), written without the limit + let expected = state_init_with_libs(300)?; + let mut builder = TonCell::builder(); + builder.write_num(&0b0011u8, 4)?; + builder.write_ref(TonCell::empty().clone())?; + builder.write_ref(TonCell::empty().clone())?; + StateInitLibs::dict().write(&mut builder, &expected.library)?; + let cell = builder.build()?; + + let parsed = StateInit::from_cell(&cell)?; + assert_eq!(parsed, expected); + assert!(parsed.to_cell().is_err()); + Ok(()) + } } diff --git vendor/ton/src/tlb_adapters.rs vendor/ton/src/tlb_adapters.rs index a17be18..b00a7bc 100644 --- vendor/ton/src/tlb_adapters.rs +++ vendor/ton/src/tlb_adapters.rs @@ -1,5 +1,6 @@ mod bin_tree; mod dict; +mod node_budget; pub use bin_tree::*; pub use dict::*; diff --git vendor/ton/src/tlb_adapters/bin_tree.rs vendor/ton/src/tlb_adapters/bin_tree.rs index 3170e67..4ab7bdd 100644 --- vendor/ton/src/tlb_adapters/bin_tree.rs +++ vendor/ton/src/tlb_adapters/bin_tree.rs @@ -1,5 +1,6 @@ use crate::block_tlb::ShardPfx; use crate::tlb_adapters::DictValAdapter; +use crate::tlb_adapters::node_budget::WalkBudget; use std::collections::HashMap; use std::marker::PhantomData; use ton_core::bail_ton_core_data; @@ -22,8 +23,10 @@ impl BinTree { } pub fn read(parser: &mut CellParser) -> Result, TonCoreError> { + // the depth limit alone leaves 2^60 paths over cells that share subtrees + let budget = WalkBudget::enter(); let mut val = HashMap::new(); - Self::read_impl(parser, ShardPfx::default(), &mut val)?; + Self::read_impl(parser, ShardPfx::default(), &mut val, &budget)?; Ok(val) } @@ -31,7 +34,9 @@ impl BinTree { parser: &mut CellParser, cur_key: ShardPfx, cur_val: &mut HashMap, + budget: &WalkBudget, ) -> Result<(), TonCoreError> { + budget.visit_node()?; if cur_key.bits_len > TON_MAX_SPLIT_DEPTH as u32 { bail_ton_core_data!( "[read] BinTree depth exceeded: {} > {TON_MAX_SPLIT_DEPTH}", @@ -48,13 +53,23 @@ impl BinTree { value: cur_key.value, bits_len: new_bits_len, }; - Self::read_impl(&mut parser.read_next_ref()?.parser(), left_key, cur_val)?; + Self::read_impl( + &mut parser.read_next_ref()?.parser(), + left_key, + cur_val, + budget, + )?; let right_key = ShardPfx { value: cur_key.value | (1 << (64 - new_bits_len)), bits_len: new_bits_len, }; - Self::read_impl(&mut parser.read_next_ref()?.parser(), right_key, cur_val)?; + Self::read_impl( + &mut parser.read_next_ref()?.parser(), + right_key, + cur_val, + budget, + )?; Ok(()) } @@ -169,4 +184,23 @@ mod tests { assert_eq!(data, parsed_data); Ok(()) } + + #[test] + fn test_bin_tree_shared_cells_walk_is_bounded() -> anyhow::Result<()> { + // bt_leaf$0 under 60 levels of bt_fork$1 whose two references are one cell: 2^60 paths + let mut builder = TonCell::builder(); + builder.write_bit(false)?; + builder.write_num(&7u32, 32)?; + let mut node = builder.build()?; + for _ in 0..TON_MAX_SPLIT_DEPTH { + let mut builder = TonCell::builder(); + builder.write_bit(true)?; + builder.write_ref(node.clone())?; + builder.write_ref(node)?; + node = builder.build()?; + } + let result = BinTree::>::read(&mut node.parser()); + assert!(result.is_err_and(|err| err.to_string().contains("Too many nodes"))); + Ok(()) + } } diff --git vendor/ton/src/tlb_adapters/dict/data_parser.rs vendor/ton/src/tlb_adapters/dict/data_parser.rs index fee4250..0637811 100644 --- vendor/ton/src/tlb_adapters/dict/data_parser.rs +++ vendor/ton/src/tlb_adapters/dict/data_parser.rs @@ -2,8 +2,10 @@ use std::collections::HashMap; use super::label_type::DictLabelType; use crate::tlb_adapters::DictValAdapter; +use crate::tlb_adapters::node_budget::WalkBudget; use num_bigint::BigUint; use num_traits::One; +use ton_core::bail_ton_core_data; use ton_core::cell::CellParser; use ton_core::errors::TonCoreError; use ton_core::traits::tlb::TLB; @@ -29,8 +31,10 @@ impl DictDataParser { // reset state in case of reusing self.cur_key_prefix = BigUint::one(); + // the cells are untrusted and may share subtrees: the walk is bounded, not the BoC + let budget = WalkBudget::enter(); let mut result = HashMap::new(); - self.parse_impl::(parser, &mut result)?; + self.parse_impl::(parser, &mut result, &budget)?; Ok(result) } @@ -38,16 +42,21 @@ impl DictDataParser { &mut self, parser: &mut CellParser, dst: &mut HashMap, + budget: &WalkBudget, ) -> Result<(), TonCoreError> { + budget.visit_node()?; + // will rollback prefix to original value at the end of the function let origin_key_prefix_len = self.cur_key_prefix.bits(); + // a label is never longer than the key bits not consumed yet (HmLabel ~n m, n <= m): + // every length below is checked against it before it sizes a shift or an allocation + let key_bits_left = self.key_bits_left()?; let label_type = self.detect_label_type(parser)?; match label_type { DictLabelType::Same => { let prefix_val = parser.read_bit()?; - let prefix_len_len = self.remain_suffix_bit_len(); - let prefix_len = parser.read_num::(prefix_len_len)?; + let prefix_len = Self::read_label_len(parser, key_bits_left)?; if prefix_val { self.cur_key_prefix += 1u32; self.cur_key_prefix <<= prefix_len; @@ -57,35 +66,36 @@ impl DictDataParser { } } DictLabelType::Short => { - let prefix_len = UnaryLen::read(parser)?; - if *prefix_len != 0 { - let val = parser.read_num::(*prefix_len)?; - self.cur_key_prefix <<= *prefix_len; + let prefix_len = *UnaryLen::read(parser)?; + Self::check_label_len(prefix_len, key_bits_left)?; + if prefix_len != 0 { + let val = parser.read_num::(prefix_len)?; + self.cur_key_prefix <<= prefix_len; self.cur_key_prefix |= val; } } DictLabelType::Long => { - let prefix_len_len = self.remain_suffix_bit_len(); - let prefix_len: usize = parser.read_num(prefix_len_len)?; - if prefix_len_len != 0 { + let prefix_len = Self::read_label_len(parser, key_bits_left)?; + if prefix_len != 0 { let val: BigUint = parser.read_num(prefix_len)?; self.cur_key_prefix <<= prefix_len; self.cur_key_prefix |= val; } } } - if self.cur_key_prefix.bits() as usize == (self.key_bits_len + 1) { + // the label fits the key, so the prefix is the whole key (a leaf) or shorter (a fork) + if self.key_bits_left()? == 0 { let mut key = BigUint::one() << self.key_bits_len; key ^= &self.cur_key_prefix; dst.insert(key, VA::read(parser)?); } else { let left_ref = parser.read_next_ref()?; self.cur_key_prefix <<= 1; - self.parse_impl::(&mut left_ref.parser(), dst)?; + self.parse_impl::(&mut left_ref.parser(), dst, budget)?; let right_ref = parser.read_next_ref()?; self.cur_key_prefix += BigUint::one(); - self.parse_impl::(&mut right_ref.parser(), dst)?; + self.parse_impl::(&mut right_ref.parser(), dst, budget)?; } self.cur_key_prefix >>= self.cur_key_prefix.bits() - origin_key_prefix_len; Ok(()) @@ -104,9 +114,218 @@ impl DictDataParser { Ok(label) } - fn remain_suffix_bit_len(&self) -> usize { - // add 2 because cur_prefix contains leading bit - let prefix_len_left = self.key_bits_len - self.cur_key_prefix.bits() as usize + 2; - (prefix_len_left as f32).log2().ceil() as usize + /// Key bits not consumed yet on the path to the current node. + fn key_bits_left(&self) -> Result { + // cur_key_prefix contains leading bit + let consumed = self.cur_key_prefix.bits().saturating_sub(1); + match (self.key_bits_len as u64).checked_sub(consumed) { + Some(left) => Ok(left as usize), + None => bail_ton_core_data!( + "Dict key prefix is longer than the key: {consumed} > {}", + self.key_bits_len + ), + } + } + + /// Reads `n:(#<= m)` of a long or same label, `m` being the key bits left. + fn read_label_len( + parser: &mut CellParser, + key_bits_left: usize, + ) -> Result { + let label_len = parser.read_num::(Self::label_len_bits(key_bits_left))?; + Self::check_label_len(label_len, key_bits_left)?; + Ok(label_len) + } + + /// Width of `#<= m`: as many bits as `m` itself takes, that is ceil(log2(m + 1)). + fn label_len_bits(key_bits_left: usize) -> usize { + (usize::BITS - key_bits_left.leading_zeros()) as usize + } + + fn check_label_len(label_len: usize, key_bits_left: usize) -> Result<(), TonCoreError> { + if label_len > key_bits_left { + bail_ton_core_data!( + "Dict label is longer than the key bits left: {label_len} > {key_bits_left}" + ); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::block_tlb::{AccountState, MaybeAccount, ShardAccount, StateInit}; + use crate::tlb_adapters::DictValAdapterNum; + use crate::tlb_adapters::node_budget::MAX_WALK_NODES; + use std::time::{Duration, Instant}; + use ton_core::cell::TonCell; + + // WC-2b: the library dictionary of a StateInit whose `same` label is longer than the key, + // followed by a fork: the next length was sized from a wrapped subtraction (2^61 bytes). + const WC2B_STATE_INIT: &str = "te6ccgEBAwEAXwABAQwBApd/////////////////////////////////////////////////+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAgIAEd//////////8A=="; + // WC-2: a well-formed library dictionary of 27 cells, 24 forks deep, both references of + // every fork being the same cell: 2^24 keys. + const WC2_STATE_INIT: &str = "te6ccgEBGwEAtgABAQwBAgFIAgICAUgDAwIBSAQEAgFIBQUCAUgGBgIBSAcHAgFICAgCAUgJCQIBSAoKAgFICwsCAUgMDAIBSA0NAgFIDg4CAUgPDwIBSBAQAgFIERECAUgSEgIBSBMTAgFIFBQCAUgVFQIBSBYWAgFIFxcCAUgYGAIBSBkZAWl//////////////////////////////////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBoAAA=="; + // far above what the refused inputs take, far below what they took before + const FAIL_FAST: Duration = Duration::from_secs(5); + + type U8Val = DictValAdapterNum; + + fn read_u8_dict( + key_bits_len: usize, + root: &TonCell, + ) -> Result, TonCoreError> { + DictDataParser::new(key_bits_len).read::(&mut root.parser()) + } + + fn cell(bits: &str, refs: &[&TonCell]) -> anyhow::Result { + let mut builder = TonCell::builder(); + for bit in bits.chars().filter(|bit| !bit.is_whitespace()) { + builder.write_bit(bit == '1')?; + } + for cell_ref in refs { + builder.write_ref((*cell_ref).clone())?; + } + Ok(builder.build()?) + } + + /// A dictionary of `depth`-bit keys made of `depth + 1` cells: every fork has an empty + /// label and points twice at the next cell, the single leaf holds 0xAB. + fn shared_tree(depth: usize) -> anyhow::Result { + let mut node = cell("00 10101011", &[])?; + for _ in 0..depth { + node = cell("00", &[&node, &node])?; + } + Ok(node) + } + + fn assert_refused(result: Result, expected: &str) { + match result { + Ok(_) => panic!("must be refused: {expected}"), + Err(err) => assert!( + err.to_string().contains(expected), + "unexpected error: {err}" + ), + } + } + + #[test] + fn test_dict_wc2b_label_longer_than_key_is_refused() { + let started = Instant::now(); + let result = StateInit::from_boc_base64(WC2B_STATE_INIT); + assert_refused( + result, + "Dict label is longer than the key bits left: 300 > 256", + ); + assert!(started.elapsed() < FAIL_FAST); + } + + #[test] + fn test_dict_wc2_shared_cells_walk_is_bounded() { + let started = Instant::now(); + let result = StateInit::from_boc_base64(WC2_STATE_INIT); + assert_refused(result, "Too many nodes on the paths of a dict"); + assert!(started.elapsed() < FAIL_FAST); + } + + #[test] + fn test_dict_label_len_is_bound_for_every_label_type() -> anyhow::Result<()> { + // hml_same$11 v:Bit n:(#<= 8): n = 9 + assert_refused(read_u8_dict(8, &cell("11 0 1001", &[])?), "9 > 8"); + // hml_long$10 n:(#<= 8) s:(n * Bit): n = 15, the bits are there + let long = cell("10 1111 111111111111111 00000000", &[])?; + assert_refused(read_u8_dict(8, &long), "15 > 8"); + // hml_short$0 len:(Unary ~n) s:(n * Bit): n = 9 + let short = cell("0 1111111110 000000000 00000000", &[])?; + assert_refused(read_u8_dict(8, &short), "9 > 8"); + + // below a fork one key bit is gone: the label is checked against what is left + let leaf = cell("11 0 1001 00000000", &[])?; + assert_refused(read_u8_dict(9, &cell("00", &[&leaf, &leaf])?), "9 > 8"); + let leaf = cell("0 111111110 00000000 00000000", &[])?; + assert_refused(read_u8_dict(8, &cell("00", &[&leaf, &leaf])?), "8 > 7"); + let leaf = cell("11 0 111 00000000", &[])?; + assert_eq!(read_u8_dict(8, &cell("00", &[&leaf, &leaf])?)?.len(), 2); + + // the whole key in one label of each type is a leaf + let expected = HashMap::from([(BigUint::from(0xFFu32), 0x5Au8)]); + for bits in [ + "11 1 1000 01011010", + "10 1000 11111111 01011010", + "0 111111110 11111111 01011010", + ] { + assert_eq!(read_u8_dict(8, &cell(bits, &[])?)?, expected, "{bits}"); + } + // a label that ends before the key does needs a fork + assert!(read_u8_dict(8, &cell("11 1 0111 01011010", &[])?).is_err()); + Ok(()) + } + + #[test] + fn test_dict_label_len_width_matches_the_builder() { + // data_builder.rs: (key_bits_len_left as f32 + 1.0).log2().ceil() + for key_bits_left in 0..=4096usize { + let expected = (key_bits_left as f32 + 1.0).log2().ceil() as usize; + assert_eq!( + DictDataParser::label_len_bits(key_bits_left), + expected, + "{key_bits_left}" + ); + } + } + + #[test] + fn test_dict_walk_budget() -> anyhow::Result<()> { + // a complete 15-bit dictionary is 2^16 - 1 nodes: the largest one inside the budget + assert_eq!(MAX_WALK_NODES, 1 << 16); + let dict = read_u8_dict(15, &shared_tree(15)?)?; + assert_eq!(dict.len(), 1 << 15); + assert!(dict.values().all(|value| *value == 0xAB)); + + for depth in [16, 24, 64, 256] { + let started = Instant::now(); + assert_refused(read_u8_dict(depth, &shared_tree(depth)?), "Too many nodes"); + assert!(started.elapsed() < FAIL_FAST, "depth {depth}"); + } + + // nothing is left over for the next dictionary on this thread + assert_eq!(read_u8_dict(15, &shared_tree(15)?)?.len(), 1 << 15); + Ok(()) + } + + #[test] + fn test_dict_state_init_without_library() -> anyhow::Result<()> { + // state_init for UQCJ7Quj9gM_SE3uwOk3gEJC2JFQcgg0s7CSpLr7B_2yiHPG (see state_init.rs) + let boc_hex = "b5ee9c720102160100030400020134020100510000082f29a9a31738dd3a33f904d35e2f4f6f9af2d2f9c563c05faa6bb0b12648d5632083ea3f89400114ff00f4a413f4bcf2c80b03020120090404f8f28308d71820d31fd31fd31f02f823bbf264ed44d0d31fd31fd3fff404d15143baf2a15151baf2a205f901541064f910f2a3f80024a4c8cb1f5240cb1f5230cbff5210f400c9ed54f80f01d30721c0009f6c519320d74a96d307d402fb00e830e021c001e30021c002e30001c0039130e30d03a4c8cb1f12cb1fcbff08070605000af400c9ed54006c810108d718fa00d33f305224810108f459f2a782106473747270748018c8cb05cb025005cf165003fa0213cb6acb1f12cb3fc973fb000070810108d718fa00d33fc8542047810108f451f2a782106e6f746570748018c8cb05cb025006cf165004fa0214cb6a12cb1fcb3fc973fb0002006ed207fa00d4d422f90005c8ca0715cbffc9d077748018c8cb05cb0222cf165005fa0214cb6b12ccccc973fb00c84014810108f451f2a702020148130a0201200c0b0059bd242b6f6a2684080a06b90fa0218470d4080847a4937d29910ce6903e9ff9837812801b7810148987159f31840201200e0d0011b8c97ed44d0d70b1f8020158120f02012011100019af1df6a26840106b90eb858fc00019adce76a26840206b90eb85ffc0003db29dfb513420405035c87d010c00b23281f2fff274006040423d029be84c6002e6d001d0d3032171b0925f04e022d749c120925f04e002d31f218210706c7567bd22821064737472bdb0925f05e003fa403020fa4401c8ca07cbffc9d0ed44d0810140d721f404305c810108f40a6fa131b3925f07e005d33fc8258210706c7567ba923830e30d03821064737472ba925f06e30d1514008a5004810108f45930ed44d0810140d720c801cf16f400c9ed540172b08e23821064737472831eb17080185005cb055003cf1623fa0213cb6acb1fcb3fc98040fb00925f03e2007801fa00f40430f8276f2230500aa121bef2e0508210706c7567831eb17080185004cb0526cf1658fa0219f400cb6917cb1f5260cb3f20c98040fb0006"; + let source = TonCell::from_boc_hex(boc_hex)?; + let state_init = StateInit::from_boc_hex(boc_hex)?; + assert!(state_init.code.is_some() && state_init.data.is_some()); + assert!(state_init.library.is_empty()); + assert_eq!(state_init.to_cell()?, source); + Ok(()) + } + + #[test] + fn test_dict_state_init_with_library() -> anyhow::Result<()> { + // the masterchain account of test_block_tlb_shard_account_tick_tock (shard_account.rs) + let account_boc_hex = "b5ee9c7201020d0100017500015099602ce40fd84286bddb06f8bcc9fceb7e3027f9826c8985017f16cba12363cc000016e2cc89c18101036fcff34517c7bdf5187c55af4f8b61fdc321588c7ab768dee24b006df29106458d7cf21881f4800000000000005b8b322706090311d3e017f009080202016206030142bf412429205ea66d6f2004edfa570f6f56b3e85e59baa1befbc73b7da5d55bdc61040104123405000456780142bf5a2eef5056775f5b9572ff3ad63dd2a71d1fb281ca177a5e1c74730eccb2e51307000fabacabadabacaba8004811fd096c00000000000000000000000000000000000000000000000000000000000000000114ff00f4a413f4a0f2c80b0a0201200c0b00dfa5ffff76a268698fe9ffe8e42c5267858f90e785ffe4f6aa6467c444ffb365ffc10802faf0807d014035e7a064b87d804077e7857fc10803dfd2407d014035e7a064b86467cd8903a32b9ba4410803ade68afd014035e7a045ea432b6363796103bb7b9363210c678b64b87d807d80400002d2"; + let shard_account = ShardAccount::from_boc_hex(account_boc_hex)?; + let MaybeAccount::Account(account) = &*shard_account.account else { + panic!("the account must exist"); + }; + let AccountState::Active(active) = &account.storage.state else { + panic!("the account must be active"); + }; + let state_init = &active.state_init; + assert_eq!(state_init.library.len(), 2); + + // the same StateInit on its own, as a message carries it + let state_init_boc = state_init.to_boc()?; + let parsed = StateInit::from_boc(state_init_boc.clone())?; + assert_eq!(&parsed, state_init); + assert_eq!(parsed.to_boc()?, state_init_boc); + + Ok(()) } } diff --git vendor/ton/src/tlb_adapters/node_budget.rs vendor/ton/src/tlb_adapters/node_budget.rs new file mode 100644 index 0000000..7a1a981 --- /dev/null +++ vendor/ton/src/tlb_adapters/node_budget.rs @@ -0,0 +1,100 @@ +//! Work bound for the recursive readers of untrusted cell trees (`Hashmap`, `BinTree`). +//! +//! Cells form a DAG: a few dozen cells whose two references point at the same child +//! describe a tree with 2^depth distinct paths. A reader that follows every path has to +//! bound its own work, the size of the BoC it was given bounds nothing. + +use std::cell::Cell; +use ton_core::bail_ton_core_data; +use ton_core::errors::TonCoreError; + +/// Nodes (forks and leaves) that one outermost read may visit, dictionaries nested in its +/// values included. A complete 15-bit dictionary (the widest key space of the fixed-size +/// dictionaries in a transaction, `out_msgs`) has 2^16 - 1 nodes. +pub(crate) const MAX_WALK_NODES: usize = 1 << 16; + +thread_local! { + // (reads active on this thread, nodes left for the outermost of them) + static WALK: Cell<(usize, usize)> = const { Cell::new((0, 0)) }; +} + +/// Scope of one read. A read started inside another one (a dictionary in a dictionary +/// value) draws from the budget of the outermost read, so nesting can't multiply it. +pub(crate) struct WalkBudget(()); + +impl WalkBudget { + pub(crate) fn enter() -> Self { + WALK.with(|walk| { + let (depth, left) = walk.get(); + walk.set(if depth == 0 { + (1, MAX_WALK_NODES) + } else { + (depth + 1, left) + }); + }); + Self(()) + } + + /// Accounts one visited node, fails when the budget of the outermost read is spent. + pub(crate) fn visit_node(&self) -> Result<(), TonCoreError> { + WALK.with(|walk| { + let (depth, left) = walk.get(); + let Some(left) = left.checked_sub(1) else { + bail_ton_core_data!( + "Too many nodes on the paths of a dict: limit is {MAX_WALK_NODES}" + ); + }; + walk.set((depth, left)); + Ok(()) + }) + } +} + +impl Drop for WalkBudget { + fn drop(&mut self) { + WALK.with(|walk| { + let (depth, left) = walk.get(); + walk.set((depth.saturating_sub(1), left)); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spend(budget: &WalkBudget, nodes: usize) -> Result<(), TonCoreError> { + (0..nodes).try_for_each(|_| budget.visit_node()) + } + + #[test] + fn test_walk_budget_is_per_outermost_read() -> anyhow::Result<()> { + for _ in 0..2 { + let budget = WalkBudget::enter(); + spend(&budget, MAX_WALK_NODES)?; + assert!(budget.visit_node().is_err()); + } + Ok(()) + } + + #[test] + fn test_walk_budget_is_shared_with_nested_reads() -> anyhow::Result<()> { + let outer = WalkBudget::enter(); + spend(&outer, MAX_WALK_NODES - 10)?; + { + let nested = WalkBudget::enter(); + spend(&nested, 7)?; + } + { + let nested = WalkBudget::enter(); + spend(&nested, 3)?; + assert!(nested.visit_node().is_err()); + } + assert!(outer.visit_node().is_err()); + drop(outer); + + let next = WalkBudget::enter(); + spend(&next, MAX_WALK_NODES)?; + Ok(()) + } +}