Skip to main content

forge_script/
recovery.rs

1use crate::{
2    multi_sequence::MultiChainSequence,
3    sequence::{SequenceData, completed_transaction_prefix, operation_ordinal},
4};
5use alloy_consensus::{Transaction, transaction::SignerRecoverable};
6use alloy_eips::eip2718::{Decodable2718, Encodable2718};
7use alloy_network::{Network, ReceiptResponse, TransactionBuilder, TransactionResponse};
8use alloy_primitives::{Address, B256, Bytes, TxKind, keccak256};
9use eyre::{ContextCompat, Result, WrapErr, bail};
10use forge_script_sequence::{DRY_RUN_DIR, ScriptSequence, TransactionWithMetadata, now};
11use foundry_common::{FoundryTransactionBuilder, TransactionMaybeSigned};
12use serde::{Deserialize, Serialize};
13use std::{
14    fs::{File, OpenOptions},
15    io::{BufWriter, Write},
16    path::{Path, PathBuf},
17};
18use tempfile::NamedTempFile;
19use tempo_primitives::transaction::{TEMPO_EXPIRING_NONCE_KEY, TempoTxEnvelope};
20
21#[cfg(unix)]
22use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
23
24const RECOVERY_VERSION: u32 = 1;
25
26#[derive(Clone, Serialize, Deserialize)]
27#[serde(bound(
28    serialize = "N::TxEnvelope: Serialize",
29    deserialize = "N::TxEnvelope: for<'de2> Deserialize<'de2>"
30))]
31struct RecoveryPlan<N: Network> {
32    version: u32,
33    generation: B256,
34    multi: bool,
35    batch: bool,
36    /// Tempo sponsor of the run that created the snapshot. Resume must not prepare new
37    /// transactions without it.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    sponsor: Option<Address>,
40    deployments: Vec<RecoveryDeployment<N>>,
41    data: SequenceData<N>,
42}
43
44#[derive(Clone, Serialize, Deserialize)]
45#[serde(bound = "")]
46struct RecoveryDeployment<N: Network> {
47    chain: u64,
48    batch_id: Option<u32>,
49    operations: Vec<RecoveryOperation>,
50    #[serde(default, skip_serializing_if = "Vec::is_empty")]
51    attempts: Vec<SubmissionAttempt<N::TransactionRequest>>,
52}
53
54#[derive(Clone, Serialize, Deserialize)]
55struct RecoveryOperation {
56    id: OperationId,
57    fingerprint: B256,
58    rpc: String,
59}
60
61#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62struct OperationId {
63    sequence: u32,
64    index: u32,
65}
66
67#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub(crate) struct SignedPayload {
69    pub(crate) payload: Bytes,
70    pub(crate) hash: B256,
71}
72
73#[derive(Clone, Serialize, Deserialize)]
74struct SubmissionAttempt<T> {
75    id: B256,
76    members: Vec<OperationId>,
77    kind: AttemptKind<T>,
78}
79
80#[derive(Clone, Serialize, Deserialize)]
81#[serde(tag = "kind", rename_all = "camelCase")]
82pub(crate) enum AttemptKind<T> {
83    Signed { request: Option<T>, payload: SignedPayload },
84    Delegated { request: T, status: DelegatedStatus },
85    Legacy { hash: B256 },
86}
87
88#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(tag = "status", rename_all = "camelCase")]
90pub(crate) enum DelegatedStatus {
91    Prepared,
92    Pending { hash: B256 },
93    OutcomeUnknown,
94}
95
96/// For each operation by sequence and index, its fingerprint and the digest of the transaction
97/// last found to match it.
98type VerifiedOperations = Vec<Vec<Option<(B256, B256)>>>;
99
100/// Owns the authoritative recovery snapshot and its process-lifetime writer lock.
101pub(crate) struct RecoveryStore<N: Network> {
102    path: PathBuf,
103    _lock: RecoveryLock,
104    plan: RecoveryPlan<N>,
105    /// Lets each save skip fingerprinting transactions that did not change since the last one.
106    verified: VerifiedOperations,
107}
108
109pub(crate) struct RecoveryLock {
110    path: PathBuf,
111    _files: Vec<File>,
112}
113
114pub(crate) struct RecoveryRelocation {
115    lock: RecoveryLock,
116}
117
118impl<N: Network> RecoveryStore<N>
119where
120    N::TxEnvelope: for<'de> Deserialize<'de> + Serialize,
121{
122    pub(crate) const fn data(&self) -> &SequenceData<N> {
123        &self.plan.data
124    }
125
126    pub(crate) const fn data_mut(&mut self) -> &mut SequenceData<N> {
127        &mut self.plan.data
128    }
129
130    pub(crate) const fn is_batch(&self) -> bool {
131        self.plan.batch
132    }
133
134    pub(crate) const fn sponsor(&self) -> Option<Address> {
135        self.plan.sponsor
136    }
137
138    pub(crate) fn create(
139        mut data: SequenceData<N>,
140        batch: bool,
141        sponsor: Option<Address>,
142    ) -> Result<Self> {
143        let paths = data.paths();
144        let lock = RecoveryLock::acquire(&paths)?;
145        let pending = pending_path(&lock.path);
146        if pending.exists() {
147            bail!(
148                "uncommitted recovery snapshot `{}` already exists; resume it before starting a new execution",
149                pending.display()
150            );
151        }
152        if previous_unfinished::<N>(&lock.path, &paths, data.is_multi())? {
153            bail!(
154                "the previous broadcast `{}` has unfinished operations; finish it with `{}`, or pass `--start-fresh` to archive it and broadcast anew",
155                paths.0.display(),
156                if data.is_multi() { "--multi --resume" } else { "--resume" }
157            );
158        }
159        let generation = B256::random();
160        data.set_recovery_generation(generation);
161        let plan = RecoveryPlan { sponsor, ..RecoveryPlan::new(data, batch, generation)? };
162        write_snapshot(&lock.path, &plan)?;
163        Self::finish_open(lock, plan)
164    }
165
166    /// Moves the unfinished progress of a previous execution of `data` to timestamped names, so
167    /// that a new execution can replace it.
168    pub(crate) fn archive_unfinished(data: &SequenceData<N>) -> Result<()> {
169        let paths = &data.paths();
170        let lock = RecoveryLock::acquire(paths)?;
171        // A crash mid-commit leaves the newest complete snapshot pending, as resume would find it.
172        let pending = pending_path(&lock.path);
173        if pending.exists() {
174            commit_pending_plan(&pending, &lock.path)?;
175        }
176        if matches!(previous_unfinished::<N>(&lock.path, paths, data.is_multi()), Ok(false)) {
177            return Ok(());
178        }
179        let timestamp = now().as_millis();
180        for path in [&lock.path, &paths.0, &paths.1] {
181            if path.symlink_metadata().is_ok() {
182                let archive = path.with_extension(format!("{timestamp}.json"));
183                std::fs::rename(path, &archive)?;
184                sh_status!("Archived `{}` to `{}`", path.display(), archive.display())?;
185            }
186        }
187        Ok(())
188    }
189
190    pub(crate) fn load(
191        paths: &(PathBuf, PathBuf),
192        batch: bool,
193        lock: RecoveryLock,
194    ) -> Result<Option<Self>>
195    where
196        N::TxEnvelope: SignerRecoverable,
197        N::TransactionRequest: FoundryTransactionBuilder<N>,
198    {
199        let pending = pending_path(&lock.path);
200        let (mut plan, recover_pending) = if pending.exists() {
201            (load_plan(&pending)?, true)
202        } else if lock.path.exists() {
203            (load_plan(&lock.path)?, false)
204        } else {
205            return Ok(None);
206        };
207        plan.restore_sensitive();
208        plan.data.set_paths(paths.clone());
209        plan.validate(batch, &mut Default::default())?;
210        plan.validate_signed_payloads()?;
211        if recover_pending {
212            commit_pending_plan(&pending, &lock.path)?;
213        }
214        Self::finish_open(lock, plan).map(Some)
215    }
216
217    pub(crate) fn import(mut data: SequenceData<N>, batch: bool, lock: RecoveryLock) -> Result<Self>
218    where
219        N::TxEnvelope: SignerRecoverable,
220        N::TransactionRequest: FoundryTransactionBuilder<N>,
221    {
222        let generation = B256::random();
223        data.set_recovery_generation(generation);
224        let mut plan = RecoveryPlan::new(data, batch, generation)?;
225        if batch {
226            plan.import_legacy_batch_attempts()?;
227        }
228        plan.validate_signed_payloads()?;
229        write_snapshot(&lock.path, &plan)?;
230        Self::finish_open(lock, plan)
231    }
232
233    fn finish_open(lock: RecoveryLock, plan: RecoveryPlan<N>) -> Result<Self> {
234        #[cfg(unix)]
235        for path in [&lock.path, &pending_path(&lock.path)] {
236            if path.exists() {
237                std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
238            }
239        }
240        Ok(Self { path: lock.path.clone(), _lock: lock, plan, verified: Vec::new() })
241    }
242
243    pub(crate) fn save(&mut self) -> Result<()> {
244        self.plan.validate(self.plan.batch, &mut self.verified)?;
245        write_snapshot(&self.path, &self.plan)
246    }
247
248    fn submission_attempts(
249        &self,
250        sequence: usize,
251        index: usize,
252    ) -> impl Iterator<Item = &SubmissionAttempt<N::TransactionRequest>> {
253        let operation = self
254            .plan
255            .deployments
256            .get(sequence)
257            .and_then(|deployment| deployment.operations.get(index))
258            .map(|operation| operation.id);
259        self.plan
260            .deployments
261            .get(sequence)
262            .into_iter()
263            .flat_map(|deployment| &deployment.attempts)
264            .filter(move |attempt| operation.is_some_and(|id| attempt.members.contains(&id)))
265    }
266
267    pub(crate) fn signed_payload(&self, sequence: usize, index: usize) -> Option<&SignedPayload> {
268        self.submission_attempts(sequence, index).find_map(|attempt| match &attempt.kind {
269            AttemptKind::Signed { payload, .. } => Some(payload),
270            AttemptKind::Delegated { .. } | AttemptKind::Legacy { .. } => None,
271        })
272    }
273
274    pub(crate) fn delegated_status(
275        &self,
276        sequence: usize,
277        index: usize,
278    ) -> Option<DelegatedStatus> {
279        self.submission_attempts(sequence, index).find_map(|attempt| match &attempt.kind {
280            AttemptKind::Delegated { status, .. } => Some(*status),
281            AttemptKind::Signed { .. } | AttemptKind::Legacy { .. } => None,
282        })
283    }
284
285    pub(crate) fn submission_hashes(&self, sequence: usize) -> (Vec<B256>, Vec<B256>) {
286        let mut durable = Vec::new();
287        let mut replayable = Vec::new();
288        for attempt in self
289            .plan
290            .deployments
291            .get(sequence)
292            .into_iter()
293            .flat_map(|deployment| &deployment.attempts)
294        {
295            match &attempt.kind {
296                AttemptKind::Signed { payload, .. } => {
297                    durable.push(payload.hash);
298                    replayable.push(payload.hash);
299                }
300                AttemptKind::Delegated { status: DelegatedStatus::Pending { hash }, .. } => {
301                    durable.push(*hash);
302                }
303                AttemptKind::Legacy { hash } => durable.push(*hash),
304                AttemptKind::Delegated { .. } => {}
305            }
306        }
307        (durable, replayable)
308    }
309
310    pub(crate) fn batch_attempt(
311        &self,
312        sequence: usize,
313    ) -> Option<(usize, B256, &AttemptKind<N::TransactionRequest>)> {
314        if !self.plan.batch {
315            return None;
316        }
317        let attempt = self.plan.deployments.get(sequence)?.attempts.first()?;
318        Some((attempt.members.first()?.index as usize, attempt.id, &attempt.kind))
319    }
320
321    pub(crate) fn persist_signed_payload(
322        &mut self,
323        sequence: usize,
324        index: usize,
325        payload: Bytes,
326        sender_scoped_replay: bool,
327    ) -> Result<B256>
328    where
329        N::TxEnvelope: SignerRecoverable,
330        N::TransactionRequest: FoundryTransactionBuilder<N>,
331    {
332        let deployment = self
333            .plan
334            .deployments
335            .get(sequence)
336            .context("signed payload deployment is not in the recovery snapshot")?;
337        let operation = deployment
338            .operations
339            .get(index)
340            .context("signed payload operation is not in the recovery snapshot")?;
341        let transaction = &self.plan.data.sequences()[sequence].transactions[index];
342        let signed = validate_signed_payload::<N>(
343            payload,
344            transaction,
345            deployment.chain,
346            index,
347            operation_ordinal(self.plan.data.sequences(), sequence, index),
348        )?;
349        let id = operation.id;
350        // From T1B, expiring replay identities exclude sponsor signatures, so different envelopes
351        // can still be replays. Compare identities across all sequences of the same chain before
352        // recording an attempt the node would reject. Keep envelope hashes for receipt tracking.
353        let replay_hash = expiring_replay_hash(&signed.payload, sender_scoped_replay)?;
354        for attempt in self
355            .plan
356            .deployments
357            .iter()
358            .enumerate()
359            .filter(|(i, other)| {
360                *i == sequence || (replay_hash.is_some() && other.chain == deployment.chain)
361            })
362            .flat_map(|(_, other)| &other.attempts)
363        {
364            if !attempt.members.contains(&id)
365                && let AttemptKind::Signed { payload, .. } = &attempt.kind
366                && match replay_hash {
367                    Some(hash) => {
368                        expiring_replay_hash(&payload.payload, sender_scoped_replay)? == Some(hash)
369                    }
370                    None => payload.hash == signed.hash,
371                }
372            {
373                bail!(
374                    "transaction {index} is identical to an earlier transaction of this script ({}) and would be rejected as a replay; identical Tempo expiring nonce transactions are only distinct from the T12 hardfork (TIP-1106)",
375                    signed.hash
376                );
377            }
378        }
379        if let Some(existing) = self.signed_payload(sequence, index) {
380            if existing != &signed {
381                bail!("refusing to replace an existing signed payload");
382            }
383            return Ok(existing.hash);
384        }
385        if deployment.attempts.iter().any(|attempt| attempt.members.contains(&id)) {
386            bail!("refusing to replace an existing submission attempt");
387        }
388        let hash = signed.hash;
389        self.persist_attempt(
390            sequence,
391            SubmissionAttempt {
392                id: B256::random(),
393                members: vec![id],
394                kind: AttemptKind::Signed { request: None, payload: signed },
395            },
396        )?;
397        Ok(hash)
398    }
399
400    pub(crate) fn persist_delegated_request(
401        &mut self,
402        sequence: usize,
403        index: usize,
404        request: N::TransactionRequest,
405    ) -> Result<()> {
406        let deployment = self
407            .plan
408            .deployments
409            .get(sequence)
410            .context("delegated operation is not in the recovery snapshot")?;
411        let id = deployment
412            .operations
413            .get(index)
414            .context("delegated operation is not in the recovery snapshot")?
415            .id;
416        if deployment.attempts.iter().any(|attempt| attempt.members.contains(&id)) {
417            bail!("refusing to replace an existing submission attempt");
418        }
419        self.persist_attempt(
420            sequence,
421            SubmissionAttempt {
422                id: B256::random(),
423                members: vec![id],
424                kind: AttemptKind::Delegated { request, status: DelegatedStatus::Prepared },
425            },
426        )
427    }
428
429    pub(crate) fn persist_delegated_status(
430        &mut self,
431        sequence: usize,
432        index: usize,
433        status: DelegatedStatus,
434    ) -> Result<()> {
435        let deployment = self
436            .plan
437            .deployments
438            .get_mut(sequence)
439            .context("delegated operation is not in the recovery snapshot")?;
440        let id = deployment
441            .operations
442            .get(index)
443            .context("delegated operation is not in the recovery snapshot")?
444            .id;
445        let attempt = deployment
446            .attempts
447            .iter_mut()
448            .find(|attempt| attempt.members.contains(&id))
449            .context("delegated operation has no submission attempt")?;
450        let AttemptKind::Delegated { status: current, .. } = &mut attempt.kind else {
451            bail!("operation has no delegated submission attempt");
452        };
453        let previous = *current;
454        if previous == status {
455            return Ok(());
456        }
457        *current = status;
458        if let Err(error) = write_snapshot(&self.path, &self.plan) {
459            let AttemptKind::Delegated { status, .. } = &mut self.plan.deployments[sequence]
460                .attempts
461                .iter_mut()
462                .find(|attempt| attempt.members.contains(&id))
463                .unwrap()
464                .kind
465            else {
466                unreachable!()
467            };
468            *status = previous;
469            return Err(error);
470        }
471        Ok(())
472    }
473
474    pub(crate) fn clear_delegated_request(&mut self, sequence: usize, index: usize) -> Result<()> {
475        let deployment = self
476            .plan
477            .deployments
478            .get_mut(sequence)
479            .context("delegated operation is not in the recovery snapshot")?;
480        let id = deployment
481            .operations
482            .get(index)
483            .context("delegated operation is not in the recovery snapshot")?
484            .id;
485        let position = deployment
486            .attempts
487            .iter()
488            .position(|attempt| {
489                attempt.members.contains(&id)
490                    && matches!(&attempt.kind, AttemptKind::Delegated { .. })
491            })
492            .context("delegated operation has no submission attempt")?;
493        let attempt = deployment.attempts.remove(position);
494        if let Err(error) = write_snapshot(&self.path, &self.plan) {
495            self.plan.deployments[sequence].attempts.insert(position, attempt);
496            return Err(error);
497        }
498        Ok(())
499    }
500
501    pub(crate) fn delegated_attempt_location(&self, id: B256) -> Option<(usize, usize)> {
502        self.plan.deployments.iter().enumerate().find_map(|(sequence, deployment)| {
503            let attempt = deployment.attempts.iter().find(|attempt| {
504                attempt.id == id && matches!(attempt.kind, AttemptKind::Delegated { .. })
505            })?;
506            let operation = attempt.members.first()?;
507            Some((sequence, operation.index as usize))
508        })
509    }
510
511    pub(crate) fn delegated_attempts(&self) -> Vec<(usize, usize, B256, DelegatedStatus)> {
512        self.plan
513            .deployments
514            .iter()
515            .enumerate()
516            .flat_map(|(sequence, deployment)| {
517                deployment.attempts.iter().filter_map(move |attempt| {
518                    let AttemptKind::Delegated { status, .. } = &attempt.kind else { return None };
519                    Some((sequence, attempt.members.first()?.index as usize, attempt.id, *status))
520                })
521            })
522            .collect()
523    }
524
525    pub(crate) fn resolve_delegated_hash(
526        &mut self,
527        attempt_id: B256,
528        hash: B256,
529        transaction: &N::TransactionResponse,
530    ) -> Result<(usize, usize)>
531    where
532        N::TransactionRequest: FoundryTransactionBuilder<N>,
533    {
534        let (sequence, index) = self
535            .delegated_attempt_location(attempt_id)
536            .context("no interrupted delegated submission matches --resume-attempt")?;
537        let deployment = &self.plan.deployments[sequence];
538        let attempt = deployment.attempts.iter().find(|attempt| attempt.id == attempt_id).unwrap();
539        let AttemptKind::Delegated { request, status } = &attempt.kind else { unreachable!() };
540        if !matches!(status, DelegatedStatus::Prepared | DelegatedStatus::OutcomeUnknown) {
541            bail!("delegated submission attempt {attempt_id} does not require resolution");
542        }
543        validate_delegated_transaction::<N>(transaction, request, deployment.chain, hash)?;
544        self.persist_delegated_status(sequence, index, DelegatedStatus::Pending { hash })?;
545        Ok((sequence, index))
546    }
547
548    pub(crate) fn persist_batch_signed_payload(
549        &mut self,
550        sequence: usize,
551        first_operation: usize,
552        request: N::TransactionRequest,
553        payload: Bytes,
554    ) -> Result<B256>
555    where
556        N::TxEnvelope: Decodable2718 + Encodable2718,
557    {
558        let signed = SignedPayload { hash: signed_payload_hash::<N>(&payload)?, payload };
559        let hash = signed.hash;
560        self.persist_batch_attempt(
561            sequence,
562            first_operation,
563            AttemptKind::Signed { request: Some(request), payload: signed },
564        )?;
565        Ok(hash)
566    }
567
568    pub(crate) fn persist_batch_delegated_request(
569        &mut self,
570        sequence: usize,
571        first_operation: usize,
572        request: N::TransactionRequest,
573    ) -> Result<()> {
574        self.persist_batch_attempt(
575            sequence,
576            first_operation,
577            AttemptKind::Delegated { request, status: DelegatedStatus::Prepared },
578        )
579    }
580
581    fn persist_batch_attempt(
582        &mut self,
583        sequence: usize,
584        first_operation: usize,
585        kind: AttemptKind<N::TransactionRequest>,
586    ) -> Result<()> {
587        if self.batch_attempt(sequence).is_some() {
588            bail!("refusing to replace an existing batch submission attempt");
589        }
590        let members = self
591            .plan
592            .deployments
593            .get(sequence)
594            .context("batch deployment is not in the recovery snapshot")?
595            .operations
596            .get(first_operation..)
597            .context("batch operation is not in the recovery snapshot")?
598            .iter()
599            .map(|operation| operation.id)
600            .collect::<Vec<_>>();
601        if members.is_empty() {
602            bail!("batch submission has no operations");
603        }
604        self.persist_attempt(sequence, SubmissionAttempt { id: B256::random(), members, kind })
605    }
606
607    fn persist_attempt(
608        &mut self,
609        sequence: usize,
610        attempt: SubmissionAttempt<N::TransactionRequest>,
611    ) -> Result<()> {
612        self.plan
613            .deployments
614            .get_mut(sequence)
615            .context("submission deployment is not in the recovery snapshot")?
616            .attempts
617            .push(attempt);
618        if let Err(error) = write_snapshot(&self.path, &self.plan) {
619            self.plan.deployments[sequence].attempts.pop();
620            return Err(error);
621        }
622        Ok(())
623    }
624
625    pub(crate) fn prepare_relocation(
626        &self,
627        paths: &(PathBuf, PathBuf),
628    ) -> Result<RecoveryRelocation> {
629        let lock = RecoveryLock::acquire(paths)?;
630        let path = &lock.path;
631        if paths.0.exists() {
632            bail!(
633                "broadcast progress `{}` already exists; refusing to replace it",
634                paths.0.display()
635            );
636        }
637        if path.exists() {
638            let existing: RecoveryPlan<N> = foundry_common::fs::read_json_file(path)
639                .wrap_err_with(|| format!("recovery snapshot `{}` is corrupt", path.display()))?;
640            existing.validate(self.plan.batch, &mut Default::default())?;
641            self.plan.validate(self.plan.batch, &mut Default::default())?;
642            if serde_json::to_value(existing.deployments)?
643                != serde_json::to_value(&self.plan.deployments)?
644            {
645                bail!("destination recovery snapshot does not match the script operations");
646            }
647        }
648        write_snapshot(path, &self.plan)?;
649        Ok(RecoveryRelocation { lock })
650    }
651
652    pub(crate) fn commit_relocation(&mut self, relocation: RecoveryRelocation) -> Result<()> {
653        let RecoveryRelocation { lock } = relocation;
654        let path = &lock.path;
655        #[cfg(unix)]
656        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
657        self.path.clone_from(path);
658        self._lock = lock;
659        Ok(())
660    }
661}
662
663impl RecoveryLock {
664    pub(crate) fn acquire(paths: &(PathBuf, PathBuf)) -> Result<Self> {
665        let path = recovery_path_from_sensitive(&paths.1)?;
666        let mut lock_paths =
667            vec![path.with_extension("lock"), paths.0.with_extension("recovery.lock")];
668        lock_paths.sort();
669        lock_paths.dedup();
670        let mut files = Vec::with_capacity(lock_paths.len());
671        for lock_path in lock_paths {
672            if let Some(parent) = lock_path.parent() {
673                std::fs::create_dir_all(parent)?;
674            }
675            let mut options = OpenOptions::new();
676            options.read(true).write(true).create(true);
677            #[cfg(unix)]
678            options.mode(0o600);
679            let file = options.open(&lock_path)?;
680            #[cfg(unix)]
681            file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
682            file.try_lock().wrap_err_with(|| {
683                format!("another process is already modifying recovery state `{}`", path.display())
684            })?;
685            files.push(file);
686        }
687        Ok(Self { path, _files: files })
688    }
689}
690
691impl<N: Network> RecoveryPlan<N>
692where
693    N::TxEnvelope: for<'de> Deserialize<'de> + Serialize,
694{
695    fn new(data: SequenceData<N>, batch: bool, generation: B256) -> Result<Self> {
696        let deployments = data
697            .sequences()
698            .iter()
699            .enumerate()
700            .map(|(sequence, deployment)| {
701                Ok(RecoveryDeployment {
702                    chain: deployment.chain,
703                    batch_id: batch.then(|| u32::try_from(sequence).expect("too many sequences")),
704                    attempts: Vec::new(),
705                    operations: deployment
706                        .transactions
707                        .iter()
708                        .enumerate()
709                        .map(|(index, transaction)| {
710                            Ok(RecoveryOperation {
711                                id: OperationId {
712                                    sequence: u32::try_from(sequence).expect("too many sequences"),
713                                    index: u32::try_from(index).expect("too many operations"),
714                                },
715                                fingerprint: operation_fingerprint(transaction)?,
716                                rpc: transaction.rpc.clone(),
717                            })
718                        })
719                        .collect::<Result<Vec<_>>>()?,
720                })
721            })
722            .collect::<Result<Vec<_>>>()?;
723        Ok(Self {
724            version: RECOVERY_VERSION,
725            generation,
726            multi: data.is_multi(),
727            batch,
728            sponsor: None,
729            deployments,
730            data,
731        })
732    }
733
734    fn import_legacy_batch_attempts(&mut self) -> Result<()> {
735        for (deployment, data) in self.deployments.iter_mut().zip(self.data.sequences().iter()) {
736            let completed = completed_transaction_prefix(data)?;
737            if data.pending.is_empty() {
738                if data
739                    .transactions
740                    .iter()
741                    .skip(completed)
742                    .any(|transaction| transaction.hash.is_some())
743                {
744                    bail!("legacy batch progress has operation hashes without a pending hash");
745                }
746                continue;
747            }
748            let [hash] = data.pending.as_slice() else {
749                bail!("cannot import legacy batch progress with multiple pending hashes");
750            };
751            let first = data
752                .transactions
753                .iter()
754                .position(|transaction| transaction.hash == Some(*hash))
755                .context("legacy batch hash is not bound to a recovery operation")?;
756            if completed != first {
757                bail!("legacy batch progress omits an incomplete operation");
758            }
759            if data
760                .transactions
761                .iter()
762                .skip(first)
763                .any(|transaction| transaction.hash != Some(*hash))
764            {
765                bail!("cannot import inconsistent legacy batch operation hashes");
766            }
767            deployment.attempts.push(SubmissionAttempt {
768                id: B256::random(),
769                members: deployment.operations[first..]
770                    .iter()
771                    .map(|operation| operation.id)
772                    .collect(),
773                kind: AttemptKind::Legacy { hash: *hash },
774            });
775        }
776        Ok(())
777    }
778
779    /// Checks the snapshot's mode and generation, and that its operations still match the script's
780    /// transactions. `verified` caches matching transactions across calls.
781    fn validate(&self, batch: bool, verified: &mut VerifiedOperations) -> Result<()> {
782        if self.version != RECOVERY_VERSION {
783            bail!(
784                "unsupported recovery snapshot version {}; expected version {}",
785                self.version,
786                RECOVERY_VERSION
787            );
788        }
789        if self.batch != batch || self.multi != self.data.is_multi() {
790            bail!("recovery snapshot does not match the requested script mode");
791        }
792        if self
793            .data
794            .sequences()
795            .iter()
796            .any(|sequence| sequence.recovery_generation != Some(self.generation))
797        {
798            bail!("recovery snapshot contains inconsistent generations");
799        }
800        if !self.operations_match(verified)? {
801            bail!("recovery snapshot does not match the script operations; refusing to resume");
802        }
803        Ok(())
804    }
805
806    /// Returns true if the deployments are the ones [`Self::new`] would plan for the current
807    /// transactions, ignoring attempts.
808    ///
809    /// Fingerprinting dominates a save, so a transaction is fingerprinted again only when its
810    /// serialized form changed since it last matched its operation.
811    fn operations_match(&self, verified: &mut VerifiedOperations) -> Result<bool> {
812        let sequences = self.data.sequences();
813        if self.deployments.len() != sequences.len() {
814            return Ok(false);
815        }
816        verified.resize_with(sequences.len(), Vec::new);
817        for (sequence, ((deployment, data), verified)) in
818            self.deployments.iter().zip(sequences).zip(verified.iter_mut()).enumerate()
819        {
820            let sequence = u32::try_from(sequence).expect("too many sequences");
821            if deployment.chain != data.chain
822                || deployment.batch_id != self.batch.then_some(sequence)
823                || deployment.operations.len() != data.transactions.len()
824            {
825                return Ok(false);
826            }
827            verified.resize(data.transactions.len(), None);
828            for (index, ((operation, transaction), verified)) in
829                deployment.operations.iter().zip(&data.transactions).zip(verified).enumerate()
830            {
831                let index = u32::try_from(index).expect("too many operations");
832                if operation.id != (OperationId { sequence, index })
833                    || operation.rpc != transaction.rpc
834                {
835                    return Ok(false);
836                }
837                let digest = keccak256(serde_json::to_vec(transaction)?);
838                if *verified == Some((operation.fingerprint, digest)) {
839                    continue;
840                }
841                if operation_fingerprint(transaction)? != operation.fingerprint {
842                    return Ok(false);
843                }
844                *verified = Some((operation.fingerprint, digest));
845            }
846        }
847        Ok(true)
848    }
849
850    fn validate_signed_payloads(&self) -> Result<()>
851    where
852        N::TxEnvelope: SignerRecoverable,
853        N::TransactionRequest: FoundryTransactionBuilder<N>,
854    {
855        for (sequence, deployment) in self.deployments.iter().enumerate() {
856            let data = &self.data.sequences()[sequence];
857            if self.batch && deployment.attempts.is_empty() {
858                let completed = completed_transaction_prefix(data)?;
859                if !data.pending.is_empty()
860                    || data
861                        .transactions
862                        .iter()
863                        .skip(completed)
864                        .any(|transaction| transaction.hash.is_some())
865                {
866                    bail!("batch progress exists without a durable submission attempt");
867                }
868            }
869            if self.batch && deployment.attempts.len() > 1 {
870                bail!("recovery snapshot contains multiple batch submission attempts");
871            }
872            let mut claimed = vec![false; deployment.operations.len()];
873            for attempt in &deployment.attempts {
874                let Some(first) = attempt.members.first() else {
875                    bail!("recovery snapshot attempt has invalid operation membership");
876                };
877                if first.sequence as usize != sequence {
878                    bail!("recovery snapshot attempt has invalid operation membership");
879                }
880                let start = first.index as usize;
881                let end = start
882                    .checked_add(attempt.members.len())
883                    .context("recovery snapshot attempt has invalid operation membership")?;
884                let operations = deployment
885                    .operations
886                    .get(start..end)
887                    .context("recovery snapshot attempt has invalid operation membership")?;
888                if operations
889                    .iter()
890                    .map(|operation| operation.id)
891                    .ne(attempt.members.iter().copied())
892                    || claimed[start..end].iter().any(|claimed| *claimed)
893                    || if self.batch {
894                        end != deployment.operations.len()
895                    } else {
896                        attempt.members.len() != 1
897                    }
898                {
899                    bail!("recovery snapshot attempt has invalid operation membership");
900                }
901                if self.batch {
902                    let completed = completed_transaction_prefix(data)?;
903                    if completed != start && completed != deployment.operations.len() {
904                        bail!("batch submission attempt omits an incomplete operation");
905                    }
906                    let expected_hash = match &attempt.kind {
907                        AttemptKind::Signed { payload, .. } => Some(payload.hash),
908                        AttemptKind::Delegated {
909                            status: DelegatedStatus::Pending { hash },
910                            ..
911                        }
912                        | AttemptKind::Legacy { hash } => Some(*hash),
913                        AttemptKind::Delegated { .. } => None,
914                    };
915                    if data.pending.len() > 1
916                        || data.pending.iter().any(|hash| Some(*hash) != expected_hash)
917                        || data
918                            .transactions
919                            .iter()
920                            .skip(start)
921                            .filter_map(|transaction| transaction.hash)
922                            .any(|hash| Some(hash) != expected_hash)
923                    {
924                        bail!("batch submission attempt conflicts with script progress");
925                    }
926                }
927                claimed[start..end].fill(true);
928                match &attempt.kind {
929                    AttemptKind::Signed { request, payload } => {
930                        if request.is_some() != self.batch {
931                            bail!("recovery snapshot signed attempt has an invalid request");
932                        }
933                        let validated = if let [operation] = operations
934                            && !self.batch
935                        {
936                            validate_signed_payload::<N>(
937                                payload.payload.clone(),
938                                &data.transactions[operation.id.index as usize],
939                                deployment.chain,
940                                operation.id.index as usize,
941                                operation_ordinal(
942                                    self.data.sequences(),
943                                    sequence,
944                                    operation.id.index as usize,
945                                ),
946                            )?
947                        } else {
948                            SignedPayload {
949                                hash: signed_payload_hash::<N>(&payload.payload)?,
950                                payload: payload.payload.clone(),
951                            }
952                        };
953                        if validated != *payload {
954                            bail!("recovery snapshot signed payload does not match its hash");
955                        }
956                    }
957                    AttemptKind::Legacy { .. } if !self.batch => {
958                        bail!("ordinary recovery snapshot contains a legacy batch attempt");
959                    }
960                    AttemptKind::Delegated { .. } | AttemptKind::Legacy { .. } => {}
961                }
962            }
963        }
964        Ok(())
965    }
966
967    fn restore_sensitive(&mut self) {
968        for (deployment, data) in self.deployments.iter().zip(self.data.sequences_mut().iter_mut())
969        {
970            for (operation, transaction) in
971                deployment.operations.iter().zip(data.transactions.iter_mut())
972            {
973                transaction.rpc.clone_from(&operation.rpc);
974            }
975        }
976    }
977}
978
979fn operation_fingerprint<N: Network>(transaction: &TransactionWithMetadata<N>) -> Result<B256>
980where
981    N::TxEnvelope: for<'de> Deserialize<'de> + Serialize,
982{
983    let mut transaction = transaction.clone();
984    transaction.hash = None;
985    transaction.rpc.clear();
986    let transaction =
987        serde_json::from_value::<TransactionWithMetadata<N>>(serde_json::to_value(transaction)?)?;
988    let mut value = serde_json::to_value(transaction)?;
989    value.sort_all_objects();
990    Ok(keccak256(serde_json::to_vec(&value)?))
991}
992
993fn load_plan<N: Network>(path: &Path) -> Result<RecoveryPlan<N>>
994where
995    N::TxEnvelope: for<'de> Deserialize<'de>,
996{
997    foundry_common::fs::read_json_file(path)
998        .wrap_err_with(|| format!("recovery snapshot `{}` is corrupt", path.display()))
999}
1000
1001/// Returns whether the previous execution at `paths` submitted anything and left an operation, on
1002/// any chain, with neither a receipt nor a recorded revert. Without a recovery snapshot, progress
1003/// saved before snapshots existed is read from the broadcast export. An unreadable snapshot counts
1004/// as unfinished, as resume would refuse it too.
1005///
1006/// Errors when a broadcast export written with a snapshot has such an operation but the snapshot
1007/// is missing, for example in a checkout without `cache/`: only the snapshot records submission
1008/// attempts, so the export cannot show a submission whose response was lost. Without a snapshot,
1009/// an existing but unreadable export of a non-dry run errors too, as it cannot show anything.
1010fn previous_unfinished<N: Network>(
1011    snapshot: &Path,
1012    paths: &(PathBuf, PathBuf),
1013    multi: bool,
1014) -> Result<bool>
1015where
1016    N::TxEnvelope: for<'de> Deserialize<'de> + Serialize,
1017{
1018    let incomplete = |data: &SequenceData<N>| {
1019        data.sequences().iter().any(|sequence| {
1020            sequence.transactions.iter().any(|tx| {
1021                !tx.hash.is_some_and(|hash| {
1022                    sequence.reverted.contains(&hash)
1023                        || sequence
1024                            .receipts
1025                            .iter()
1026                            .any(|receipt| receipt.transaction_hash() == hash)
1027                })
1028            })
1029        })
1030    };
1031    let (data, attempted) = if snapshot.exists() {
1032        let Ok(plan) = load_plan::<N>(snapshot) else { return Ok(true) };
1033        let attempted = plan.deployments.iter().any(|deployment| !deployment.attempts.is_empty());
1034        (plan.data, attempted)
1035    } else {
1036        let data = if multi {
1037            foundry_common::fs::read_json_file::<MultiChainSequence<N>>(&paths.0)
1038                .map(SequenceData::Multi)
1039        } else {
1040            foundry_common::fs::read_json_file::<ScriptSequence<N>>(&paths.0)
1041                .map(|sequence| SequenceData::Single(Box::new(sequence)))
1042        };
1043        // Dry runs never submit. Their exports sit under `DRY_RUN_DIR`, as laid out by
1044        // `ScriptSequence::get_paths` and `MultiChainSequence::get_paths`.
1045        let dry_run = paths.0.ancestors().nth(if multi { 2 } else { 1 }).and_then(Path::file_name)
1046            == Some(DRY_RUN_DIR.as_ref());
1047        let data = match data {
1048            Ok(data) => data,
1049            // A dangling link counts as an export, since publishing would follow it.
1050            Err(_) if dry_run || paths.0.symlink_metadata().is_err() => return Ok(false),
1051            Err(err) => {
1052                return Err(err).wrap_err(format!(
1053                    "the previous broadcast `{}` is unreadable and its recovery snapshot `{}` is missing, so forge cannot tell whether it left unfinished operations; pass `--start-fresh` to archive it and broadcast anew after confirming that none of its transactions is still pending, or restore the snapshot and finish with `{}`",
1054                    paths.0.display(),
1055                    snapshot.display(),
1056                    if multi { "--multi --resume" } else { "--resume" }
1057                ));
1058            }
1059        };
1060        if data.has_recovery_generation() && !dry_run && incomplete(&data) {
1061            bail!(
1062                "the recovery snapshot `{}` of the previous broadcast `{}` is missing, so forge cannot tell which of its unfinished operations were sent; restore the snapshot and finish with `{}`, or pass `--start-fresh` to archive it and broadcast anew after confirming that none of its transactions is still pending",
1063                snapshot.display(),
1064                paths.0.display(),
1065                if multi { "--multi --resume" } else { "--resume" }
1066            );
1067        }
1068        (data, false)
1069    };
1070    // Transactions saved for owners on other machines hold the approvals collected so far.
1071    let submitted = attempted
1072        || data.sequences().iter().any(|sequence| {
1073            !sequence.awaiting_owners.is_empty()
1074                || sequence.transactions.iter().any(|tx| tx.hash.is_some())
1075        });
1076    Ok(submitted && incomplete(&data))
1077}
1078
1079fn pending_path(path: &Path) -> PathBuf {
1080    path.with_extension("pending")
1081}
1082
1083pub(crate) fn recovery_exists(paths: &(PathBuf, PathBuf)) -> Result<bool> {
1084    let path = recovery_path_from_sensitive(&paths.1)?;
1085    Ok(path.exists() || pending_path(&path).exists())
1086}
1087
1088fn commit_pending_plan(pending: &Path, path: &Path) -> Result<()> {
1089    #[cfg(windows)]
1090    if path.exists() {
1091        std::fs::remove_file(path)?;
1092    }
1093    std::fs::rename(pending, path)?;
1094    #[cfg(unix)]
1095    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
1096    #[cfg(unix)]
1097    File::open(path.parent().context("recovery plan has no parent directory")?)?.sync_all()?;
1098    Ok(())
1099}
1100
1101fn recovery_path_from_sensitive(sensitive_path: &Path) -> Result<PathBuf> {
1102    let filename = sensitive_path.file_name().context("sensitive cache path has no filename")?;
1103    Ok(sensitive_path.with_file_name(format!("{}.recovery.json", filename.to_string_lossy())))
1104}
1105
1106fn signed_payload_hash<N: Network>(payload: &Bytes) -> Result<B256>
1107where
1108    N::TxEnvelope: Decodable2718 + Encodable2718,
1109{
1110    Ok(N::TxEnvelope::decode_2718_exact(payload)
1111        .wrap_err("recovery snapshot contains an invalid signed payload")?
1112        .trie_hash())
1113}
1114
1115fn validate_signed_payload<N: Network>(
1116    payload: Bytes,
1117    planned: &TransactionWithMetadata<N>,
1118    chain: u64,
1119    index: usize,
1120    ordinal: usize,
1121) -> Result<SignedPayload>
1122where
1123    N::TxEnvelope: SignerRecoverable,
1124    N::TransactionRequest: FoundryTransactionBuilder<N>,
1125{
1126    let envelope = N::TxEnvelope::decode_2718_exact(&payload)
1127        .wrap_err("recovery snapshot contains an invalid signed payload")?;
1128    let signer = envelope
1129        .recover_signer()
1130        .wrap_err("recovery snapshot signed payload has an invalid signature")?;
1131    let transaction = planned.tx();
1132    let chain_matches = match transaction {
1133        TransactionMaybeSigned::Signed { tx, .. } => {
1134            envelope.trie_hash() == tx.trie_hash() && tx.chain_id().is_none_or(|id| id == chain)
1135        }
1136        TransactionMaybeSigned::Unsigned(_) => envelope.chain_id() == Some(chain),
1137    };
1138    // The planned nonce is the sender's sequential nonce. A Tempo expiring nonce transaction
1139    // never reads nonce state and is signed with 0 or, from T12, with its complete-plan ordinal as
1140    // the TIP-1106 discriminator. Accept sequence-local indices from older recovery snapshots
1141    // too.
1142    let nonce = envelope.nonce();
1143    let nonce_matches = transaction.nonce() == Some(nonce)
1144        || ((nonce == 0 || nonce == ordinal as u64 || nonce == index as u64)
1145            && <N::TransactionRequest as From<N::TxEnvelope>>::from(envelope.clone()).nonce_key()
1146                == Some(TEMPO_EXPIRING_NONCE_KEY));
1147    if transaction.from() != Some(signer)
1148        || !chain_matches
1149        || !nonce_matches
1150        || transaction.to() != envelope.to()
1151        || transaction.value().unwrap_or_default() != envelope.value()
1152        || transaction.input().cloned().unwrap_or_default() != *envelope.input()
1153        || transaction.authorization_list().as_deref().unwrap_or_default()
1154            != envelope.authorization_list().unwrap_or_default()
1155    {
1156        bail!("signed payload does not match its planned transaction");
1157    }
1158    Ok(SignedPayload { hash: envelope.trie_hash(), payload })
1159}
1160
1161fn validate_delegated_transaction<N: Network>(
1162    transaction: &N::TransactionResponse,
1163    planned: &N::TransactionRequest,
1164    chain: u64,
1165    hash: B256,
1166) -> Result<()>
1167where
1168    N::TransactionRequest: FoundryTransactionBuilder<N>,
1169{
1170    // Preserve network-specific execution fields while allowing the signer to choose gas and fees.
1171    let resolved =
1172        <N::TransactionRequest as From<N::TransactionResponse>>::from(transaction.clone());
1173    let sender = planned.from().context("delegated request has no sender")?;
1174    let planned_tempo_aa = planned.is_tempo_aa();
1175    let resolved_tempo_aa = resolved.is_tempo_aa();
1176    let planned_fields = serde_json::to_value(planned)?;
1177    let resolved_fields = serde_json::to_value(&resolved)?;
1178    let same = |field: &str| planned_fields.get(field) == resolved_fields.get(field);
1179    let same_list = |field: &str| {
1180        let empty = serde_json::Value::Array(Vec::new());
1181        planned_fields.get(field).filter(|value| !value.is_null()).unwrap_or(&empty)
1182            == resolved_fields.get(field).filter(|value| !value.is_null()).unwrap_or(&empty)
1183    };
1184    if transaction.tx_hash() != hash
1185        || transaction.from() != sender
1186        || transaction.chain_id() != Some(chain)
1187        || planned.chain_id() != Some(chain)
1188        || transaction.nonce() != planned.nonce().context("delegated request has no nonce")?
1189        || planned_tempo_aa != resolved_tempo_aa
1190        // A missing `to` and `TxKind::Create` both describe a contract creation.
1191        || (!planned_tempo_aa
1192            && (resolved.kind().unwrap_or(TxKind::Create)
1193                != planned.kind().unwrap_or(TxKind::Create)
1194                || resolved.value().unwrap_or_default() != planned.value().unwrap_or_default()
1195                || resolved.input().unwrap_or_default() != planned.input().unwrap_or_default()))
1196        || transaction.authorization_list().unwrap_or_default()
1197            != planned.authorization_list().map(Vec::as_slice).unwrap_or_default()
1198        || planned.access_list().filter(|list| !list.is_empty())
1199            != resolved.access_list().filter(|list| !list.is_empty())
1200        || planned.blob_versioned_hashes().filter(|hashes| !hashes.is_empty())
1201            != resolved.blob_versioned_hashes().filter(|hashes| !hashes.is_empty())
1202        || (planned_tempo_aa
1203            && canonical_tempo_calls::<N>(planned, &planned_fields)?
1204                != canonical_tempo_calls::<N>(&resolved, &resolved_fields)?)
1205        || !same_list("aaAuthorizationList")
1206        || planned.nonce_key().unwrap_or_default() != resolved.nonce_key().unwrap_or_default()
1207        || planned.fee_token() != resolved.fee_token()
1208        || planned.valid_before() != resolved.valid_before()
1209        || planned.valid_after() != resolved.valid_after()
1210        || !same("keyAuthorization")
1211        || delegated_fee_payer::<N>(planned, sender)?
1212            != delegated_fee_payer::<N>(&resolved, sender)?
1213    {
1214        bail!("resolved transaction does not match its delegated submission attempt");
1215    }
1216    Ok(())
1217}
1218
1219fn canonical_tempo_calls<N: Network>(
1220    request: &N::TransactionRequest,
1221    fields: &serde_json::Value,
1222) -> Result<Vec<serde_json::Value>> {
1223    let mut calls =
1224        fields.get("calls").and_then(serde_json::Value::as_array).cloned().unwrap_or_default();
1225    if let Some(to) = request.kind() {
1226        calls.push(serde_json::to_value(tempo_primitives::transaction::Call {
1227            to,
1228            value: request.value().unwrap_or_default(),
1229            input: request.input().cloned().unwrap_or_default(),
1230        })?);
1231    }
1232    Ok(calls)
1233}
1234
1235fn delegated_fee_payer<N: Network>(
1236    request: &N::TransactionRequest,
1237    sender: Address,
1238) -> Result<Option<Address>>
1239where
1240    N::TransactionRequest: FoundryTransactionBuilder<N>,
1241{
1242    let Some(signature) = request.fee_payer_signature() else { return Ok(None) };
1243    let hash = request
1244        .compute_sponsor_hash(sender)
1245        .context("failed to compute delegated Tempo sponsor hash")?;
1246    Ok(Some(
1247        signature
1248            .recover_address_from_prehash(&hash)
1249            .wrap_err("failed to recover delegated Tempo sponsor")?,
1250    ))
1251}
1252
1253fn write_snapshot<N: Network>(path: &Path, plan: &RecoveryPlan<N>) -> Result<()>
1254where
1255    N::TxEnvelope: Serialize,
1256{
1257    let pending = pending_path(path);
1258    write_plan(&pending, plan)?;
1259    commit_pending_plan(&pending, path)
1260}
1261
1262fn write_plan<N: Network>(path: &Path, plan: &RecoveryPlan<N>) -> Result<()>
1263where
1264    N::TxEnvelope: Serialize,
1265{
1266    let parent = path.parent().context("recovery plan has no parent directory")?;
1267    std::fs::create_dir_all(parent)?;
1268    let mut tmp = NamedTempFile::new_in(parent)?;
1269    #[cfg(unix)]
1270    tmp.as_file().set_permissions(std::fs::Permissions::from_mode(0o600))?;
1271    {
1272        let mut writer = BufWriter::new(tmp.as_file_mut());
1273        serde_json::to_writer_pretty(&mut writer, plan)?;
1274        writer.flush()?;
1275    }
1276    tmp.as_file().sync_all()?;
1277    tmp.persist(path).map_err(|error| error.error)?;
1278    #[cfg(unix)]
1279    File::open(parent)?.sync_all()?;
1280    Ok(())
1281}
1282
1283/// Tempo replay protection excludes sponsor signatures from T1B onward.
1284fn expiring_replay_hash(payload: &[u8], sender_scoped_replay: bool) -> Result<Option<B256>> {
1285    if let Ok(TempoTxEnvelope::AA(tx)) = TempoTxEnvelope::decode_2718_exact(payload)
1286        && tx.tx().is_expiring_nonce_tx()
1287    {
1288        return Ok(Some(if sender_scoped_replay {
1289            tx.expiring_nonce_hash(tx.recover_signer()?)
1290        } else {
1291            *tx.hash()
1292        }));
1293    }
1294    Ok(None)
1295}
1296
1297#[cfg(test)]
1298mod tests {
1299    use super::*;
1300    use alloy_consensus::{
1301        Eip658Value, Receipt, ReceiptEnvelope, ReceiptWithBloom, SignableTransaction, TxEip1559,
1302        TxEnvelope, transaction::Recovered,
1303    };
1304    use alloy_network::Ethereum;
1305    use alloy_primitives::{Bloom, Signature, U256, hex};
1306    use alloy_rpc_types::{Transaction as RpcTransaction, TransactionReceipt, TransactionRequest};
1307    use alloy_signer::SignerSync;
1308    use tempo_alloy::{TempoNetwork, rpc::TempoTransactionRequest};
1309    use tempo_primitives::{AASigned, TempoSignature, transaction::Call};
1310
1311    const SIGNED_TX: &[u8] = &hex!(
1312        "02f86b0180843b9aca008502540be4008252089400000000000000000000000000000000000000016480c001a070d55e79ed3ac9fc8f51e78eb91fd054720d943d66633f2eb1bc960f0126b0eca052eda05a792680de3181e49bab4093541f75b49d1ecbe443077b3660c836016a"
1313    );
1314    const OTHER_SIGNED_TX: &[u8] = &hex!(
1315        "02f86b0180843b9aca008502540be4008252089400000000000000000000000000000000000000018080c001a0cce9a61187b5d18a89ecd27ec675e3b3f10d37f165627ef89a15a7fe76395ce8a07537f5bffb358ffbef22cda84b1c92f7211723f9e09ae037e81686805d3e5505"
1316    );
1317
1318    const ROOT_PRIVATE_KEY: &str =
1319        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
1320
1321    fn sequence(dir: &Path) -> SequenceData<Ethereum> {
1322        let mut transaction = TransactionWithMetadata::from_tx_request(
1323            TransactionMaybeSigned::Unsigned(Default::default()),
1324        );
1325        transaction.rpc = "http://localhost:8545".to_string();
1326        let mut sequence = forge_script_sequence::ScriptSequence::default();
1327        sequence.transactions.push_back(transaction);
1328        sequence.paths = Some((dir.join("broadcast.json"), dir.join("cache.json")));
1329        SequenceData::Single(Box::new(sequence))
1330    }
1331
1332    fn signed_sequence(dir: &Path) -> SequenceData<Ethereum> {
1333        let transactions = [SIGNED_TX, OTHER_SIGNED_TX].map(|payload| {
1334            let envelope = TxEnvelope::decode_2718_exact(payload).unwrap();
1335            let from = envelope.recover_signer().unwrap();
1336            let mut request: TransactionRequest = envelope.into();
1337            request.from = Some(from);
1338            TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::new(request))
1339        });
1340        let mut sequence = forge_script_sequence::ScriptSequence {
1341            chain: 1,
1342            transactions: transactions.into(),
1343            ..Default::default()
1344        };
1345        sequence.paths = Some((dir.join("broadcast.json"), dir.join("cache.json")));
1346        SequenceData::Single(Box::new(sequence))
1347    }
1348
1349    fn delegated_transaction(payload: &[u8]) -> (TransactionRequest, RpcTransaction) {
1350        let envelope = TxEnvelope::decode_2718_exact(payload).unwrap();
1351        let from = envelope.recover_signer().unwrap();
1352        let mut request: TransactionRequest = envelope.clone().into();
1353        request.from = Some(from);
1354        let transaction = RpcTransaction {
1355            inner: Recovered::new_unchecked(envelope, from),
1356            block_hash: None,
1357            block_number: None,
1358            transaction_index: None,
1359            effective_gas_price: None,
1360            block_timestamp: None,
1361        };
1362        (request, transaction)
1363    }
1364
1365    fn tempo_transaction(
1366        request: TempoTransactionRequest,
1367        from: Address,
1368    ) -> RpcTransaction<TempoTxEnvelope> {
1369        let envelope =
1370            TempoTxEnvelope::AA(request.build_aa().unwrap().into_signed(TempoSignature::default()));
1371        RpcTransaction {
1372            inner: Recovered::new_unchecked(envelope, from),
1373            block_hash: None,
1374            block_number: None,
1375            transaction_index: None,
1376            effective_gas_price: None,
1377            block_timestamp: None,
1378        }
1379    }
1380
1381    #[test]
1382    fn expiring_signed_payload_accepts_complete_plan_ordinal_and_legacy_index() {
1383        let signer = foundry_wallets::utils::create_local_signer(ROOT_PRIVATE_KEY).unwrap();
1384        let request = expiring_request(signer.address(), 4217, 8);
1385        let planned =
1386            TransactionWithMetadata::from_tx_request(TransactionMaybeSigned::new(request.clone()));
1387        for nonce in [0, 1, 3, 4] {
1388            let mut request = request.clone();
1389            request.inner.nonce = Some(nonce);
1390            let payload = sign_tempo_payload(request, &signer);
1391            assert_eq!(
1392                validate_signed_payload::<TempoNetwork>(payload, &planned, 4217, 1, 3).is_ok(),
1393                nonce != 4
1394            );
1395        }
1396    }
1397
1398    #[test]
1399    fn identical_expiring_payload_is_rejected_across_same_chain_sequences() {
1400        let dir = tempfile::tempdir().unwrap();
1401        let signer = foundry_wallets::utils::create_local_signer(ROOT_PRIVATE_KEY).unwrap();
1402        // A -> B -> A: the planned nonce on A advances, the signed expiring nonce stays 0.
1403        let deployments = [(4217, 0), (4218, 0), (4217, 1)]
1404            .map(|(chain, nonce)| ScriptSequence::<TempoNetwork> {
1405                chain,
1406                transactions: [TransactionWithMetadata::from_tx_request(
1407                    TransactionMaybeSigned::new(expiring_request(signer.address(), chain, nonce)),
1408                )]
1409                .into(),
1410                ..Default::default()
1411            })
1412            .into();
1413        let data = SequenceData::Multi(MultiChainSequence {
1414            deployments,
1415            path: dir.path().join("broadcast.json"),
1416            sensitive_path: dir.path().join("cache.json"),
1417            timestamp: 0,
1418        });
1419        let payload = sign_tempo_payload(expiring_request(signer.address(), 4217, 0), &signer);
1420
1421        let mut store = RecoveryStore::create(data, false, None).unwrap();
1422        let hash = store.persist_signed_payload(0, 0, payload.clone(), true).unwrap();
1423        assert_eq!(
1424            store.persist_signed_payload(2, 0, payload, true).unwrap_err().to_string(),
1425            format!(
1426                "transaction 0 is identical to an earlier transaction of this script ({hash}) and would be rejected as a replay; identical Tempo expiring nonce transactions are only distinct from the T12 hardfork (TIP-1106)"
1427            )
1428        );
1429    }
1430
1431    fn sign_tempo_sponsor(
1432        request: &mut TempoTransactionRequest,
1433        from: Address,
1434        sponsor: &impl SignerSync,
1435    ) {
1436        request.fee_payer_signature = None;
1437        let hash = request.compute_sponsor_hash(from).unwrap();
1438        request.fee_payer_signature = Some(sponsor.sign_hash_sync(&hash).unwrap());
1439    }
1440
1441    fn load(paths: &(PathBuf, PathBuf), batch: bool) -> Result<RecoveryStore<Ethereum>> {
1442        let lock = RecoveryLock::acquire(paths)?;
1443        RecoveryStore::load(paths, batch, lock)?.context("missing recovery snapshot")
1444    }
1445
1446    #[test]
1447    fn snapshot_is_versioned_private_and_locks_writers() {
1448        let dir = tempfile::tempdir().unwrap();
1449        let data = sequence(dir.path());
1450        let paths = data.paths();
1451        let store = RecoveryStore::create(data, false, None).unwrap();
1452        let value: serde_json::Value = foundry_common::fs::read_json_file(&store.path).unwrap();
1453        assert_eq!(value["version"], RECOVERY_VERSION);
1454        assert_eq!(value["deployments"][0]["operations"][0]["id"]["sequence"], 0);
1455        assert_eq!(value["deployments"][0]["operations"][0]["id"]["index"], 0);
1456        assert!(value["deployments"][0]["operations"][0]["fingerprint"].is_string());
1457        assert!(value["deployments"][0]["operations"][0].get("transaction").is_none());
1458        assert!(RecoveryLock::acquire(&paths).is_err());
1459        #[cfg(unix)]
1460        assert_eq!(store.path.metadata().unwrap().permissions().mode() & 0o777, 0o600);
1461    }
1462
1463    #[test]
1464    fn snapshot_recovers_without_compatibility_exports() {
1465        let dir = tempfile::tempdir().unwrap();
1466        let data = sequence(dir.path());
1467        let paths = data.paths();
1468        let hash = B256::repeat_byte(0x11);
1469        {
1470            let mut store = RecoveryStore::create(data, false, None).unwrap();
1471            let deployment = &mut store.data_mut().sequences_mut()[0];
1472            deployment.transactions[0].hash = Some(hash);
1473            deployment.pending.push(hash);
1474            store.save().unwrap();
1475        }
1476        for path in [&paths.0, &paths.1] {
1477            assert!(!path.exists());
1478        }
1479
1480        let store = load(&paths, false).unwrap();
1481        let deployment = &store.data().sequences()[0];
1482        assert_eq!(deployment.transactions[0].hash, Some(hash));
1483        assert_eq!(deployment.pending, [hash]);
1484        store.data().publish(&paths).unwrap();
1485        assert!(paths.0.exists());
1486        assert!(paths.1.exists());
1487    }
1488
1489    #[test]
1490    fn snapshot_ignores_stale_compatibility_exports() {
1491        let dir = tempfile::tempdir().unwrap();
1492        let data = sequence(dir.path());
1493        let paths = data.paths();
1494        let hash = B256::repeat_byte(0x22);
1495        {
1496            let mut store = RecoveryStore::create(data.clone(), false, None).unwrap();
1497            store.data_mut().sequences_mut()[0].transactions[0].hash = Some(hash);
1498            store.save().unwrap();
1499        }
1500        data.publish(&paths).unwrap();
1501
1502        let store = load(&paths, false).unwrap();
1503        assert_eq!(store.data().sequences()[0].transactions[0].hash, Some(hash));
1504    }
1505
1506    #[test]
1507    fn corrupt_snapshot_fails_closed_even_with_valid_exports() {
1508        let dir = tempfile::tempdir().unwrap();
1509        let data = sequence(dir.path());
1510        let paths = data.paths();
1511        data.publish(&paths).unwrap();
1512        let snapshot = {
1513            let store = RecoveryStore::create(data, false, None).unwrap();
1514            store.path
1515        };
1516        std::fs::write(snapshot, b"{").unwrap();
1517
1518        assert!(load(&paths, false).err().unwrap().to_string().contains("is corrupt"));
1519    }
1520
1521    #[test]
1522    fn interrupted_snapshot_replacement_is_recovered() {
1523        let dir = tempfile::tempdir().unwrap();
1524        let data = sequence(dir.path());
1525        let paths = data.paths();
1526        let hash = B256::repeat_byte(0x33);
1527        let snapshot = {
1528            let mut store = RecoveryStore::create(data, false, None).unwrap();
1529            store.data_mut().sequences_mut()[0].pending.push(hash);
1530            write_plan(&pending_path(&store.path), &store.plan).unwrap();
1531            store.path.clone()
1532        };
1533
1534        let store = load(&paths, false).unwrap();
1535        assert_eq!(store.data().sequences()[0].pending, [hash]);
1536        assert!(snapshot.exists());
1537        assert!(!pending_path(&snapshot).exists());
1538    }
1539
1540    #[test]
1541    fn changed_operations_fail_closed() {
1542        let dir = tempfile::tempdir().unwrap();
1543        let mut store = RecoveryStore::create(sequence(dir.path()), false, None).unwrap();
1544        store.data_mut().sequences_mut()[0].transactions.clear();
1545        assert!(store.save().unwrap_err().to_string().contains("does not match"));
1546    }
1547
1548    #[test]
1549    fn save_rechecks_operations_changed_after_an_earlier_save() {
1550        let dir = tempfile::tempdir().unwrap();
1551        let mut store = RecoveryStore::create(sequence(dir.path()), false, None).unwrap();
1552        store.save().unwrap();
1553        store.data_mut().sequences_mut()[0].transactions[0].hash = Some(B256::repeat_byte(0x11));
1554        store.save().unwrap();
1555        store.data_mut().sequences_mut()[0].transactions[0].function = Some("f()".to_string());
1556        assert!(store.save().unwrap_err().to_string().contains("does not match"));
1557    }
1558
1559    #[test]
1560    fn relocation_preserves_the_authoritative_snapshot() {
1561        let dir = tempfile::tempdir().unwrap();
1562        let data = sequence(dir.path());
1563        let source_paths = data.paths();
1564        let mut store = RecoveryStore::create(data, false, None).unwrap();
1565        let destination = dir.path().join("broadcast-cache.json");
1566        let destination_snapshot = recovery_path_from_sensitive(&destination).unwrap();
1567        let paths = (dir.path().join("broadcasted.json"), destination);
1568        let relocation = store.prepare_relocation(&paths).unwrap();
1569        assert!(RecoveryLock::acquire(&source_paths).is_err());
1570        store.commit_relocation(relocation).unwrap();
1571        assert_eq!(store.path, destination_snapshot);
1572        assert!(destination_snapshot.exists());
1573        RecoveryLock::acquire(&source_paths).unwrap();
1574    }
1575
1576    #[test]
1577    fn signed_payload_is_immutable_and_survives_reload() {
1578        let dir = tempfile::tempdir().unwrap();
1579        let data = signed_sequence(dir.path());
1580        let paths = data.paths();
1581        let expected_hash = {
1582            let mut store = RecoveryStore::create(data, false, None).unwrap();
1583            let hash = store.persist_signed_payload(0, 0, SIGNED_TX.into(), true).unwrap();
1584            assert!(store.persist_signed_payload(0, 0, OTHER_SIGNED_TX.into(), true).is_err());
1585            hash
1586        };
1587
1588        let store = load(&paths, false).unwrap();
1589        let signed = store.signed_payload(0, 0).unwrap();
1590        assert_eq!(signed.payload.as_ref(), SIGNED_TX);
1591        assert_eq!(signed.hash, expected_hash);
1592    }
1593
1594    #[test]
1595    fn signed_payload_is_bound_to_its_planned_operation() {
1596        let dir = tempfile::tempdir().unwrap();
1597        let mut store = RecoveryStore::create(signed_sequence(dir.path()), false, None).unwrap();
1598
1599        assert!(store.persist_signed_payload(1, 0, SIGNED_TX.into(), true).is_err());
1600        assert!(store.persist_signed_payload(0, 1, SIGNED_TX.into(), true).is_err());
1601    }
1602
1603    #[test]
1604    fn delegated_submission_is_immutable_and_survives_reload() {
1605        let dir = tempfile::tempdir().unwrap();
1606        let data = sequence(dir.path());
1607        let paths = data.paths();
1608        let request = TransactionRequest::default();
1609        let hash = B256::repeat_byte(0x42);
1610        {
1611            let mut store = RecoveryStore::create(data, false, None).unwrap();
1612            store.persist_delegated_request(0, 0, request).unwrap();
1613            store.persist_delegated_status(0, 0, DelegatedStatus::Pending { hash }).unwrap();
1614            assert!(store.persist_delegated_request(0, 0, Default::default()).is_err());
1615        }
1616
1617        let store = load(&paths, false).unwrap();
1618        assert!(
1619            matches!(store.delegated_status(0, 0), Some(DelegatedStatus::Pending { hash: value }) if value == hash)
1620        );
1621    }
1622
1623    #[test]
1624    fn delegated_resolution_is_bound_to_its_planned_transaction() {
1625        let (mut request, transaction) = delegated_transaction(SIGNED_TX);
1626        let hash = transaction.tx_hash();
1627        validate_delegated_transaction::<Ethereum>(&transaction, &request, 1, hash).unwrap();
1628
1629        request.gas = Some(100_000);
1630        request.max_fee_per_gas = Some(10_000);
1631        validate_delegated_transaction::<Ethereum>(&transaction, &request, 1, hash).unwrap();
1632
1633        request.blob_versioned_hashes = Some(vec![B256::repeat_byte(0x42)]);
1634        assert!(
1635            validate_delegated_transaction::<Ethereum>(&transaction, &request, 1, hash).is_err()
1636        );
1637
1638        let (other, _) = delegated_transaction(OTHER_SIGNED_TX);
1639        assert!(validate_delegated_transaction::<Ethereum>(&transaction, &other, 1, hash).is_err());
1640    }
1641
1642    #[test]
1643    fn delegated_resolution_matches_creations_by_kind() {
1644        let from = Address::repeat_byte(0x11);
1645        let transaction = |to: TxKind| {
1646            let envelope = TxEnvelope::Eip1559(
1647                TxEip1559 {
1648                    chain_id: 1,
1649                    gas_limit: 100_000,
1650                    max_fee_per_gas: 1,
1651                    max_priority_fee_per_gas: 1,
1652                    to,
1653                    input: Bytes::from_static(&[0x60, 0x00]),
1654                    ..Default::default()
1655                }
1656                .into_signed(Signature::test_signature()),
1657            );
1658            RpcTransaction {
1659                inner: Recovered::new_unchecked(envelope, from),
1660                block_hash: None,
1661                block_number: None,
1662                transaction_index: None,
1663                effective_gas_price: None,
1664                block_timestamp: None,
1665            }
1666        };
1667        // Serialize the planned request the same way the recovery snapshot stores it.
1668        let planned = |to: TxKind| {
1669            let mut request: TransactionRequest = transaction(to).inner.into_inner().into();
1670            request.from = Some(from);
1671            serde_json::from_value::<TransactionRequest>(serde_json::to_value(request).unwrap())
1672                .unwrap()
1673        };
1674        let validate = |transaction: &RpcTransaction, planned: &TransactionRequest| {
1675            validate_delegated_transaction::<Ethereum>(
1676                transaction,
1677                planned,
1678                1,
1679                transaction.tx_hash(),
1680            )
1681        };
1682        let create = transaction(TxKind::Create);
1683        let call = transaction(TxKind::Call(Address::repeat_byte(0x22)));
1684        assert_eq!(planned(TxKind::Create).to, None);
1685
1686        validate(&create, &planned(TxKind::Create)).unwrap();
1687        validate(&call, &planned(TxKind::Call(Address::repeat_byte(0x22)))).unwrap();
1688        assert!(validate(&create, &planned(TxKind::Call(Address::repeat_byte(0x22)))).is_err());
1689        assert!(validate(&call, &planned(TxKind::Create)).is_err());
1690        assert!(validate(&call, &planned(TxKind::Call(Address::repeat_byte(0x33)))).is_err());
1691    }
1692
1693    #[test]
1694    fn delegated_tempo_resolution_matches_creations_by_kind() {
1695        let from = Address::repeat_byte(0x11);
1696        let transaction = |to: TxKind| {
1697            let envelope = TempoTxEnvelope::Eip1559(
1698                TxEip1559 {
1699                    chain_id: 4217,
1700                    gas_limit: 100_000,
1701                    max_fee_per_gas: 1,
1702                    max_priority_fee_per_gas: 1,
1703                    to,
1704                    input: Bytes::from_static(&[0x60, 0x00]),
1705                    ..Default::default()
1706                }
1707                .into_signed(Signature::test_signature()),
1708            );
1709            RpcTransaction {
1710                inner: Recovered::new_unchecked(envelope, from),
1711                block_hash: None,
1712                block_number: None,
1713                transaction_index: None,
1714                effective_gas_price: None,
1715                block_timestamp: None,
1716            }
1717        };
1718        // Serialize the planned request the same way the recovery snapshot stores it.
1719        let planned = |to: TxKind| {
1720            let mut request = <TempoTransactionRequest as From<_>>::from(transaction(to));
1721            request.inner.from = Some(from);
1722            serde_json::from_value::<TempoTransactionRequest>(
1723                serde_json::to_value(request).unwrap(),
1724            )
1725            .unwrap()
1726        };
1727        let validate = |transaction: &RpcTransaction<TempoTxEnvelope>,
1728                        planned: &TempoTransactionRequest| {
1729            validate_delegated_transaction::<TempoNetwork>(
1730                transaction,
1731                planned,
1732                4217,
1733                transaction.tx_hash(),
1734            )
1735        };
1736        let create = transaction(TxKind::Create);
1737        let call = transaction(TxKind::Call(Address::repeat_byte(0x22)));
1738        assert_eq!(planned(TxKind::Create).inner.to, None);
1739        assert!(!planned(TxKind::Create).is_tempo_aa());
1740
1741        validate(&create, &planned(TxKind::Create)).unwrap();
1742        validate(&call, &planned(TxKind::Call(Address::repeat_byte(0x22)))).unwrap();
1743        assert!(validate(&create, &planned(TxKind::Call(Address::repeat_byte(0x22)))).is_err());
1744        assert!(validate(&call, &planned(TxKind::Create)).is_err());
1745    }
1746
1747    #[test]
1748    fn delegated_tempo_resolution_checks_nonce_domain_and_calls() {
1749        let from = Address::repeat_byte(0x11);
1750        let resolved = TempoTransactionRequest {
1751            inner: TransactionRequest {
1752                from: Some(from),
1753                gas: Some(0),
1754                max_fee_per_gas: Some(0),
1755                max_priority_fee_per_gas: Some(0),
1756                nonce: Some(0),
1757                chain_id: Some(4217),
1758                ..Default::default()
1759            },
1760            nonce_key: Some(U256::from(7)),
1761            calls: vec![
1762                Call {
1763                    to: TxKind::Call(Address::repeat_byte(0x22)),
1764                    value: U256::ONE,
1765                    input: Bytes::from_static(&[0x12]),
1766                },
1767                Call {
1768                    to: TxKind::Call(Address::repeat_byte(0x33)),
1769                    value: U256::from(2),
1770                    input: Bytes::from_static(&[0x34]),
1771                },
1772            ],
1773            ..Default::default()
1774        };
1775        let transaction = tempo_transaction(resolved, from);
1776        let mut request = <TempoTransactionRequest as From<_>>::from(transaction.clone());
1777        request.from = Some(from);
1778        let hash = transaction.tx_hash();
1779        validate_delegated_transaction::<TempoNetwork>(&transaction, &request, 4217, hash).unwrap();
1780        assert!(
1781            validate_delegated_transaction::<TempoNetwork>(
1782                &transaction,
1783                &request,
1784                4217,
1785                B256::ZERO,
1786            )
1787            .is_err()
1788        );
1789
1790        request.valid_before = std::num::NonZeroU64::new(1);
1791        assert!(
1792            validate_delegated_transaction::<TempoNetwork>(&transaction, &request, 4217, hash)
1793                .is_err()
1794        );
1795        request.valid_before = None;
1796        request.fee_token = Some(Address::repeat_byte(0x44));
1797        assert!(
1798            validate_delegated_transaction::<TempoNetwork>(&transaction, &request, 4217, hash)
1799                .is_err()
1800        );
1801        request.fee_token = None;
1802
1803        let top_level = request.calls.pop().unwrap();
1804        request.inner.to = Some(top_level.to);
1805        request.inner.value = Some(top_level.value);
1806        request.inner.input = top_level.input.into();
1807        validate_delegated_transaction::<TempoNetwork>(&transaction, &request, 4217, hash).unwrap();
1808
1809        request.nonce_key = Some(U256::from(8));
1810        assert!(
1811            validate_delegated_transaction::<TempoNetwork>(&transaction, &request, 4217, hash)
1812                .is_err()
1813        );
1814        request.nonce_key = Some(U256::from(7));
1815        request.calls.push(Call {
1816            to: request.inner.to.take().unwrap(),
1817            value: request.inner.value.take().unwrap(),
1818            input: request.inner.input.input.take().unwrap(),
1819        });
1820        request.calls.swap(0, 1);
1821        assert!(
1822            validate_delegated_transaction::<TempoNetwork>(&transaction, &request, 4217, hash)
1823                .is_err()
1824        );
1825    }
1826
1827    #[test]
1828    fn delegated_tempo_resolution_checks_sponsor_identity() {
1829        let from = Address::repeat_byte(0x11);
1830        let sponsor = foundry_wallets::utils::create_local_signer(
1831            "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
1832        )
1833        .unwrap();
1834        let other_sponsor = foundry_wallets::utils::create_local_signer(
1835            "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d",
1836        )
1837        .unwrap();
1838        assert_ne!(sponsor.address(), other_sponsor.address());
1839
1840        let mut planned = TempoTransactionRequest {
1841            inner: TransactionRequest {
1842                from: Some(from),
1843                to: Some(TxKind::Call(Address::repeat_byte(0x22))),
1844                gas: Some(100_000),
1845                max_fee_per_gas: Some(10),
1846                max_priority_fee_per_gas: Some(1),
1847                nonce: Some(0),
1848                chain_id: Some(4217),
1849                ..Default::default()
1850            },
1851            nonce_key: Some(U256::from(7)),
1852            ..Default::default()
1853        };
1854        sign_tempo_sponsor(&mut planned, from, &sponsor);
1855
1856        let mut resolved = planned.clone();
1857        resolved.inner.gas = Some(120_000);
1858        resolved.inner.max_fee_per_gas = Some(12);
1859        sign_tempo_sponsor(&mut resolved, from, &sponsor);
1860        let transaction = tempo_transaction(resolved.clone(), from);
1861        validate_delegated_transaction::<TempoNetwork>(
1862            &transaction,
1863            &planned,
1864            4217,
1865            transaction.tx_hash(),
1866        )
1867        .unwrap();
1868
1869        resolved.fee_payer_signature = None;
1870        let transaction = tempo_transaction(resolved.clone(), from);
1871        assert!(
1872            validate_delegated_transaction::<TempoNetwork>(
1873                &transaction,
1874                &planned,
1875                4217,
1876                transaction.tx_hash(),
1877            )
1878            .is_err()
1879        );
1880
1881        sign_tempo_sponsor(&mut resolved, from, &other_sponsor);
1882        let transaction = tempo_transaction(resolved, from);
1883        assert!(
1884            validate_delegated_transaction::<TempoNetwork>(
1885                &transaction,
1886                &planned,
1887                4217,
1888                transaction.tx_hash(),
1889            )
1890            .is_err()
1891        );
1892    }
1893
1894    #[test]
1895    fn definite_non_submission_clears_delegated_request() {
1896        let dir = tempfile::tempdir().unwrap();
1897        let data = sequence(dir.path());
1898        let paths = data.paths();
1899        let mut store = RecoveryStore::create(data, false, None).unwrap();
1900        store.persist_delegated_request(0, 0, Default::default()).unwrap();
1901        store.clear_delegated_request(0, 0).unwrap();
1902        assert!(store.delegated_status(0, 0).is_none());
1903        drop(store);
1904
1905        assert!(load(&paths, false).unwrap().delegated_status(0, 0).is_none());
1906    }
1907
1908    #[test]
1909    fn batch_attempt_uses_shared_membership_and_survives_reload() {
1910        let dir = tempfile::tempdir().unwrap();
1911        let data = signed_sequence(dir.path());
1912        let paths = data.paths();
1913        let request = TransactionRequest::default();
1914        {
1915            let mut store = RecoveryStore::create(data, true, None).unwrap();
1916            store.persist_batch_signed_payload(0, 0, request.clone(), SIGNED_TX.into()).unwrap();
1917            assert!(store.persist_signed_payload(0, 1, OTHER_SIGNED_TX.into(), true).is_err());
1918        }
1919
1920        let store = load(&paths, true).unwrap();
1921        let Some((0, _, AttemptKind::Signed { request: Some(saved), .. })) = store.batch_attempt(0)
1922        else {
1923            panic!("expected signed batch attempt");
1924        };
1925        assert_eq!(saved, &request);
1926    }
1927
1928    #[test]
1929    fn batch_attempt_rejects_conflicting_progress() {
1930        let foreign = B256::repeat_byte(0x66);
1931        for (transaction_hash, pending) in [(Some(foreign), vec![]), (None, vec![foreign])] {
1932            let dir = tempfile::tempdir().unwrap();
1933            let data = signed_sequence(dir.path());
1934            let paths = data.paths();
1935            {
1936                let mut store = RecoveryStore::create(data, true, None).unwrap();
1937                store
1938                    .persist_batch_signed_payload(
1939                        0,
1940                        0,
1941                        TransactionRequest::default(),
1942                        SIGNED_TX.into(),
1943                    )
1944                    .unwrap();
1945                let deployment = &mut store.data_mut().sequences_mut()[0];
1946                deployment.transactions[0].hash = transaction_hash;
1947                deployment.pending = pending;
1948                write_snapshot(&store.path, &store.plan).unwrap();
1949            }
1950
1951            assert!(load(&paths, true).is_err());
1952        }
1953    }
1954
1955    #[test]
1956    fn batch_progress_without_an_attempt_fails_closed() {
1957        let dir = tempfile::tempdir().unwrap();
1958        let data = signed_sequence(dir.path());
1959        let paths = data.paths();
1960        {
1961            let mut store = RecoveryStore::create(data, true, None).unwrap();
1962            store.data_mut().sequences_mut()[0].pending.push(B256::repeat_byte(0x77));
1963            write_snapshot(&store.path, &store.plan).unwrap();
1964        }
1965
1966        assert!(load(&paths, true).is_err());
1967    }
1968
1969    #[test]
1970    fn legacy_batch_import_requires_one_consistent_pending_hash() {
1971        let dir = tempfile::tempdir().unwrap();
1972        let mut data = signed_sequence(dir.path());
1973        let paths = data.paths();
1974        let hash = B256::repeat_byte(0x55);
1975        let deployment = &mut data.sequences_mut()[0];
1976        for transaction in &mut deployment.transactions {
1977            transaction.hash = Some(hash);
1978        }
1979        deployment.pending.push(hash);
1980        let store =
1981            RecoveryStore::import(data, true, RecoveryLock::acquire(&paths).unwrap()).unwrap();
1982        assert!(
1983            matches!(store.batch_attempt(0), Some((0, _, AttemptKind::Legacy { hash: saved })) if *saved == hash)
1984        );
1985        drop(store);
1986
1987        let other = tempfile::tempdir().unwrap();
1988        let mut data = signed_sequence(other.path());
1989        let paths = data.paths();
1990        let deployment = &mut data.sequences_mut()[0];
1991        deployment.transactions[1].hash = Some(hash);
1992        deployment.pending.push(hash);
1993        assert!(RecoveryStore::import(data, true, RecoveryLock::acquire(&paths).unwrap()).is_err());
1994    }
1995
1996    #[test]
1997    fn legacy_batch_import_accepts_a_receipted_prefix() {
1998        let dir = tempfile::tempdir().unwrap();
1999        let mut data = signed_sequence(dir.path());
2000        let paths = data.paths();
2001        let completed = B256::repeat_byte(0x44);
2002        let pending = B256::repeat_byte(0x55);
2003        let deployment = &mut data.sequences_mut()[0];
2004        deployment.transactions[0].hash = Some(completed);
2005        deployment.transactions[1].hash = Some(pending);
2006        let completed_receipt = TransactionReceipt {
2007            inner: ReceiptEnvelope::Legacy(ReceiptWithBloom {
2008                receipt: Receipt {
2009                    status: Eip658Value::success(),
2010                    cumulative_gas_used: 0,
2011                    logs: Vec::new(),
2012                },
2013                logs_bloom: Bloom::ZERO,
2014            }),
2015            transaction_hash: completed,
2016            transaction_index: None,
2017            block_hash: None,
2018            block_number: None,
2019            gas_used: 0,
2020            effective_gas_price: 0,
2021            blob_gas_used: None,
2022            blob_gas_price: None,
2023            from: Address::ZERO,
2024            to: None,
2025            contract_address: None,
2026        };
2027        deployment.receipts.push(completed_receipt);
2028        deployment.pending.push(pending);
2029
2030        let store =
2031            RecoveryStore::import(data, true, RecoveryLock::acquire(&paths).unwrap()).unwrap();
2032        assert!(
2033            matches!(store.batch_attempt(0), Some((1, _, AttemptKind::Legacy { hash })) if *hash == pending)
2034        );
2035    }
2036
2037    #[test]
2038    fn rejected_legacy_batch_import_does_not_publish_a_snapshot() {
2039        let dir = tempfile::tempdir().unwrap();
2040        let mut data = signed_sequence(dir.path());
2041        let paths = data.paths();
2042        data.sequences_mut()[0].transactions[0].hash = Some(B256::repeat_byte(0x55));
2043        let snapshot = recovery_path_from_sensitive(&paths.1).unwrap();
2044
2045        assert!(RecoveryStore::import(data, true, RecoveryLock::acquire(&paths).unwrap()).is_err());
2046        assert!(!snapshot.exists());
2047    }
2048
2049    #[test]
2050    fn expiring_replay_guard_ignores_sponsor_changes_and_keeps_discriminators() {
2051        let dir = tempfile::tempdir().unwrap();
2052        let sender = foundry_wallets::utils::create_local_signer(ROOT_PRIVATE_KEY).unwrap();
2053        let sponsor = foundry_wallets::utils::create_local_signer(
2054            "0x59c6995e998f97a5a004497e5da3b5d2b2b66a87f064d39c44da0b6d6e4f8ff0",
2055        )
2056        .unwrap();
2057        let request = |nonce| expiring_request(sender.address(), 4217, nonce);
2058        let data = SequenceData::Multi(MultiChainSequence {
2059            deployments: [0, 1]
2060                .map(|nonce| ScriptSequence::<TempoNetwork> {
2061                    chain: 4217,
2062                    transactions: [TransactionWithMetadata::from_tx_request(
2063                        TransactionMaybeSigned::new(request(nonce)),
2064                    )]
2065                    .into(),
2066                    ..Default::default()
2067                })
2068                .into(),
2069            path: dir.path().join("broadcast.json"),
2070            sensitive_path: dir.path().join("cache.json"),
2071            timestamp: 0,
2072        });
2073        let payload = |nonce, sponsor: &_| {
2074            let mut request = request(nonce);
2075            sign_tempo_sponsor(&mut request, sender.address(), sponsor);
2076            sign_tempo_payload(request, &sender)
2077        };
2078        let first = payload(0, &sender);
2079        let duplicate = payload(0, &sponsor);
2080        assert_ne!(
2081            signed_payload_hash::<TempoNetwork>(&first).unwrap(),
2082            signed_payload_hash::<TempoNetwork>(&duplicate).unwrap()
2083        );
2084        assert_eq!(
2085            expiring_replay_hash(&first, true).unwrap(),
2086            expiring_replay_hash(&duplicate, true).unwrap()
2087        );
2088        let mut store = RecoveryStore::create(data, false, None).unwrap();
2089        let first_hash = store.persist_signed_payload(0, 0, first, true).unwrap();
2090        assert_eq!(store.signed_payload(0, 0).unwrap().hash, first_hash);
2091        let snapshot = std::fs::read(&store.path).unwrap();
2092        let duplicate_hash = signed_payload_hash::<TempoNetwork>(&duplicate).unwrap();
2093        assert_eq!(
2094            store.persist_signed_payload(1, 0, duplicate.clone(), true).unwrap_err().to_string(),
2095            format!(
2096                "transaction 0 is identical to an earlier transaction of this script ({duplicate_hash}) and would be rejected as a replay; identical Tempo expiring nonce transactions are only distinct from the T12 hardfork (TIP-1106)"
2097            )
2098        );
2099        assert!(store.signed_payload(1, 0).is_none());
2100        assert_eq!(std::fs::read(&store.path).unwrap(), snapshot);
2101        // Older snapshots may already contain a conflicting durable attempt.
2102        let id = store.plan.deployments[1].operations[0].id;
2103        store.plan.deployments[1].attempts.push(SubmissionAttempt {
2104            id: B256::random(),
2105            members: vec![id],
2106            kind: AttemptKind::Signed {
2107                request: None,
2108                payload: SignedPayload { payload: duplicate.clone(), hash: duplicate_hash },
2109            },
2110        });
2111        assert!(store.persist_signed_payload(1, 0, duplicate.clone(), true).is_err());
2112        store.plan.deployments[1].attempts.clear();
2113        // T1/T1A use envelope hashes, so the differently sponsored payload is executable.
2114        assert_eq!(store.persist_signed_payload(1, 0, duplicate, false).unwrap(), duplicate_hash);
2115        store.plan.deployments[1].attempts.clear();
2116        // T12 discriminators distinguish the second operation despite the sponsor change.
2117        let distinct = payload(1, &sponsor);
2118        let distinct_hash = signed_payload_hash::<TempoNetwork>(&distinct).unwrap();
2119        assert_eq!(store.persist_signed_payload(1, 0, distinct, true).unwrap(), distinct_hash);
2120        assert_eq!(store.signed_payload(1, 0).unwrap().hash, distinct_hash);
2121    }
2122
2123    fn expiring_request(from: Address, chain_id: u64, nonce: u64) -> TempoTransactionRequest {
2124        TempoTransactionRequest {
2125            inner: TransactionRequest {
2126                from: Some(from),
2127                to: Some(TxKind::Call(Address::with_last_byte(2))),
2128                chain_id: Some(chain_id),
2129                nonce: Some(nonce),
2130                gas: Some(100_000),
2131                max_fee_per_gas: Some(10),
2132                max_priority_fee_per_gas: Some(1),
2133                ..Default::default()
2134            },
2135            nonce_key: Some(TEMPO_EXPIRING_NONCE_KEY),
2136            valid_before: std::num::NonZeroU64::new(100),
2137            ..Default::default()
2138        }
2139    }
2140
2141    fn sign_tempo_payload(request: TempoTransactionRequest, signer: &impl SignerSync) -> Bytes {
2142        let tx = request.build_aa().unwrap();
2143        let signature = signer.sign_hash_sync(&tx.signature_hash()).unwrap();
2144        Bytes::from(
2145            TempoTxEnvelope::AA(AASigned::new_unhashed(tx, TempoSignature::from(signature)))
2146                .encoded_2718(),
2147        )
2148    }
2149
2150    #[test]
2151    fn sponsor_survives_reload_and_defaults_to_none() {
2152        let dir = tempfile::tempdir().unwrap();
2153        let data = sequence(dir.path());
2154        let paths = data.paths();
2155        let sponsor = Address::repeat_byte(0x55);
2156        let snapshot = RecoveryStore::create(data, false, Some(sponsor)).unwrap().path;
2157        let store = load(&paths, false).unwrap();
2158        assert_eq!(store.sponsor(), Some(sponsor));
2159        drop(store);
2160
2161        // Snapshots written before the sponsor was recorded load without one.
2162        let mut value: serde_json::Value = foundry_common::fs::read_json_file(&snapshot).unwrap();
2163        assert_eq!(value["sponsor"], serde_json::json!(sponsor));
2164        value.as_object_mut().unwrap().remove("sponsor");
2165        std::fs::write(&snapshot, serde_json::to_vec(&value).unwrap()).unwrap();
2166        assert_eq!(load(&paths, false).unwrap().sponsor(), None);
2167    }
2168
2169    #[test]
2170    fn new_execution_refuses_unfinished_progress() {
2171        let dir = tempfile::tempdir().unwrap();
2172        let paths = sequence(dir.path()).paths();
2173        let refused = format!(
2174            "the previous broadcast `{}` has unfinished operations; finish it with `--resume`, or pass `--start-fresh` to archive it and broadcast anew",
2175            paths.0.display()
2176        );
2177        let create = || RecoveryStore::create(sequence(dir.path()), false, None).map(|_| ());
2178
2179        // Progress without any submission is replaced.
2180        create().unwrap();
2181        create().unwrap();
2182
2183        // A submission attempt makes it unfinished, also when its commit was interrupted.
2184        let mut store = RecoveryStore::create(sequence(dir.path()), false, None).unwrap();
2185        store.persist_delegated_request(0, 0, Default::default()).unwrap();
2186        let snapshot = store.path.clone();
2187        drop(store);
2188        assert_eq!(create().unwrap_err().to_string(), refused);
2189        std::fs::rename(&snapshot, pending_path(&snapshot)).unwrap();
2190        RecoveryStore::<Ethereum>::archive_unfinished(&sequence(dir.path())).unwrap();
2191        assert!(!snapshot.exists() && !pending_path(&snapshot).exists());
2192        create().unwrap();
2193
2194        // An unreadable snapshot is never silently replaced.
2195        std::fs::write(&snapshot, "garbage").unwrap();
2196        assert_eq!(create().unwrap_err().to_string(), refused);
2197        RecoveryStore::<Ethereum>::archive_unfinished(&sequence(dir.path())).unwrap();
2198        create().unwrap();
2199
2200        // Without a snapshot, progress saved before snapshots existed is checked.
2201        std::fs::remove_file(&snapshot).unwrap();
2202        let mut legacy = sequence(dir.path());
2203        legacy.sequences_mut()[0].transactions[0].hash = Some(B256::ZERO);
2204        foundry_common::fs::write_json_file(&paths.0, &legacy.sequences()[0]).unwrap();
2205        assert_eq!(create().unwrap_err().to_string(), refused);
2206        RecoveryStore::<Ethereum>::archive_unfinished(&sequence(dir.path())).unwrap();
2207        assert!(!paths.0.exists());
2208        create().unwrap();
2209
2210        // An export written with a snapshot cannot show a submission whose response was lost, so
2211        // without its snapshot it blocks while any operation is incomplete, even without hashes.
2212        std::fs::remove_file(&snapshot).unwrap();
2213        let mut export = sequence(dir.path());
2214        export.set_recovery_generation(B256::ZERO);
2215        export.publish(&paths).unwrap();
2216        assert_eq!(
2217            create().unwrap_err().to_string(),
2218            format!(
2219                "the recovery snapshot `{}` of the previous broadcast `{}` is missing, so forge cannot tell which of its unfinished operations were sent; restore the snapshot and finish with `--resume`, or pass `--start-fresh` to archive it and broadcast anew after confirming that none of its transactions is still pending",
2220                snapshot.display(),
2221                paths.0.display()
2222            )
2223        );
2224        RecoveryStore::<Ethereum>::archive_unfinished(&sequence(dir.path())).unwrap();
2225        assert!(!paths.0.exists());
2226        create().unwrap();
2227
2228        // A completed export without its snapshot does not block.
2229        std::fs::remove_file(&snapshot).unwrap();
2230        export.sequences_mut()[0].transactions[0].hash = Some(B256::ZERO);
2231        export.sequences_mut()[0].reverted.push(B256::ZERO);
2232        export.publish(&paths).unwrap();
2233        create().unwrap();
2234
2235        // Dry runs never submit, so their exports never block, in either layout.
2236        let single = sequence(dir.path());
2237        let multi = SequenceData::Multi(MultiChainSequence {
2238            deployments: single.sequences().to_vec(),
2239            path: PathBuf::new(),
2240            sensitive_path: PathBuf::new(),
2241            timestamp: 0,
2242        });
2243        for (mut dry_run, export) in
2244            [(single, "dry-run/run.json"), (multi, "multi/dry-run/Script.s.sol-latest/run.json")]
2245        {
2246            let export = dir.path().join(export);
2247            let paths = (export.clone(), export.with_file_name("cache.json"));
2248            std::fs::create_dir_all(export.parent().unwrap()).unwrap();
2249            dry_run.set_recovery_generation(B256::ZERO);
2250            dry_run.publish(&paths).unwrap();
2251            dry_run.set_paths(paths);
2252            RecoveryStore::create(dry_run, false, None).unwrap();
2253        }
2254    }
2255}