Skip to main content

quai_browser/browser/
wallet_send.rs

1//! Explicit wallet-mediated sends; reported hashes are verified by later reads.
2use super::*;
3use quai_consensus::{QuaiTransaction, SignedQuaiTransaction};
4use quai_primitives::Hash32;
5use quai_provider::{Inclusion, Provider, ProviderError};
6
7/// Original request identity to retain before awaiting a wallet-mediated send.
8/// The signing digest is NOT a transaction ID. A wallet can change fields in its
9/// approval flow; after an unknown outcome this identity alone cannot prove reuse safe.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11#[non_exhaustive]
12pub struct WalletSendIdentity {
13    /// Requested exposed account.
14    pub from: QuaiAddress,
15    /// Requested network.
16    pub chain_id: U256,
17    /// Requested nonce; observed wallet behavior is checked separately.
18    pub nonce: u64,
19    /// Digest of the complete requested unsigned transaction.
20    pub signing_digest: Hash32,
21}
22impl WalletSendIdentity {
23    /// Compute public recovery metadata without any wallet request.
24    pub fn new(from: QuaiAddress, transaction: &QuaiTransaction) -> Result<Self, BrowserError> {
25        Ok(Self {
26            from,
27            chain_id: transaction.chain_id,
28            nonce: transaction.nonce,
29            signing_digest: transaction
30                .signing_digest()
31                .map_err(|_| BrowserError::InvalidConfig)?,
32        })
33    }
34}
35/// Whether the adapter failed before dispatch or after submission could occur.
36#[derive(Debug, thiserror::Error)]
37#[non_exhaustive]
38pub enum WalletSendError {
39    /// No wallet transaction request was dispatched.
40    #[error("wallet transaction preflight failed: {0}")]
41    Preflight(#[source] BrowserError),
42    /// Wallet dispatch began. No retry or nonce/claim release is implied.
43    #[error("wallet transaction outcome is ambiguous: {source}")]
44    Ambiguous {
45        /// Original request metadata, not an expected signed transaction ID.
46        identity: WalletSendIdentity,
47        /// Hash returned before the failure, if it was structurally parseable.
48        /// It may have failed origin/ledger checks and is not a verified identity.
49        reported_hash: Option<Hash32>,
50        /// Sanitized cause, including numeric rejection or context change.
51        #[source]
52        source: BrowserError,
53    },
54}
55impl WalletSendError {
56    /// True after wallet dispatch may have occurred, including remote rejection.
57    pub fn acceptance_is_ambiguous(&self) -> bool {
58        matches!(self, Self::Ambiguous { .. })
59    }
60}
61/// Structurally valid wallet acknowledgement, pending independent transaction verification.
62/// Unlike raw submission, there was no locally signed payload from which to compute its ID.
63#[derive(Clone)]
64pub struct WalletSendAcknowledgement {
65    identity: WalletSendIdentity,
66    reported_hash: Hash32,
67    requested: QuaiTransaction,
68}
69impl fmt::Debug for WalletSendAcknowledgement {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        f.debug_struct("WalletSendAcknowledgement")
72            .field("identity", &self.identity)
73            .field("reported_hash", &self.reported_hash)
74            .finish()
75    }
76}
77impl WalletSendAcknowledgement {
78    /// Restore an unverified wallet-reported hash and original request after
79    /// restart or an ambiguous error. This does not assert that submission occurred.
80    /// Validates bounds and hash routing; `observe` still verifies signed identity.
81    pub fn from_reported_hash(
82        from: QuaiAddress,
83        requested: QuaiTransaction,
84        reported_hash: Hash32,
85    ) -> Result<Self, BrowserError> {
86        if requested.chain_id == U256::ZERO || !valid_hash(from, reported_hash) {
87            return Err(BrowserError::InvalidResult);
88        }
89        let identity = WalletSendIdentity::new(from, &requested)?;
90        Ok(Self {
91            identity,
92            reported_hash,
93            requested,
94        })
95    }
96    /// Original request metadata; no wallet changes have been accepted implicitly.
97    pub fn identity(&self) -> WalletSendIdentity {
98        self.identity
99    }
100    /// Wallet-reported hash for readonly lookup; not yet independently verified.
101    pub fn reported_hash(&self) -> Hash32 {
102        self.reported_hash
103    }
104    /// Exact original request, retained for comparison and application recovery.
105    pub fn requested_transaction(&self) -> &QuaiTransaction {
106        &self.requested
107    }
108    /// One readonly transaction lookup. None means not indexed yet, not dropped.
109    /// Cryptographically reconstructs the returned transaction and compares every
110    /// unsigned field and sender. No unbounded polling, retry or submission occurs.
111    pub async fn observe<T: Transport>(
112        &self,
113        provider: &Provider<T>,
114    ) -> Result<Option<WalletSendObservation>, ProviderError> {
115        let zone = self.identity.from.zone();
116        let actual = provider.chain_id(zone.into()).await?;
117        if actual != self.identity.chain_id {
118            return Err(ProviderError::ChainMismatch {
119                expected: self.identity.chain_id,
120                actual,
121            });
122        }
123        let Some(observed) = provider.transaction(zone, self.reported_hash).await? else {
124            return Ok(None);
125        };
126        let signed = observed.verified_quai()?;
127        let matches_request =
128            signed.from() == self.identity.from && signed.transaction() == &self.requested;
129        Ok(Some(WalletSendObservation {
130            signed,
131            matches_request,
132            inclusion: observed.inclusion,
133        }))
134    }
135}
136/// Independently verified transaction bytes and explicit comparison to the request.
137#[derive(Debug)]
138pub struct WalletSendObservation {
139    signed: SignedQuaiTransaction,
140    matches_request: bool,
141    inclusion: Option<Inclusion>,
142}
143impl WalletSendObservation {
144    /// Actual canonical signed transaction, verified against the reported hash.
145    pub fn signed(&self) -> &SignedQuaiTransaction {
146        &self.signed
147    }
148    /// Whether the wallet preserved every requested field and the requested sender.
149    pub fn matches_request(&self) -> bool {
150        self.matches_request
151    }
152    /// Node-claimed location only; canonical receipt/confirmation checks are separate.
153    pub fn inclusion(&self) -> Option<Inclusion> {
154        self.inclusion
155    }
156}
157impl InjectedProvider {
158    /// Explicitly ask the selected wallet to authorize, sign and send a populated
159    /// type-0 request using `quai_sendTransaction`. No offline-signing support is
160    /// required. Retain account/nonce/digest before awaiting in case of cancellation.
161    /// Wallets may alter fields in their approval flow: the returned acknowledgement
162    /// does not assert exact signing; call `observe` to verify and compare the result.
163    pub async fn send_quai_transaction(
164        &self,
165        address: QuaiAddress,
166        transaction: &QuaiTransaction,
167    ) -> Result<WalletSendAcknowledgement, WalletSendError> {
168        let params = self
169            .transaction_params(address, transaction, "quai_sendTransaction")
170            .map_err(WalletSendError::Preflight)?;
171        let identity =
172            WalletSendIdentity::new(address, transaction).map_err(WalletSendError::Preflight)?;
173        let revision = self.context_revision();
174        self.check_chain()
175            .await
176            .map_err(WalletSendError::Preflight)?;
177        let accounts = Self::accounts_from(
178            self.raw("quai_accounts", json!([]))
179                .await
180                .map_err(WalletSendError::Preflight)?,
181        )
182        .map_err(WalletSendError::Preflight)?;
183        if !accounts.contains(&address) {
184            return Err(WalletSendError::Preflight(BrowserError::AccountUnavailable));
185        }
186        if provider_changed(&self.watch.0, revision) {
187            return Err(WalletSendError::Preflight(BrowserError::ContextChanged));
188        }
189        let value = self
190            .raw("quai_sendTransaction", params)
191            .await
192            .map_err(|source| WalletSendError::Ambiguous {
193                identity,
194                reported_hash: None,
195                source,
196            })?;
197        let reported_hash = value.as_str().and_then(|s| s.parse::<Hash32>().ok());
198        self.verify_context(revision, Some(address))
199            .await
200            .map_err(|source| WalletSendError::Ambiguous {
201                identity,
202                reported_hash,
203                source,
204            })?;
205        let valid = reported_hash
206            .filter(|hash| valid_hash(address, *hash))
207            .ok_or(WalletSendError::Ambiguous {
208                identity,
209                reported_hash,
210                source: BrowserError::InvalidResult,
211            })?;
212        Ok(WalletSendAcknowledgement {
213            identity,
214            reported_hash: valid,
215            requested: transaction.clone(),
216        })
217    }
218}
219fn valid_hash(address: QuaiAddress, hash: Hash32) -> bool {
220    let bytes = hash.bytes();
221    hash != Hash32::ZERO
222        && bytes[0] == address.zone().byte()
223        && bytes[2] == address.zone().byte()
224        && bytes[1] & 0x80 == 0
225        && bytes[3] & 0x80 == 0
226}