1use 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#[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 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 pub fn address(&self) -> QuaiAddress {
55 self.address
56 }
57 pub fn transaction_hash(&self) -> Hash32 {
59 self.hash
60 }
61 pub fn zone(&self) -> Zone {
63 self.sender.zone()
64 }
65}
66#[derive(Clone, Debug, PartialEq)]
69#[non_exhaustive]
70pub struct DeploymentCode {
71 pub bytes: RpcData,
73 pub hash: Hash32,
75 pub matches_expected: Option<bool>,
77}
78#[derive(Clone, Debug, PartialEq)]
80pub enum DeploymentObservation {
81 NoReceipt {
84 transaction_known: bool,
86 },
87 Noncanonical {
89 reported: BlockReference,
91 canonical: Option<BlockReference>,
93 },
94 Included {
96 block: BlockReference,
98 outcome: ReceiptOutcome,
100 confirmations: u64,
102 code: Option<DeploymentCode>,
105 },
106}
107impl<T: Transport> Provider<T> {
108 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#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
208#[derive(Debug, thiserror::Error)]
209#[non_exhaustive]
210pub enum DeploymentWaitError {
211 #[error("invalid deployment wait limits")]
213 InvalidConfig,
214 #[error("timed out waiting for deployment {transaction_hash}")]
216 Timeout {
217 transaction_hash: Hash32,
219 last_observed: Option<BlockReference>,
221 },
222 #[error(transparent)]
224 Provider(#[from] ProviderError),
225}
226#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
227impl<T: Transport> Provider<T> {
228 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}