contracts.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. io::{Cursor, Read},
  20. str::FromStr,
  21. };
  22. use tar::Archive;
  23. use tinyjson::JsonValue;
  24. use tracing::info;
  25. use darkfi::{
  26. blockchain::BlockchainOverlay, validator::utils::deploy_native_contracts, Error, Result,
  27. };
  28. use darkfi_sdk::crypto::{ContractId, DAO_CONTRACT_ID, DEPLOYOOOR_CONTRACT_ID, MONEY_CONTRACT_ID};
  29. use darkfi_serial::deserialize;
  30. use crate::{
  31. store::{
  32. contract_metadata::{ContractMetaData, ContractSourceFile},
  33. NATIVE_CONTRACT_SOURCE_ARCHIVES,
  34. },
  35. ExplorerService,
  36. };
  37. /// Represents a contract record embellished with details that are not stored on-chain.
  38. #[derive(Debug, Clone)]
  39. pub struct ContractRecord {
  40. /// The Contract ID as a string
  41. pub id: String,
  42. /// The optional name of the contract
  43. pub name: Option<String>,
  44. /// The optional description of the contract
  45. pub description: Option<String>,
  46. }
  47. impl ContractRecord {
  48. /// Auxiliary function to convert a `ContractRecord` into a `JsonValue` array.
  49. pub fn to_json_array(&self) -> JsonValue {
  50. JsonValue::Array(vec![
  51. JsonValue::String(self.id.clone()),
  52. JsonValue::String(self.name.clone().unwrap_or_default()),
  53. JsonValue::String(self.description.clone().unwrap_or_default()),
  54. ])
  55. }
  56. }
  57. impl ExplorerService {
  58. /// Fetches the total contract count of all deployed contracts in the explorer database.
  59. pub fn get_contract_count(&self) -> usize {
  60. self.db.blockchain.contracts.wasm.len()
  61. }
  62. /// Retrieves all contracts from the store excluding native contracts (DAO, Deployooor, and Money),
  63. /// transforming them into `Vec` of [`ContractRecord`]s, and returns the result.
  64. pub fn get_contracts(&self) -> Result<Vec<ContractRecord>> {
  65. let native_contracts = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  66. self.get_filtered_contracts(|contract_id| !native_contracts.contains(contract_id))
  67. }
  68. /// Retrieves all native contracts (DAO, Deployooor, and Money) from the store, transforming them
  69. /// into `Vec` of [`ContractRecord`]s and returns the result.
  70. pub fn get_native_contracts(&self) -> Result<Vec<ContractRecord>> {
  71. let native_contracts = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  72. self.get_filtered_contracts(|contract_id| native_contracts.contains(contract_id))
  73. }
  74. /// Fetches a list of source code file paths for a given [ContractId], returning an empty vector
  75. /// if no contracts are found.
  76. pub fn get_contract_source_paths(&self, contract_id: &ContractId) -> Result<Vec<String>> {
  77. self.db.contract_meta_store.get_source_paths(contract_id).map_err(|e| {
  78. Error::DatabaseError(format!(
  79. "[get_contract_source_paths] Retrieval of contract source code paths failed: {e:?}"
  80. ))
  81. })
  82. }
  83. /// Fetches [`ContractMetaData`] for a given [`ContractId`], returning `None` if no metadata is found.
  84. pub fn get_contract_metadata(
  85. &self,
  86. contract_id: &ContractId,
  87. ) -> Result<Option<ContractMetaData>> {
  88. self.db.contract_meta_store.get(contract_id).map_err(|e| {
  89. Error::DatabaseError(format!(
  90. "[get_contract_metadata] Retrieval of contract metadata paths failed: {e:?}"
  91. ))
  92. })
  93. }
  94. /// Fetches the source code content for a specified [`ContractId`] and `path`, returning `None` if
  95. /// no source content is found.
  96. pub fn get_contract_source_content(
  97. &self,
  98. contract_id: &ContractId,
  99. path: &str,
  100. ) -> Result<Option<String>> {
  101. self.db.contract_meta_store.get_source_content(contract_id, path).map_err(|e| {
  102. Error::DatabaseError(format!(
  103. "[get_contract_source_content] Retrieval of contract source file failed: {e:?}"
  104. ))
  105. })
  106. }
  107. /// Adds source code for a specified [`ContractId`] from a provided tar file (in bytes).
  108. ///
  109. /// This function extracts the tar archive from `tar_bytes`, then loads each source file
  110. /// into the store. Each file is keyed by its path prefixed with the Contract ID.
  111. /// Returns a successful result or an error.
  112. pub fn add_contract_source(&self, contract_id: &ContractId, tar_bytes: &[u8]) -> Result<()> {
  113. // Untar the source code
  114. let source = untar_source(tar_bytes)?;
  115. // Insert contract source code
  116. self.db.contract_meta_store.insert_source(contract_id, &source).map_err(|e| {
  117. Error::DatabaseError(format!(
  118. "[add_contract_source] Adding of contract source code failed: {e:?}"
  119. ))
  120. })
  121. }
  122. /// Adds provided [`ContractId`] with corresponding [`ContractMetaData`] pairs into the contract
  123. /// metadata store, returning a successful result upon success.
  124. pub fn add_contract_metadata(
  125. &self,
  126. contract_ids: &[ContractId],
  127. metadata: &[ContractMetaData],
  128. ) -> Result<()> {
  129. self.db.contract_meta_store.insert_metadata(contract_ids, metadata).map_err(|e| {
  130. Error::DatabaseError(format!(
  131. "[add_contract_metadata] Upload of contract source code failed: {e:?}"
  132. ))
  133. })
  134. }
  135. /// Deploys native contracts required for gas calculation and retrieval.
  136. pub async fn deploy_native_contracts(&self) -> Result<()> {
  137. let overlay = BlockchainOverlay::new(&self.db.blockchain)?;
  138. deploy_native_contracts(&overlay, 10).await?;
  139. overlay.lock().unwrap().overlay.lock().unwrap().apply()?;
  140. Ok(())
  141. }
  142. /// Loads native contract source code into the explorer database by extracting it from tar archives
  143. /// created during the explorer build process. The extracted source code is associated with
  144. /// the corresponding [`ContractId`] for each loaded contract and stored.
  145. pub fn load_native_contract_sources(&self) -> Result<()> {
  146. // Iterate each native contract source archive
  147. for (contract_id_str, archive_bytes) in NATIVE_CONTRACT_SOURCE_ARCHIVES.iter() {
  148. // Untar the native contract source code
  149. let source_code = untar_source(archive_bytes)?;
  150. // Parse contract id into a contract id instance
  151. let contract_id = &ContractId::from_str(contract_id_str)?;
  152. // Add source code into the `ContractMetaStore`
  153. self.db.contract_meta_store.insert_source(contract_id, &source_code)?;
  154. info!(target: "explorerd: load_native_contract_sources", "Loaded native contract source {contract_id_str}");
  155. }
  156. Ok(())
  157. }
  158. /// Loads [`ContractMetaData`] for deployed native contracts into the explorer database by adding descriptive
  159. /// information (e.g., name and description) used to display contract details.
  160. pub fn load_native_contract_metadata(&self) -> Result<()> {
  161. let contract_ids = [*MONEY_CONTRACT_ID, *DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID];
  162. // Create pre-defined native contract metadata
  163. let metadatas = [
  164. ContractMetaData::new(
  165. "Money".to_string(),
  166. "Facilitates money transfers, atomic swaps, minting, freezing, and staking of consensus tokens".to_string(),
  167. ),
  168. ContractMetaData::new(
  169. "DAO".to_string(),
  170. "Provides functionality for Anonymous DAOs".to_string(),
  171. ),
  172. ContractMetaData::new(
  173. "Deployoor".to_string(),
  174. "Handles non-native smart contract deployments".to_string(),
  175. ),
  176. ];
  177. // Load contract metadata into the `ContractMetaStore`
  178. self.db.contract_meta_store.insert_metadata(&contract_ids, &metadatas)?;
  179. info!(target: "explorerd: load_native_contract_metadata", "Loaded metadata for native contracts");
  180. Ok(())
  181. }
  182. /// Converts a [`ContractId`] into a [`ContractRecord`].
  183. ///
  184. /// This function retrieves the [`ContractMetaData`] associated with the provided Contract ID
  185. /// and uses any found metadata to construct a contract record. Upon success, the function
  186. /// returns a [`ContractRecord`] containing relevant details about the contract.
  187. fn to_contract_record(&self, contract_id: &ContractId) -> Result<ContractRecord> {
  188. let metadata = self.db.contract_meta_store.get(contract_id)?;
  189. let name: Option<String>;
  190. let description: Option<String>;
  191. // Set name and description based on the presence of metadata
  192. if let Some(metadata) = metadata {
  193. name = Some(metadata.name);
  194. description = Some(metadata.description);
  195. } else {
  196. name = None;
  197. description = None;
  198. }
  199. // Return transformed contract record
  200. Ok(ContractRecord { id: contract_id.to_string(), name, description })
  201. }
  202. /// Auxiliary function that retrieves [`ContractRecord`]s filtered by a provided `filter_fn` closure.
  203. ///
  204. /// This function accepts a filter function `Fn(&ContractId) -> bool` that determines
  205. /// which contracts are included based on their [`ContractId`]. It iterates over
  206. /// Contract IDs stored in the blockchain's contract tree, applying the filter function to decide inclusion.
  207. /// Converts the filtered Contract IDs into [`ContractRecord`] instances, returning them as a `Vec`,
  208. /// or an empty `Vec` if no contracts are found.
  209. fn get_filtered_contracts<F>(&self, filter_fn: F) -> Result<Vec<ContractRecord>>
  210. where
  211. F: Fn(&ContractId) -> bool,
  212. {
  213. let contract_keys = self.db.blockchain.contracts.wasm.iter().keys();
  214. // Iterate through stored Contract IDs, filtering out the contracts based filter
  215. contract_keys
  216. .filter_map(|serialized_contract_id| {
  217. // Deserialize the serialized Contract ID
  218. let contract_id: ContractId = match serialized_contract_id
  219. .map_err(Error::from)
  220. .and_then(|id_bytes| deserialize(&id_bytes).map_err(Error::from))
  221. {
  222. Ok(id) => id,
  223. Err(e) => {
  224. return Some(Err(Error::DatabaseError(format!(
  225. "[get_filtered_contracts] Contract ID retrieval or deserialization failed: {e:?}"
  226. ))));
  227. }
  228. };
  229. // Apply the filter
  230. if filter_fn(&contract_id) {
  231. // Convert the matching Contract ID into a `ContractRecord`, return result
  232. return match self.to_contract_record(&contract_id).map_err(|e| {
  233. Error::DatabaseError(format!("[get_filtered_contracts] Failed to convert contract: {e:?}"))
  234. }) {
  235. Ok(record) => Some(Ok(record)),
  236. Err(e) => Some(Err(e)),
  237. };
  238. }
  239. // Skip contracts that do not match the filter
  240. None
  241. })
  242. .collect::<Result<Vec<ContractRecord>>>()
  243. }
  244. }
  245. /// Auxiliary function that extracts source code files from a TAR archive provided as a byte slice [`&[u8]`],
  246. /// returning a `Vec` of [`ContractSourceFile`]s representing the extracted file paths and their contents.
  247. pub fn untar_source(tar_bytes: &[u8]) -> Result<Vec<ContractSourceFile>> {
  248. // Use a Cursor and archive to read the tar file
  249. let cursor = Cursor::new(tar_bytes);
  250. let mut archive = Archive::new(cursor);
  251. // Vectors to hold the source paths and source contents
  252. let mut source: Vec<ContractSourceFile> = Vec::new();
  253. // Iterate through the entries in the tar archive
  254. for tar_entry in archive.entries()? {
  255. let mut tar_entry = tar_entry?;
  256. let path = tar_entry.path()?.to_path_buf();
  257. // Check if the entry is a file
  258. if tar_entry.header().entry_type().is_file() {
  259. let mut content = Vec::new();
  260. tar_entry.read_to_end(&mut content)?;
  261. // Convert the contents into a string
  262. let source_content = String::from_utf8(content)
  263. .map_err(|_| Error::ParseFailed("Failed converting source code to a string"))?;
  264. // Collect source paths and contents
  265. let path_str = path.to_string_lossy().into_owned();
  266. source.push(ContractSourceFile::new(path_str, source_content));
  267. }
  268. }
  269. Ok(source)
  270. }
  271. /// This test module ensures the correctness of the [`ExplorerService`] functionality with
  272. /// respect to smart contracts.
  273. ///
  274. /// The tests in this module cover adding, loading, storing, retrieving, and validating contract
  275. /// metadata and source code. The primary goal is to validate the accuracy and reliability of
  276. /// the `ExplorerService` when handling contract-related operations.
  277. #[cfg(test)]
  278. mod tests {
  279. use std::{fs::File, io::Read, path::Path, slice, sync::Arc};
  280. use darkfi::{
  281. util::logger::{setup_test_logger, Level},
  282. Error::Custom,
  283. };
  284. use darkfi_sdk::crypto::MONEY_CONTRACT_ID;
  285. use tar::Archive;
  286. use tempdir::TempDir;
  287. use tracing::warn;
  288. use super::*;
  289. use crate::rpc::DarkfidRpcClient;
  290. /// Tests the adding of [`ContractMetaData`] to the store by adding
  291. /// metadata, and verifying the inserted data matches the expected results.
  292. #[test]
  293. fn test_add_metadata() -> Result<()> {
  294. // Setup test, returning initialized service
  295. let service = setup()?;
  296. // Unique identifier for contracts in tests
  297. let contract_id: ContractId = *MONEY_CONTRACT_ID;
  298. // Declare expected metadata used for test
  299. let expected_metadata: ContractMetaData = ContractMetaData::new(
  300. "Money Contract".to_string(),
  301. "Money Contract Description".to_string(),
  302. );
  303. // Add the metadata
  304. service.add_contract_metadata(&[contract_id], slice::from_ref(&expected_metadata))?;
  305. // Get the metadata that was loaded as actual results
  306. let actual_metadata = service.get_contract_metadata(&contract_id)?;
  307. // Verify existence of loaded metadata
  308. assert!(actual_metadata.is_some());
  309. // Confirm actual metadata match expected results
  310. assert_eq!(actual_metadata.unwrap(), expected_metadata.clone());
  311. Ok(())
  312. }
  313. /// This test validates the loading and retrieval of native contract metadata. It sets up the
  314. /// explorer service, loads native contract metadata, and then verifies metadata retrieval
  315. /// for each native contract.
  316. #[test]
  317. fn test_load_native_contract_metadata() -> Result<()> {
  318. // Setup test, returning initialized service
  319. let service = setup()?;
  320. // Load native contract metadata
  321. service.load_native_contract_metadata()?;
  322. // Define Contract IDs used to retrieve loaded metadata
  323. let native_contract_ids = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  324. // For each native contract, verify metadata was loaded
  325. for contract_id in native_contract_ids.iter() {
  326. let metadata = service.get_contract_metadata(contract_id)?;
  327. assert!(metadata.is_some());
  328. }
  329. Ok(())
  330. }
  331. /// This test validates the loading, storage, and retrieval of native contract source code. It sets up the
  332. /// explorer service, loads native contract sources, and then verifies both the source paths and content
  333. /// for each native contract. The test compares the retrieved source paths and content against the expected
  334. /// results from the corresponding tar archives.
  335. #[test]
  336. fn test_load_native_contracts() -> Result<()> {
  337. // Setup test, returning initialized service
  338. let service = setup()?;
  339. // Load native contracts
  340. service.load_native_contract_sources()?;
  341. // Define contract archive paths
  342. let native_contract_tars = [
  343. "native_contracts_src/dao_contract_src.tar",
  344. "native_contracts_src/deployooor_contract_src.tar",
  345. "native_contracts_src/money_contract_src.tar",
  346. ];
  347. // Define Contract IDs to associate with each contract source archive
  348. let native_contract_ids = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  349. // Iterate archive and verify actual match expected results
  350. for (&tar_file, &contract_id) in native_contract_tars.iter().zip(&native_contract_ids) {
  351. // Verify that source paths match
  352. verify_source_paths(&service, tar_file, contract_id)?;
  353. // Verify that source content match
  354. verify_source_content(&service, tar_file, contract_id)?;
  355. }
  356. Ok(())
  357. }
  358. /// This test validates the transformation of a [`ContractId`] into a [`ContractRecord`].
  359. /// It sets up the explorer service, adds test metadata for a specific Contract ID, and then verifies the
  360. /// correct transformation of this Contract ID into a ContractRecord.
  361. #[test]
  362. fn test_to_contract_record() -> Result<()> {
  363. // Setup test, returning initialized service
  364. let service = setup()?;
  365. // Unique identifier for contracts in tests
  366. let contract_id: ContractId = *MONEY_CONTRACT_ID;
  367. // Declare expected metadata used for test
  368. let expected_metadata: ContractMetaData = ContractMetaData::new(
  369. "Money Contract".to_string(),
  370. "Money Contract Description".to_string(),
  371. );
  372. // Load contract metadata used for test
  373. service.add_contract_metadata(&[contract_id], slice::from_ref(&expected_metadata))?;
  374. // Transform Contract ID to a `ContractRecord`
  375. let contract_record = service.to_contract_record(&contract_id)?;
  376. // Verify that name and description exist
  377. assert!(
  378. contract_record.name.is_some(),
  379. "Expected to_contract_record to return a contract with name"
  380. );
  381. assert!(
  382. contract_record.description.is_some(),
  383. "Expected to_contract_record to return a contract with description"
  384. );
  385. // Verify that id, name, and description match expected results
  386. assert_eq!(contract_id.to_string(), contract_record.id);
  387. assert_eq!(expected_metadata.name, contract_record.name.unwrap());
  388. assert_eq!(expected_metadata.description, contract_record.description.unwrap());
  389. Ok(())
  390. }
  391. /// Sets up a test case for contract metadata store testing by initializing the logger
  392. /// and returning an initialized [`ExplorerService`].
  393. fn setup() -> Result<ExplorerService> {
  394. // Initialize logger to show execution output
  395. if setup_test_logger(
  396. &["sled", "runtime", "net"],
  397. false,
  398. Level::Info,
  399. //Level::Verbose,
  400. //Level::Debug,
  401. //Level::Trace,
  402. )
  403. .is_err()
  404. {
  405. warn!("Logger already initialized");
  406. }
  407. // Create a temporary directory for sled DB
  408. let temp_dir = TempDir::new("test")?;
  409. // Initialize a sled DB instance using the temporary directory's path
  410. let db_path = temp_dir.path().join("sled_db");
  411. // Initialize the explorer service
  412. ExplorerService::new(
  413. db_path.to_string_lossy().into_owned(),
  414. Arc::new(DarkfidRpcClient::new()),
  415. )
  416. }
  417. /// This Auxiliary function verifies that the loaded native contract source paths match the expected results
  418. /// from a given contract archive. This function extracts source paths from the specified `tar_file`, retrieves
  419. /// the actual paths for the [`ContractId`] from the ExplorerService, and compares them to ensure they match.
  420. fn verify_source_paths(
  421. service: &ExplorerService,
  422. tar_file: &str,
  423. contract_id: ContractId,
  424. ) -> Result<()> {
  425. // Read the tar file and extract source paths
  426. let tar_bytes = std::fs::read(tar_file)?;
  427. let mut expected_source_paths = extract_file_paths_from_tar(&tar_bytes)?;
  428. // Retrieve and sort actual source paths for the provided Contract ID
  429. let mut actual_source_paths = service.get_contract_source_paths(&contract_id)?;
  430. // Sort paths to ensure they are in the same order needed for assert
  431. expected_source_paths.sort();
  432. actual_source_paths.sort();
  433. // Verify actual source matches expected result
  434. assert_eq!(
  435. expected_source_paths, actual_source_paths,
  436. "Mismatch between expected and actual source paths for tar file: {tar_file}"
  437. );
  438. Ok(())
  439. }
  440. /// This auxiliary function verifies that the loaded native contract source content matches the
  441. /// expected results from a given contract source archive. It extracts source files from the specified
  442. /// `tar_file`, retrieves the actual content for each file path using the [`ContractId`] from the
  443. /// ExplorerService, and compares them to ensure the content match.
  444. fn verify_source_content(
  445. service: &ExplorerService,
  446. tar_file: &str,
  447. contract_id: ContractId,
  448. ) -> Result<()> {
  449. // Read the tar file
  450. let tar_bytes = std::fs::read(tar_file)?;
  451. let expected_source_paths = extract_file_paths_from_tar(&tar_bytes)?;
  452. // Validate contents of tar archive source code content
  453. for file_path in expected_source_paths {
  454. // Get the source code content
  455. let actual_source = service.get_contract_source_content(&contract_id, &file_path)?;
  456. // Verify source content exists
  457. assert!(
  458. actual_source.is_some(),
  459. "Actual source `{file_path}` is missing in the store."
  460. );
  461. // Read the source content from the tar archive
  462. let expected_source = read_file_from_tar(tar_file, &file_path)?;
  463. // Verify actual source matches expected results
  464. assert_eq!(
  465. actual_source.unwrap(),
  466. expected_source,
  467. "Actual source does not match expected results `{file_path}`."
  468. );
  469. }
  470. Ok(())
  471. }
  472. /// Auxiliary function that reads the contents of specified `file_path` within a tar archive.
  473. fn read_file_from_tar(tar_path: &str, file_path: &str) -> Result<String> {
  474. let file = File::open(tar_path)?;
  475. let mut archive = Archive::new(file);
  476. for entry in archive.entries()? {
  477. let mut entry = entry?;
  478. if let Ok(path) = entry.path() {
  479. if path == Path::new(file_path) {
  480. let mut content = String::new();
  481. entry.read_to_string(&mut content)?;
  482. return Ok(content);
  483. }
  484. }
  485. }
  486. Err(Custom(format!("File {file_path} not found in tar archive.")))
  487. }
  488. /// Auxiliary function that extracts all file paths from the given `tar_bytes` tar archive.
  489. pub fn extract_file_paths_from_tar(tar_bytes: &[u8]) -> Result<Vec<String>> {
  490. let cursor = Cursor::new(tar_bytes);
  491. let mut archive = Archive::new(cursor);
  492. // Collect paths from the tar archive
  493. let mut file_paths = Vec::new();
  494. for entry in archive.entries()? {
  495. let entry = entry?;
  496. let path = entry.path()?;
  497. // Skip directories and only include files
  498. if entry.header().entry_type().is_file() {
  499. file_paths.push(path.to_string_lossy().to_string());
  500. }
  501. }
  502. Ok(file_paths)
  503. }
  504. }