Skip to main content

quai_provider/
deployment.rs

1//! Signed-intent-bound deployment/code observations, without finality claims.
2use crate::{
3    BlockReference, BlockTag, Provider, ProviderError, ReceiptOutcome, RpcData, TransactionKind,
4};
5use quai_consensus::SignedQuaiTransaction;
6use quai_primitives::{Hash32, QuaiAddress, Zone, contract_address};
7use quai_rpc::{Transport, U256};
8/// Exact locally signed creation intent and optional expected runtime-code hash.
9#[derive(Clone, Debug)]
10pub struct DeploymentReference {
11    chain: U256,
12    genesis: Hash32,
13    sender: QuaiAddress,
14    hash: Hash32,
15    address: QuaiAddress,
16    expected_runtime: Option<Hash32>,
17}
18impl DeploymentReference {
19    /// Bind only a direct CREATE transaction with a valid same-zone Quai result.
20    /// Runtime code is distinct from signed init code and must be supplied explicitly
21    /// when the application wants an expected-code comparison.
22    pub fn from_signed(
23        genesis: Hash32,
24        signed: &SignedQuaiTransaction,
25        expected_runtime: Option<Hash32>,
26    ) -> Result<Self, ProviderError> {
27        let tx = signed.transaction();
28        if genesis == Hash32::ZERO || tx.to.is_some() {
29            return Err(ProviderError::InvalidRequest(
30                "not a scoped direct deployment",
31            ));
32        }
33        let nonce = tx.nonce;
34        let address =
35            QuaiAddress::try_from(contract_address(signed.from().address(), nonce, &tx.data))
36                .map_err(|_| ProviderError::InvalidRequest("deployment address is not Quai"))?;
37        if address.zone() != signed.from().zone() {
38            return Err(ProviderError::InvalidRequest(
39                "deployment address is outside sender zone",
40            ));
41        }
42        Ok(Self {
43            chain: tx.chain_id,
44            genesis,
45            sender: signed.from(),
46            hash: signed
47                .hash()
48                .map_err(|_| ProviderError::InvalidRequest("invalid signed deployment"))?,
49            address,
50            expected_runtime,
51        })
52    }
53    /// Exact predicted created account for the signed nonce and complete init code.
54    pub fn address(&self) -> QuaiAddress {
55        self.address
56    }
57    /// Original signed creation hash.
58    pub fn transaction_hash(&self) -> Hash32 {
59        self.hash
60    }
61    /// Explicit origin zone.
62    pub fn zone(&self) -> Zone {
63        self.sender.zone()
64    }
65}
66/// Code in the source's state at the end of the canonical inclusion block.
67/// Empty code is preserved: successful creation does not guarantee deployed code.
68#[derive(Clone, Debug, PartialEq)]
69#[non_exhaustive]
70pub struct DeploymentCode {
71    /// Bounded runtime bytes, not init code. Debug reveals length only.
72    pub bytes: RpcData,
73    /// Keccak-256 of the exact runtime bytes, including the empty-code case.
74    pub hash: Hash32,
75    /// Comparison with the caller's expected runtime hash, when supplied.
76    pub matches_expected: Option<bool>,
77}
78/// Current source-reported direct deployment state.
79#[derive(Clone, Debug, PartialEq)]
80pub enum DeploymentObservation {
81    /// Receipt unavailable; a known transaction may be pending or indexed without
82    /// its receipt. Absence never establishes rejection or permission to retry payment.
83    NoReceipt {
84        /// Whether the source supplied the exact transaction hash.
85        transaction_known: bool,
86    },
87    /// Reported receipt inclusion does not match the current canonical-number view.
88    Noncanonical {
89        /// Receipt's inclusion claim.
90        reported: BlockReference,
91        /// Current canonical identity, when available.
92        canonical: Option<BlockReference>,
93    },
94    /// Canonical origin inclusion with its exact outcome and sampled depth.
95    Included {
96        /// Inclusion rechecked around code lookup.
97        block: BlockReference,
98        /// Source execution result. Only Succeeded causes runtime lookup.
99        outcome: ReceiptOutcome,
100        /// Sampled canonical depth including the inclusion block, not finality.
101        confirmations: u64,
102        /// End-of-inclusion-block code for successful creation; failures/unknown
103        /// outcomes do not infer deployment from pre-existing or later code.
104        code: Option<DeploymentCode>,
105    },
106}
107impl<T: Transport> Provider<T> {
108    /// Observe the exact signed creation, validate receipt sender/type/destination
109    /// and predicted contract, then read code at the numeric inclusion height.
110    /// Pruned state and source errors propagate. Reorgs during the multi-request
111    /// observation fail closed, and hash comparison does not attest contract safety.
112    pub async fn observe_deployment(
113        &self,
114        reference: &DeploymentReference,
115    ) -> Result<DeploymentObservation, ProviderError> {
116        let zone = reference.zone();
117        if self.expected_chain_id != reference.chain {
118            return Err(ProviderError::ChainMismatch {
119                expected: self.expected_chain_id,
120                actual: reference.chain,
121            });
122        }
123        if self.genesis_hash(zone).await? != reference.genesis {
124            return Err(ProviderError::GenesisMismatch);
125        }
126        let Some(receipt) = self.receipt(zone, reference.hash).await? else {
127            return Ok(DeploymentObservation::NoReceipt {
128                transaction_known: self.transaction(zone, reference.hash).await?.is_some(),
129            });
130        };
131        if receipt.kind != TransactionKind::Quai
132            || receipt
133                .from
134                .is_some_and(|a| a != reference.sender.address())
135            || receipt.to.is_some()
136            || receipt
137                .contract_address
138                .is_some_and(|a| a != reference.address)
139            || (receipt.outcome == ReceiptOutcome::Succeeded
140                && receipt.contract_address != Some(reference.address))
141        {
142            return Err(ProviderError::InvalidResult(
143                "deployment receipt differs from signed intent",
144            ));
145        }
146        let block = BlockReference {
147            number: receipt.inclusion.block_number,
148            hash: receipt.inclusion.block_hash,
149        };
150        let canonical = self
151            .header_at(zone, block.number)
152            .await?
153            .map(|h| BlockReference {
154                number: h.number,
155                hash: h.hash,
156            });
157        if canonical != Some(block) {
158            return Ok(DeploymentObservation::Noncanonical {
159                reported: block,
160                canonical,
161            });
162        }
163        let head = self
164            .latest_header(zone)
165            .await?
166            .ok_or(ProviderError::ObservationChanged)?;
167        let confirmations = head
168            .number
169            .checked_sub(block.number)
170            .and_then(|n| n.checked_add(1))
171            .ok_or(ProviderError::ObservationChanged)?;
172        let code = if receipt.outcome == ReceiptOutcome::Succeeded {
173            let bytes = self
174                .code(
175                    reference.address,
176                    BlockTag::Number(U256::from(block.number)),
177                )
178                .await?;
179            let hash = Hash32::from_bytes(quai_crypto::keccak256(bytes.bytes()));
180            Some(DeploymentCode {
181                bytes,
182                hash,
183                matches_expected: reference.expected_runtime.map(|expected| expected == hash),
184            })
185        } else {
186            None
187        };
188        for (number, hash) in [(block.number, block.hash), (head.number, head.hash)] {
189            if self
190                .header_at(zone, number)
191                .await?
192                .is_none_or(|h| h.hash != hash)
193            {
194                return Err(ProviderError::ObservationChanged);
195            }
196        }
197        Ok(DeploymentObservation::Included {
198            block,
199            outcome: receipt.outcome,
200            confirmations,
201            code,
202        })
203    }
204}
205
206/// Native bounded deployment-wait failures never cancel an already signed operation.
207#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
208#[derive(Debug, thiserror::Error)]
209#[non_exhaustive]
210pub enum DeploymentWaitError {
211    /// Invalid timeout, polling interval or confirmation depth; no I/O occurred.
212    #[error("invalid deployment wait limits")]
213    InvalidConfig,
214    /// The elapsed-time budget expired, without inferring rejection or finality.
215    #[error("timed out waiting for deployment {transaction_hash}")]
216    Timeout {
217        /// Exact signed creation being observed.
218        transaction_hash: Hash32,
219        /// Most recently seen inclusion, which may have subsequently reorganized.
220        last_observed: Option<BlockReference>,
221    },
222    /// Source failure; the application decides whether to start another wait.
223    #[error(transparent)]
224    Provider(#[from] ProviderError),
225}
226#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
227impl<T: Transport> Provider<T> {
228    /// Wait for canonical deployment inclusion at an explicit depth, refreshing
229    /// receipt and inclusion-block code through `observe_deployment`. Failed,
230    /// locked and unknown outcomes return explicitly once they reach that depth;
231    /// empty or mismatched runtime code is never represented as successful code.
232    /// Missing/reorganized observations continue until the overall deadline.
233    /// Other source errors stop immediately. Dropping the future stops polling.
234    pub async fn wait_for_deployment(
235        &self,
236        reference: &DeploymentReference,
237        config: crate::WaitConfig,
238    ) -> Result<DeploymentObservation, DeploymentWaitError> {
239        if config.confirmations == 0
240            || config.timeout.is_zero()
241            || config.poll_interval.is_zero()
242            || config.poll_interval > config.timeout
243            || tokio::time::Instant::now()
244                .checked_add(config.timeout)
245                .is_none()
246        {
247            return Err(DeploymentWaitError::InvalidConfig);
248        }
249        let mut last_observed = None;
250        let work = async {
251            loop {
252                match self.observe_deployment(reference).await {
253                    Ok(observation) => match &observation {
254                        DeploymentObservation::Included {
255                            block,
256                            confirmations,
257                            ..
258                        } => {
259                            last_observed = Some(*block);
260                            if *confirmations >= config.confirmations {
261                                return Ok(observation);
262                            }
263                        }
264                        DeploymentObservation::Noncanonical { reported, .. } => {
265                            last_observed = Some(*reported)
266                        }
267                        DeploymentObservation::NoReceipt { .. } => {}
268                    },
269                    Err(ProviderError::ObservationChanged) => {}
270                    Err(error) => return Err(DeploymentWaitError::Provider(error)),
271                }
272                tokio::time::sleep(config.poll_interval).await;
273            }
274        };
275        match tokio::time::timeout(config.timeout, work).await {
276            Ok(result) => result,
277            Err(_) => Err(DeploymentWaitError::Timeout {
278                transaction_hash: reference.hash,
279                last_observed,
280            }),
281        }
282    }
283}