contracts.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::io::{Cursor, Read};
  19. use tar::Archive;
  20. use tinyjson::JsonValue;
  21. use darkfi::{Error, Result};
  22. use darkfi_sdk::crypto::{ContractId, DAO_CONTRACT_ID, DEPLOYOOOR_CONTRACT_ID, MONEY_CONTRACT_ID};
  23. use darkfi_serial::deserialize;
  24. use crate::{
  25. contract_meta_store::{ContractMetaData, ContractSourceFile},
  26. ExplorerService,
  27. };
  28. /// Represents a contract record embellished with details that are not stored on-chain.
  29. #[derive(Debug, Clone)]
  30. pub struct ContractRecord {
  31. /// The Contract ID as a string
  32. pub id: String,
  33. /// The optional name of the contract
  34. pub name: Option<String>,
  35. /// The optional description of the contract
  36. pub description: Option<String>,
  37. }
  38. impl ContractRecord {
  39. /// Auxiliary function to convert a `ContractRecord` into a `JsonValue` array.
  40. pub fn to_json_array(&self) -> JsonValue {
  41. JsonValue::Array(vec![
  42. JsonValue::String(self.id.clone()),
  43. JsonValue::String(self.name.clone().unwrap_or_default()),
  44. JsonValue::String(self.description.clone().unwrap_or_default()),
  45. ])
  46. }
  47. }
  48. impl ExplorerService {
  49. /// Retrieves all contracts from the store excluding native contracts (DAO, Deployooor, and Money),
  50. /// transforming them into `Vec` of [`ContractRecord`]s, and returns the result.
  51. pub fn get_contracts(&self) -> Result<Vec<ContractRecord>> {
  52. let native_contracts = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  53. self.get_filtered_contracts(|contract_id| !native_contracts.contains(contract_id))
  54. }
  55. /// Retrieves all native contracts (DAO, Deployooor, and Money) from the store, transforming them
  56. /// into `Vec` of [`ContractRecord`]s and returns the result.
  57. pub fn get_native_contracts(&self) -> Result<Vec<ContractRecord>> {
  58. let native_contracts = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  59. self.get_filtered_contracts(|contract_id| native_contracts.contains(contract_id))
  60. }
  61. /// Fetches a list of source code file paths for a given [ContractId], returning an empty vector
  62. /// if no contracts are found.
  63. pub fn get_contract_source_paths(&self, contract_id: &ContractId) -> Result<Vec<String>> {
  64. self.db.contract_meta_store.get_source_paths(contract_id).map_err(|e| {
  65. Error::DatabaseError(format!(
  66. "[get_contract_source_paths] Retrieval of contract source code paths failed: {e:?}"
  67. ))
  68. })
  69. }
  70. /// Fetches [`ContractMetaData`] for a given [`ContractId`], returning `None` if no metadata is found.
  71. pub fn get_contract_metadata(
  72. &self,
  73. contract_id: &ContractId,
  74. ) -> Result<Option<ContractMetaData>> {
  75. self.db.contract_meta_store.get(contract_id).map_err(|e| {
  76. Error::DatabaseError(format!(
  77. "[get_contract_metadata] Retrieval of contract metadata paths failed: {e:?}"
  78. ))
  79. })
  80. }
  81. /// Fetches the source code content for a specified [`ContractId`] and `path`, returning `None` if
  82. /// no source content is found.
  83. pub fn get_contract_source_content(
  84. &self,
  85. contract_id: &ContractId,
  86. path: &str,
  87. ) -> Result<Option<String>> {
  88. self.db.contract_meta_store.get_source_content(contract_id, path).map_err(|e| {
  89. Error::DatabaseError(format!(
  90. "[get_contract_source_content] Retrieval of contract source file failed: {e:?}"
  91. ))
  92. })
  93. }
  94. /// Fetches the total contract count of all deployed contracts in the explorer database.
  95. pub fn get_contract_count(&self) -> usize {
  96. self.db.blockchain.contracts.wasm.len()
  97. }
  98. /// Adds source code for a specified [`ContractId`] from a provided tar file (in bytes).
  99. ///
  100. /// This function extracts the tar archive from `tar_bytes`, then loads each source file
  101. /// into the store. Each file is keyed by its path prefixed with the Contract ID.
  102. /// Returns a successful result or an error.
  103. pub fn add_contract_source(&self, contract_id: &ContractId, tar_bytes: &[u8]) -> Result<()> {
  104. // Untar the source code
  105. let source = untar_source(tar_bytes)?;
  106. // Insert contract source code
  107. self.db.contract_meta_store.insert_source(contract_id, &source).map_err(|e| {
  108. Error::DatabaseError(format!(
  109. "[add_contract_source] Adding of contract source code failed: {e:?}"
  110. ))
  111. })
  112. }
  113. /// Adds provided [`ContractId`] with corresponding [`ContractMetaData`] pairs into the contract
  114. /// metadata store, returning a successful result upon success.
  115. pub fn add_contract_metadata(
  116. &self,
  117. contract_ids: &[ContractId],
  118. metadata: &[ContractMetaData],
  119. ) -> Result<()> {
  120. self.db.contract_meta_store.insert_metadata(contract_ids, metadata).map_err(|e| {
  121. Error::DatabaseError(format!(
  122. "[add_contract_metadata] Upload of contract source code failed: {e:?}"
  123. ))
  124. })
  125. }
  126. /// Converts a [`ContractId`] into a [`ContractRecord`].
  127. ///
  128. /// This function retrieves the [`ContractMetaData`] associated with the provided Contract ID
  129. /// and uses any found metadata to construct a contract record. Upon success, the function
  130. /// returns a [`ContractRecord`] containing relevant details about the contract.
  131. fn to_contract_record(&self, contract_id: &ContractId) -> Result<ContractRecord> {
  132. let metadata = self.db.contract_meta_store.get(contract_id)?;
  133. let name: Option<String>;
  134. let description: Option<String>;
  135. // Set name and description based on the presence of metadata
  136. if let Some(metadata) = metadata {
  137. name = Some(metadata.name);
  138. description = Some(metadata.description);
  139. } else {
  140. name = None;
  141. description = None;
  142. }
  143. // Return transformed contract record
  144. Ok(ContractRecord { id: contract_id.to_string(), name, description })
  145. }
  146. /// Auxiliary function that retrieves [`ContractRecord`]s filtered by a provided `filter_fn` closure.
  147. ///
  148. /// This function accepts a filter function `Fn(&ContractId) -> bool` that determines
  149. /// which contracts are included based on their [`ContractId`]. It iterates over
  150. /// Contract IDs stored in the blockchain's contract tree, applying the filter function to decide inclusion.
  151. /// Converts the filtered Contract IDs into [`ContractRecord`] instances, returning them as a `Vec`,
  152. /// or an empty `Vec` if no contracts are found.
  153. fn get_filtered_contracts<F>(&self, filter_fn: F) -> Result<Vec<ContractRecord>>
  154. where
  155. F: Fn(&ContractId) -> bool,
  156. {
  157. let contract_keys = self.db.blockchain.contracts.wasm.iter().keys();
  158. // Iterate through stored Contract IDs, filtering out the contracts based filter
  159. contract_keys
  160. .filter_map(|serialized_contract_id| {
  161. // Deserialize the serialized Contract ID
  162. let contract_id: ContractId = match serialized_contract_id
  163. .map_err(Error::from)
  164. .and_then(|id_bytes| deserialize(&id_bytes).map_err(Error::from))
  165. {
  166. Ok(id) => id,
  167. Err(e) => {
  168. return Some(Err(Error::DatabaseError(format!(
  169. "[get_filtered_contracts] Contract ID retrieval or deserialization failed: {e:?}"
  170. ))));
  171. }
  172. };
  173. // Apply the filter
  174. if filter_fn(&contract_id) {
  175. // Convert the matching Contract ID into a `ContractRecord`, return result
  176. return match self.to_contract_record(&contract_id).map_err(|e| {
  177. Error::DatabaseError(format!("[get_filtered_contracts] Failed to convert contract: {e:?}"))
  178. }) {
  179. Ok(record) => Some(Ok(record)),
  180. Err(e) => Some(Err(e)),
  181. };
  182. }
  183. // Skip contracts that do not match the filter
  184. None
  185. })
  186. .collect::<Result<Vec<ContractRecord>>>()
  187. }
  188. }
  189. /// Auxiliary function that extracts source code files from a TAR archive provided as a byte slice [`&[u8]`],
  190. /// returning a `Vec` of [`ContractSourceFile`]s representing the extracted file paths and their contents.
  191. pub fn untar_source(tar_bytes: &[u8]) -> Result<Vec<ContractSourceFile>> {
  192. // Use a Cursor and archive to read the tar file
  193. let cursor = Cursor::new(tar_bytes);
  194. let mut archive = Archive::new(cursor);
  195. // Vectors to hold the source paths and source contents
  196. let mut source: Vec<ContractSourceFile> = Vec::new();
  197. // Iterate through the entries in the tar archive
  198. for tar_entry in archive.entries()? {
  199. let mut tar_entry = tar_entry?;
  200. let path = tar_entry.path()?.to_path_buf();
  201. // Check if the entry is a file
  202. if tar_entry.header().entry_type().is_file() {
  203. let mut content = Vec::new();
  204. tar_entry.read_to_end(&mut content)?;
  205. // Convert the contents into a string
  206. let source_content = String::from_utf8(content)
  207. .map_err(|_| Error::ParseFailed("Failed converting source code to a string"))?;
  208. // Collect source paths and contents
  209. let path_str = path.to_string_lossy().into_owned();
  210. source.push(ContractSourceFile::new(path_str, source_content));
  211. }
  212. }
  213. Ok(source)
  214. }
  215. /// This test module ensures the correctness of the [`ExplorerService`] functionality with
  216. /// respect to smart contracts.
  217. ///
  218. /// The tests in this module cover adding, loading, storing, retrieving, and validating contract
  219. /// metadata and source code. The primary goal is to validate the accuracy and reliability of
  220. /// the `ExplorerService` when handling contract-related operations.
  221. #[cfg(test)]
  222. mod tests {
  223. use std::{fs::File, io::Read, path::Path};
  224. use tar::Archive;
  225. use tempdir::TempDir;
  226. use darkfi::Error::Custom;
  227. use darkfi_sdk::crypto::MONEY_CONTRACT_ID;
  228. use super::*;
  229. use crate::test_utils::init_logger;
  230. /// Tests the adding of [`ContractMetaData`] to the store by adding
  231. /// metadata, and verifying the inserted data matches the expected results.
  232. #[test]
  233. fn test_add_metadata() -> Result<()> {
  234. // Setup test, returning initialized service
  235. let service = setup()?;
  236. // Unique identifier for contracts in tests
  237. let contract_id: ContractId = *MONEY_CONTRACT_ID;
  238. // Declare expected metadata used for test
  239. let expected_metadata: ContractMetaData = ContractMetaData::new(
  240. "Money Contract".to_string(),
  241. "Money Contract Description".to_string(),
  242. );
  243. // Add the metadata
  244. service.add_contract_metadata(&[contract_id], &[expected_metadata.clone()])?;
  245. // Get the metadata that was loaded as actual results
  246. let actual_metadata = service.get_contract_metadata(&contract_id)?;
  247. // Verify existence of loaded metadata
  248. assert!(actual_metadata.is_some());
  249. // Confirm actual metadata match expected results
  250. assert_eq!(actual_metadata.unwrap(), expected_metadata.clone());
  251. Ok(())
  252. }
  253. /// This test validates the loading and retrieval of native contract metadata. It sets up the
  254. /// explorer service, loads native contract metadata, and then verifies metadata retrieval
  255. /// for each native contract.
  256. #[test]
  257. fn test_load_native_contract_metadata() -> Result<()> {
  258. // Setup test, returning initialized service
  259. let service = setup()?;
  260. // Load native contract metadata
  261. service.load_native_contract_metadata()?;
  262. // Define Contract IDs used to retrieve loaded metadata
  263. let native_contract_ids = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  264. // For each native contract, verify metadata was loaded
  265. for contract_id in native_contract_ids.iter() {
  266. let metadata = service.get_contract_metadata(contract_id)?;
  267. assert!(metadata.is_some());
  268. }
  269. Ok(())
  270. }
  271. /// This test validates the loading, storage, and retrieval of native contract source code. It sets up the
  272. /// explorer service, loads native contract sources, and then verifies both the source paths and content
  273. /// for each native contract. The test compares the retrieved source paths and content against the expected
  274. /// results from the corresponding tar archives.
  275. #[test]
  276. fn test_load_native_contracts() -> Result<()> {
  277. // Setup test, returning initialized service
  278. let service = setup()?;
  279. // Load native contracts
  280. service.load_native_contract_sources()?;
  281. // Define contract archive paths
  282. let native_contract_tars = [
  283. "native_contracts_src/dao_contract_src.tar",
  284. "native_contracts_src/deployooor_contract_src.tar",
  285. "native_contracts_src/money_contract_src.tar",
  286. ];
  287. // Define Contract IDs to associate with each contract source archive
  288. let native_contract_ids = [*DAO_CONTRACT_ID, *DEPLOYOOOR_CONTRACT_ID, *MONEY_CONTRACT_ID];
  289. // Iterate archive and verify actual match expected results
  290. for (&tar_file, &contract_id) in native_contract_tars.iter().zip(&native_contract_ids) {
  291. // Verify that source paths match
  292. verify_source_paths(&service, tar_file, contract_id)?;
  293. // Verify that source content match
  294. verify_source_content(&service, tar_file, contract_id)?;
  295. }
  296. Ok(())
  297. }
  298. /// This test validates the transformation of a [`ContractId`] into a [`ContractRecord`].
  299. /// It sets up the explorer service, adds test metadata for a specific Contract ID, and then verifies the
  300. /// correct transformation of this Contract ID into a ContractRecord.
  301. #[test]
  302. fn test_to_contract_record() -> Result<()> {
  303. // Setup test, returning initialized service
  304. let service = setup()?;
  305. // Unique identifier for contracts in tests
  306. let contract_id: ContractId = *MONEY_CONTRACT_ID;
  307. // Declare expected metadata used for test
  308. let expected_metadata: ContractMetaData = ContractMetaData::new(
  309. "Money Contract".to_string(),
  310. "Money Contract Description".to_string(),
  311. );
  312. // Load contract metadata used for test
  313. service.add_contract_metadata(&[contract_id], &[expected_metadata.clone()])?;
  314. // Transform Contract ID to a `ContractRecord`
  315. let contract_record = service.to_contract_record(&contract_id)?;
  316. // Verify that name and description exist
  317. assert!(
  318. contract_record.name.is_some(),
  319. "Expected to_contract_record to return a contract with name"
  320. );
  321. assert!(
  322. contract_record.description.is_some(),
  323. "Expected to_contract_record to return a contract with description"
  324. );
  325. // Verify that id, name, and description match expected results
  326. assert_eq!(contract_id.to_string(), contract_record.id);
  327. assert_eq!(expected_metadata.name, contract_record.name.unwrap());
  328. assert_eq!(expected_metadata.description, contract_record.description.unwrap());
  329. Ok(())
  330. }
  331. /// Sets up a test case for contract metadata store testing by initializing the logger
  332. /// and returning an initialized [`ExplorerService`].
  333. fn setup() -> Result<ExplorerService> {
  334. // Initialize logger to show execution output
  335. init_logger(simplelog::LevelFilter::Off, vec!["sled", "runtime", "net"]);
  336. // Create a temporary directory for sled DB
  337. let temp_dir = TempDir::new("test")?;
  338. // Initialize a sled DB instance using the temporary directory's path
  339. let db_path = temp_dir.path().join("sled_db");
  340. // Initialize the explorer service
  341. ExplorerService::new(db_path.to_string_lossy().into_owned())
  342. }
  343. /// This Auxiliary function verifies that the loaded native contract source paths match the expected results
  344. /// from a given contract archive. This function extracts source paths from the specified `tar_file`, retrieves
  345. /// the actual paths for the [`ContractId`] from the ExplorerService, and compares them to ensure they match.
  346. fn verify_source_paths(
  347. service: &ExplorerService,
  348. tar_file: &str,
  349. contract_id: ContractId,
  350. ) -> Result<()> {
  351. // Read the tar file and extract source paths
  352. let tar_bytes = std::fs::read(tar_file)?;
  353. let mut expected_source_paths = extract_file_paths_from_tar(&tar_bytes)?;
  354. // Retrieve and sort actual source paths for the provided Contract ID
  355. let mut actual_source_paths = service.get_contract_source_paths(&contract_id)?;
  356. // Sort paths to ensure they are in the same order needed for assert
  357. expected_source_paths.sort();
  358. actual_source_paths.sort();
  359. // Verify actual source matches expected result
  360. assert_eq!(
  361. expected_source_paths, actual_source_paths,
  362. "Mismatch between expected and actual source paths for tar file: {}",
  363. tar_file
  364. );
  365. Ok(())
  366. }
  367. /// This auxiliary function verifies that the loaded native contract source content matches the
  368. /// expected results from a given contract source archive. It extracts source files from the specified
  369. /// `tar_file`, retrieves the actual content for each file path using the [`ContractId`] from the
  370. /// ExplorerService, and compares them to ensure the content match.
  371. fn verify_source_content(
  372. service: &ExplorerService,
  373. tar_file: &str,
  374. contract_id: ContractId,
  375. ) -> Result<()> {
  376. // Read the tar file
  377. let tar_bytes = std::fs::read(tar_file)?;
  378. let expected_source_paths = extract_file_paths_from_tar(&tar_bytes)?;
  379. // Validate contents of tar archive source code content
  380. for file_path in expected_source_paths {
  381. // Get the source code content
  382. let actual_source = service.get_contract_source_content(&contract_id, &file_path)?;
  383. // Verify source content exists
  384. assert!(
  385. actual_source.is_some(),
  386. "Actual source `{}` is missing in the store.",
  387. file_path
  388. );
  389. // Read the source content from the tar archive
  390. let expected_source = read_file_from_tar(tar_file, &file_path)?;
  391. // Verify actual source matches expected results
  392. assert_eq!(
  393. actual_source.unwrap(),
  394. expected_source,
  395. "Actual source does not match expected results `{}`.",
  396. file_path
  397. );
  398. }
  399. Ok(())
  400. }
  401. /// Auxiliary function that reads the contents of specified `file_path` within a tar archive.
  402. fn read_file_from_tar(tar_path: &str, file_path: &str) -> Result<String> {
  403. let file = File::open(tar_path)?;
  404. let mut archive = Archive::new(file);
  405. for entry in archive.entries()? {
  406. let mut entry = entry?;
  407. if let Ok(path) = entry.path() {
  408. if path == Path::new(file_path) {
  409. let mut content = String::new();
  410. entry.read_to_string(&mut content)?;
  411. return Ok(content);
  412. }
  413. }
  414. }
  415. Err(Custom(format!("File {} not found in tar archive.", file_path)))
  416. }
  417. /// Auxiliary function that extracts all file paths from the given `tar_bytes` tar archive.
  418. pub fn extract_file_paths_from_tar(tar_bytes: &[u8]) -> Result<Vec<String>> {
  419. let cursor = Cursor::new(tar_bytes);
  420. let mut archive = Archive::new(cursor);
  421. // Collect paths from the tar archive
  422. let mut file_paths = Vec::new();
  423. for entry in archive.entries()? {
  424. let entry = entry?;
  425. let path = entry.path()?;
  426. // Skip directories and only include files
  427. if entry.header().entry_type().is_file() {
  428. file_paths.push(path.to_string_lossy().to_string());
  429. }
  430. }
  431. Ok(file_paths)
  432. }
  433. }