Skip to main content

soroban_cli/commands/contract/
restore.rs

1use std::{fmt::Debug, path::Path, str::FromStr};
2
3use crate::{
4    log::extract_events,
5    tx::sim_sign_and_send_tx,
6    xdr::{
7        Error as XdrError, ExtensionPoint, LedgerEntry, LedgerEntryChange, LedgerEntryData,
8        LedgerFootprint, Limits, Memo, Operation, OperationBody, Preconditions, RestoreFootprintOp,
9        SequenceNumber, SorobanResources, SorobanTransactionData, SorobanTransactionDataExt,
10        Transaction, TransactionExt, TransactionMeta, TransactionMetaV3, TransactionMetaV4,
11        TtlEntry, WriteXdr,
12    },
13};
14use clap::Parser;
15use stellar_strkey::DecodeError;
16
17use crate::commands::tx::fetch;
18use crate::{
19    commands::{
20        contract::extend,
21        global,
22        txn_result::{TxnEnvelopeResult, TxnResult},
23        HEADING_TRANSACTION,
24    },
25    config::{self, data, locator, network},
26    key, rpc, wasm, Pwd,
27};
28
29#[derive(Parser, Debug, Clone)]
30#[group(skip)]
31pub struct Cmd {
32    #[command(flatten)]
33    pub key: key::Args,
34
35    /// Number of ledgers to extend the entry
36    #[arg(long)]
37    pub ledgers_to_extend: Option<u32>,
38
39    /// Only print the new Time To Live ledger
40    #[arg(long)]
41    pub ttl_ledger_only: bool,
42
43    #[command(flatten)]
44    pub config: config::Args,
45
46    #[command(flatten)]
47    pub resources: crate::resources::Args,
48
49    /// Build the transaction and only write the base64 xdr to stdout
50    #[arg(long, help_heading = HEADING_TRANSACTION)]
51    pub build_only: bool,
52}
53
54impl FromStr for Cmd {
55    type Err = clap::error::Error;
56
57    fn from_str(s: &str) -> Result<Self, Self::Err> {
58        use clap::{CommandFactory, FromArgMatches};
59        Self::from_arg_matches_mut(&mut Self::command().get_matches_from(s.split_whitespace()))
60    }
61}
62
63impl Pwd for Cmd {
64    fn set_pwd(&mut self, pwd: &Path) {
65        self.config.set_pwd(pwd);
66    }
67}
68
69#[derive(thiserror::Error, Debug)]
70pub enum Error {
71    #[error("parsing key {key}: {error}")]
72    CannotParseKey {
73        key: String,
74        error: soroban_spec_tools::Error,
75    },
76
77    #[error("parsing XDR key {key}: {error}")]
78    CannotParseXdrKey { key: String, error: XdrError },
79
80    #[error("cannot parse contract ID {0}: {1}")]
81    CannotParseContractId(String, DecodeError),
82
83    #[error(transparent)]
84    Config(#[from] config::Error),
85
86    #[error("either `--key` or `--key-xdr` are required")]
87    KeyIsRequired,
88
89    #[error("xdr processing error: {0}")]
90    Xdr(#[from] XdrError),
91
92    #[error("Ledger entry not found")]
93    LedgerEntryNotFound,
94
95    #[error(transparent)]
96    Locator(#[from] locator::Error),
97
98    #[error("missing operation result")]
99    MissingOperationResult,
100
101    #[error(transparent)]
102    Rpc(#[from] rpc::Error),
103
104    #[error(transparent)]
105    Wasm(#[from] wasm::Error),
106
107    #[error(transparent)]
108    Key(#[from] key::Error),
109
110    #[error(transparent)]
111    Extend(#[from] extend::Error),
112
113    #[error(transparent)]
114    Data(#[from] data::Error),
115
116    #[error(transparent)]
117    Network(#[from] network::Error),
118
119    #[error(transparent)]
120    Fee(#[from] fetch::fee::Error),
121
122    #[error(transparent)]
123    Fetch(#[from] fetch::Error),
124}
125
126impl Cmd {
127    #[allow(clippy::too_many_lines)]
128    pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
129        let res = self
130            .execute(&self.config, global_args.quiet, global_args.no_cache)
131            .await?
132            .to_envelope();
133        let expiration_ledger_seq = match res {
134            TxnEnvelopeResult::TxnEnvelope(tx) => {
135                println!("{}", tx.to_xdr_base64(Limits::none())?);
136                return Ok(());
137            }
138            TxnEnvelopeResult::Res(res) => res,
139        };
140        if let Some(ledgers_to_extend) = self.ledgers_to_extend {
141            extend::Cmd {
142                key: self.key.clone(),
143                ledgers_to_extend,
144                config: self.config.clone(),
145                resources: self.resources.clone(),
146                ttl_ledger_only: false,
147                build_only: self.build_only,
148            }
149            .run(global_args)
150            .await?;
151        } else {
152            println!("New ttl ledger: {expiration_ledger_seq}");
153        }
154
155        Ok(())
156    }
157
158    pub async fn execute(
159        &self,
160        config: &config::Args,
161        quiet: bool,
162        no_cache: bool,
163    ) -> Result<TxnResult<u32>, Error> {
164        let print = crate::print::Print::new(quiet);
165        let network = config.get_network()?;
166        tracing::trace!(?network);
167        let entry_keys = self.key.parse_keys(&config.locator, &network)?;
168        let client = network.rpc_client()?;
169        client
170            .verify_network_passphrase(Some(&network.network_passphrase))
171            .await?;
172        let source_account = config.source_account()?;
173
174        // Get the account sequence number
175        let account_details = client
176            .get_account(&source_account.clone().to_string())
177            .await?;
178        let sequence: i64 = account_details.seq_num.into();
179
180        let tx = Box::new(Transaction {
181            source_account,
182            fee: config.get_inclusion_fee()?,
183            seq_num: SequenceNumber(sequence + 1),
184            cond: Preconditions::None,
185            memo: Memo::None,
186            operations: vec![Operation {
187                source_account: None,
188                body: OperationBody::RestoreFootprint(RestoreFootprintOp {
189                    ext: ExtensionPoint::V0,
190                }),
191            }]
192            .try_into()?,
193            ext: TransactionExt::V1(SorobanTransactionData {
194                ext: SorobanTransactionDataExt::V0,
195                resources: SorobanResources {
196                    footprint: LedgerFootprint {
197                        read_only: vec![].try_into()?,
198                        read_write: entry_keys.clone().try_into()?,
199                    },
200                    instructions: self.resources.instructions.unwrap_or_default(),
201                    disk_read_bytes: 0,
202                    write_bytes: 0,
203                },
204                resource_fee: 0,
205            }),
206        });
207        if self.build_only {
208            return Ok(TxnResult::Txn(tx));
209        }
210
211        let res = sim_sign_and_send_tx::<Error>(
212            &client,
213            &tx,
214            config,
215            &self.resources,
216            &[],
217            quiet,
218            no_cache,
219        )
220        .await?;
221
222        let meta = res
223            .result_meta
224            .as_ref()
225            .ok_or(Error::MissingOperationResult)?;
226
227        tracing::trace!(?meta);
228
229        let events = extract_events(meta);
230
231        crate::log::event::all(&events);
232        crate::log::event::contract(&events, &print);
233
234        // The transaction from core will succeed regardless of whether it actually found &
235        // restored the entry, so we have to inspect the result meta to tell if it worked or not.
236        let changes = match meta {
237            TransactionMeta::V4(TransactionMetaV4 { operations, .. }) => {
238                // Simply check if there is exactly one entry here. We only support restoring a single
239                // entry via this command (which we should fix separately, but).
240                if operations.is_empty() {
241                    return Err(Error::LedgerEntryNotFound);
242                }
243
244                operations[0].changes.clone()
245            }
246            TransactionMeta::V3(TransactionMetaV3 { operations, .. }) => {
247                // Simply check if there is exactly one entry here. We only support restoring a single
248                // entry via this command (which we should fix separately, but).
249                if operations.is_empty() {
250                    return Err(Error::LedgerEntryNotFound);
251                }
252
253                operations[0].changes.clone()
254            }
255            _ => return Err(Error::LedgerEntryNotFound),
256        };
257        tracing::debug!("Changes:\nlen:{}\n{changes:#?}", changes.len());
258
259        if changes.is_empty() {
260            print.infoln("No changes detected, transaction was a no-op.");
261            let entry = client.get_full_ledger_entries(&entry_keys).await?;
262            let extension = entry.entries[0].live_until_ledger_seq.unwrap_or_default();
263
264            return Ok(TxnResult::Res(extension));
265        }
266
267        Ok(TxnResult::Res(
268            parse_changes(&changes.to_vec()).ok_or(Error::LedgerEntryNotFound)?,
269        ))
270    }
271}
272
273fn parse_changes(changes: &[LedgerEntryChange]) -> Option<u32> {
274    changes
275        .iter()
276        .filter_map(|change| match change {
277            LedgerEntryChange::Restored(LedgerEntry {
278                data:
279                    LedgerEntryData::Ttl(TtlEntry {
280                        live_until_ledger_seq,
281                        ..
282                    }),
283                ..
284            })
285            | LedgerEntryChange::Updated(LedgerEntry {
286                data:
287                    LedgerEntryData::Ttl(TtlEntry {
288                        live_until_ledger_seq,
289                        ..
290                    }),
291                ..
292            })
293            | LedgerEntryChange::Created(LedgerEntry {
294                data:
295                    LedgerEntryData::Ttl(TtlEntry {
296                        live_until_ledger_seq,
297                        ..
298                    }),
299                ..
300            }) => Some(*live_until_ledger_seq),
301            _ => None,
302        })
303        .max()
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::xdr::{
310        ContractDataDurability::Persistent, ContractDataEntry, ContractId, Hash, LedgerEntry,
311        LedgerEntryChange, LedgerEntryData, ScAddress, ScSymbol, ScVal, SequenceNumber, StringM,
312        TtlEntry,
313    };
314
315    #[test]
316    fn test_parse_changes_two_changes_restored() {
317        // Test the original expected format with 2 changes
318        let ttl_entry = TtlEntry {
319            live_until_ledger_seq: 12345,
320            key_hash: Hash([0; 32]),
321        };
322
323        let changes = vec![
324            LedgerEntryChange::State(LedgerEntry {
325                data: LedgerEntryData::Ttl(ttl_entry.clone()),
326                last_modified_ledger_seq: 0,
327                ext: crate::xdr::LedgerEntryExt::V0,
328            }),
329            LedgerEntryChange::Restored(LedgerEntry {
330                data: LedgerEntryData::Ttl(ttl_entry),
331                last_modified_ledger_seq: 0,
332                ext: crate::xdr::LedgerEntryExt::V0,
333            }),
334        ];
335
336        let result = parse_changes(&changes);
337        assert_eq!(result, Some(12345));
338    }
339
340    #[test]
341    fn test_parse_two_changes_that_had_expired() {
342        let ttl_entry = TtlEntry {
343            live_until_ledger_seq: 55555,
344            key_hash: Hash([0; 32]),
345        };
346
347        let counter = "COUNTER".parse::<StringM<32>>().unwrap();
348        let contract_data_entry = ContractDataEntry {
349            ext: ExtensionPoint::default(),
350            contract: ScAddress::Contract(ContractId(Hash([0; 32]))),
351            key: ScVal::Symbol(ScSymbol(counter)),
352            durability: Persistent,
353            val: ScVal::U32(1),
354        };
355
356        let changes = vec![
357            LedgerEntryChange::Restored(LedgerEntry {
358                data: LedgerEntryData::Ttl(ttl_entry.clone()),
359                last_modified_ledger_seq: 37429,
360                ext: crate::xdr::LedgerEntryExt::V0,
361            }),
362            LedgerEntryChange::Restored(LedgerEntry {
363                data: LedgerEntryData::ContractData(contract_data_entry.clone()),
364                last_modified_ledger_seq: 37429,
365                ext: crate::xdr::LedgerEntryExt::V0,
366            }),
367        ];
368
369        let result = parse_changes(&changes);
370        assert_eq!(result, Some(55555));
371    }
372
373    #[test]
374    fn test_parse_changes_two_changes_updated() {
375        // Test the original expected format with 2 changes, but second change is Updated
376        let ttl_entry = TtlEntry {
377            live_until_ledger_seq: 67890,
378            key_hash: Hash([0; 32]),
379        };
380
381        let changes = vec![
382            LedgerEntryChange::State(LedgerEntry {
383                data: LedgerEntryData::Ttl(ttl_entry.clone()),
384                last_modified_ledger_seq: 0,
385                ext: crate::xdr::LedgerEntryExt::V0,
386            }),
387            LedgerEntryChange::Updated(LedgerEntry {
388                data: LedgerEntryData::Ttl(ttl_entry),
389                last_modified_ledger_seq: 0,
390                ext: crate::xdr::LedgerEntryExt::V0,
391            }),
392        ];
393
394        let result = parse_changes(&changes);
395        assert_eq!(result, Some(67890));
396    }
397
398    #[test]
399    fn test_parse_changes_two_changes_created() {
400        // Test the original expected format with 2 changes, but second change is Created
401        let ttl_entry = TtlEntry {
402            live_until_ledger_seq: 11111,
403            key_hash: Hash([0; 32]),
404        };
405
406        let changes = vec![
407            LedgerEntryChange::State(LedgerEntry {
408                data: LedgerEntryData::Ttl(ttl_entry.clone()),
409                last_modified_ledger_seq: 0,
410                ext: crate::xdr::LedgerEntryExt::V0,
411            }),
412            LedgerEntryChange::Created(LedgerEntry {
413                data: LedgerEntryData::Ttl(ttl_entry),
414                last_modified_ledger_seq: 0,
415                ext: crate::xdr::LedgerEntryExt::V0,
416            }),
417        ];
418
419        let result = parse_changes(&changes);
420        assert_eq!(result, Some(11111));
421    }
422
423    #[test]
424    fn test_parse_changes_single_change_restored() {
425        // Test the new single change format with Restored type
426        let ttl_entry = TtlEntry {
427            live_until_ledger_seq: 22222,
428            key_hash: Hash([0; 32]),
429        };
430
431        let changes = vec![LedgerEntryChange::Restored(LedgerEntry {
432            data: LedgerEntryData::Ttl(ttl_entry),
433            last_modified_ledger_seq: 0,
434            ext: crate::xdr::LedgerEntryExt::V0,
435        })];
436
437        let result = parse_changes(&changes);
438        assert_eq!(result, Some(22222));
439    }
440
441    #[test]
442    fn test_parse_changes_single_change_updated() {
443        // Test the new single change format with Updated type
444        let ttl_entry = TtlEntry {
445            live_until_ledger_seq: 33333,
446            key_hash: Hash([0; 32]),
447        };
448
449        let changes = vec![LedgerEntryChange::Updated(LedgerEntry {
450            data: LedgerEntryData::Ttl(ttl_entry),
451            last_modified_ledger_seq: 0,
452            ext: crate::xdr::LedgerEntryExt::V0,
453        })];
454
455        let result = parse_changes(&changes);
456        assert_eq!(result, Some(33333));
457    }
458
459    #[test]
460    fn test_parse_changes_single_change_created() {
461        // Test the new single change format with Created type
462        let ttl_entry = TtlEntry {
463            live_until_ledger_seq: 44444,
464            key_hash: Hash([0; 32]),
465        };
466
467        let changes = vec![LedgerEntryChange::Created(LedgerEntry {
468            data: LedgerEntryData::Ttl(ttl_entry),
469            last_modified_ledger_seq: 0,
470            ext: crate::xdr::LedgerEntryExt::V0,
471        })];
472
473        let result = parse_changes(&changes);
474        assert_eq!(result, Some(44444));
475    }
476
477    #[test]
478    fn test_parse_changes_invalid_two_changes() {
479        // Test invalid 2-change format (not TTL data)
480        let not_ttl_change = LedgerEntryChange::Restored(LedgerEntry {
481            data: LedgerEntryData::Account(crate::xdr::AccountEntry {
482                account_id: crate::xdr::AccountId(crate::xdr::PublicKey::PublicKeyTypeEd25519(
483                    crate::xdr::Uint256([0; 32]),
484                )),
485                balance: 0,
486                seq_num: SequenceNumber(0),
487                num_sub_entries: 0,
488                inflation_dest: None,
489                flags: 0,
490                home_domain: crate::xdr::String32::default(),
491                thresholds: crate::xdr::Thresholds::default(),
492                signers: crate::xdr::VecM::default(),
493                ext: crate::xdr::AccountEntryExt::V0,
494            }),
495            last_modified_ledger_seq: 0,
496            ext: crate::xdr::LedgerEntryExt::V0,
497        });
498
499        let changes = vec![not_ttl_change.clone(), not_ttl_change];
500        let result = parse_changes(&changes);
501        assert_eq!(result, None);
502    }
503
504    #[test]
505    fn test_parse_changes_invalid_single_change() {
506        // Test invalid single change format (not TTL data)
507        let changes = vec![LedgerEntryChange::Restored(LedgerEntry {
508            data: LedgerEntryData::Account(crate::xdr::AccountEntry {
509                account_id: crate::xdr::AccountId(crate::xdr::PublicKey::PublicKeyTypeEd25519(
510                    crate::xdr::Uint256([0; 32]),
511                )),
512                balance: 0,
513                seq_num: SequenceNumber(0),
514                num_sub_entries: 0,
515                inflation_dest: None,
516                flags: 0,
517                home_domain: crate::xdr::String32::default(),
518                thresholds: crate::xdr::Thresholds::default(),
519                signers: crate::xdr::VecM::default(),
520                ext: crate::xdr::AccountEntryExt::V0,
521            }),
522            last_modified_ledger_seq: 0,
523            ext: crate::xdr::LedgerEntryExt::V0,
524        })];
525
526        let result = parse_changes(&changes);
527        assert_eq!(result, None);
528    }
529
530    #[test]
531    fn test_parse_changes_empty_changes() {
532        // Test empty changes array
533        let changes = vec![];
534
535        let result = parse_changes(&changes);
536        assert_eq!(result, None);
537    }
538}