contract_store.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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. r* 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;
  19. use darkfi_sdk::crypto::ContractId;
  20. use darkfi_serial::{deserialize, serialize};
  21. use log::{debug, error};
  22. use sled_overlay::{serial::parse_record, sled};
  23. use crate::{
  24. zk::{empty_witnesses, VerifyingKey, ZkCircuit},
  25. zkas::ZkBinary,
  26. Error, Result,
  27. };
  28. use super::SledDbOverlayPtr;
  29. pub const SLED_CONTRACTS_TREE: &[u8] = b"_contracts";
  30. pub const SLED_BINCODE_TREE: &[u8] = b"_wasm_bincode";
  31. /// The hardcoded db name for the zkas circuits database tree
  32. pub const SMART_CONTRACT_ZKAS_DB_NAME: &str = "_zkas";
  33. /// The `ContractStore` is a structure representing all `sled` trees related
  34. /// to storing the blockchain's contracts information.
  35. #[derive(Clone)]
  36. pub struct ContractStore {
  37. /// The `sled` tree storing the wasm bincode for deployed contracts.
  38. /// The layout looks like this:
  39. /// ```plaintext
  40. /// tree: "_wasm_bincode"
  41. /// key: ContractId
  42. /// value: Vec<u8>
  43. pub wasm: sled::Tree,
  44. /// The `sled` tree storing the pointers to contracts' databases.
  45. /// See the rustdoc for the impl functions for more info.
  46. /// The layout looks like this:
  47. /// ```plaintext
  48. /// tree: "_contracts"
  49. /// key: ContractId
  50. /// value: Vec<blake3(ContractId || tree_name)>
  51. /// ```
  52. /// These values get mutated with `init()` and `remove()`.
  53. pub state: sled::Tree,
  54. }
  55. impl ContractStore {
  56. /// Opens a new or existing `ContractStore` on the given sled database.
  57. pub fn new(db: &sled::Db) -> Result<Self> {
  58. let wasm = db.open_tree(SLED_BINCODE_TREE)?;
  59. let state = db.open_tree(SLED_CONTRACTS_TREE)?;
  60. Ok(Self { wasm, state })
  61. }
  62. /// Fetches the bincode for a given ContractId from the store's wasm tree.
  63. /// Returns an error if the bincode is not found.
  64. pub fn get(&self, contract_id: ContractId) -> Result<Vec<u8>> {
  65. if let Some(bincode) = self.wasm.get(serialize(&contract_id))? {
  66. return Ok(bincode.to_vec())
  67. }
  68. Err(Error::WasmBincodeNotFound)
  69. }
  70. /// Do a lookup of an existing contract state. In order to succeed, the
  71. /// state must have been previously initialized with `init()`. If the
  72. /// state has been found, a handle to it will be returned. Otherwise, we
  73. /// return an error.
  74. pub fn lookup(
  75. &self,
  76. db: &sled::Db,
  77. contract_id: &ContractId,
  78. tree_name: &str,
  79. ) -> Result<sled::Tree> {
  80. debug!(target: "blockchain::contractstore", "Looking up state tree for {}:{}", contract_id, tree_name);
  81. let contract_id_bytes = serialize(contract_id);
  82. let ptr = contract_id.hash_state_id(tree_name);
  83. // A guard to make sure we went through init()
  84. if !self.state.contains_key(&contract_id_bytes)? {
  85. return Err(Error::ContractNotFound(contract_id.to_string()))
  86. }
  87. let state_pointers = self.state.get(&contract_id_bytes)?.unwrap();
  88. let state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  89. // We assume the tree has been created already, so it should be listed
  90. // in this array. If not, that's an error.
  91. if !state_pointers.contains(&ptr) {
  92. return Err(Error::ContractStateNotFound)
  93. }
  94. // We open the tree and return its handle
  95. let tree = db.open_tree(ptr)?;
  96. Ok(tree)
  97. }
  98. /// Attempt to remove an existing contract state. In order to succeed, the
  99. /// state must have been previously initialized with `init()`. If the state
  100. /// has been found, its contents in the tree will be cleared, and the pointer
  101. /// will be removed from the main `ContractStateStore`. If anything is not
  102. /// found as initialized, an error is returned.
  103. /// NOTE: this function is not used right now, we keep it for future proofing,
  104. /// and its obviously untested.
  105. pub fn remove(&self, db: &sled::Db, contract_id: &ContractId, tree_name: &str) -> Result<()> {
  106. debug!(target: "blockchain::contractstore", "Removing state tree for {}:{}", contract_id, tree_name);
  107. let contract_id_bytes = serialize(contract_id);
  108. let ptr = contract_id.hash_state_id(tree_name);
  109. // A guard to make sure we went through init()
  110. if !self.state.contains_key(&contract_id_bytes)? {
  111. return Err(Error::ContractNotFound(contract_id.to_string()))
  112. }
  113. let state_pointers = self.state.get(&contract_id_bytes)?.unwrap();
  114. let mut state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  115. // We assume the tree has been created already, so it should be listed
  116. // in this array. If not, that's an error.
  117. if !state_pointers.contains(&ptr) {
  118. return Err(Error::ContractStateNotFound)
  119. }
  120. // Remove the deleted tree from the state pointer set.
  121. state_pointers.retain(|x| *x != ptr);
  122. self.state.insert(contract_id_bytes, serialize(&state_pointers))?;
  123. // Drop the deleted tree from the database
  124. db.drop_tree(ptr)?;
  125. Ok(())
  126. }
  127. /// Abstraction function for fetching a `ZkBinary` and its respective `VerifyingKey`
  128. /// from a contract's zkas sled tree.
  129. pub fn get_zkas(
  130. &self,
  131. db: &sled::Db,
  132. contract_id: &ContractId,
  133. zkas_ns: &str,
  134. ) -> Result<(ZkBinary, VerifyingKey)> {
  135. debug!(target: "blockchain::contractstore", "Looking up \"{}:{}\" zkas circuit & vk", contract_id, zkas_ns);
  136. let zkas_tree = self.lookup(db, contract_id, SMART_CONTRACT_ZKAS_DB_NAME)?;
  137. let Some(zkas_bytes) = zkas_tree.get(serialize(&zkas_ns))? else {
  138. return Err(Error::ZkasBincodeNotFound)
  139. };
  140. // If anything in this function panics, that means corrupted data managed
  141. // to get into this sled tree. This should not be possible.
  142. let (zkbin, vkbin): (Vec<u8>, Vec<u8>) = deserialize(&zkas_bytes).unwrap();
  143. // The first vec is the compiled zkas binary
  144. let zkbin = ZkBinary::decode(&zkbin).unwrap();
  145. // Construct the circuit to be able to read the VerifyingKey
  146. let circuit = ZkCircuit::new(empty_witnesses(&zkbin).unwrap(), &zkbin);
  147. // The second one is the serialized VerifyingKey for it
  148. let mut vk_buf = Cursor::new(vkbin);
  149. let vk = VerifyingKey::read::<Cursor<Vec<u8>>, ZkCircuit>(&mut vk_buf, circuit).unwrap();
  150. Ok((zkbin, vk))
  151. }
  152. /// Retrieve all wasm bincodes from the store's wasm tree in the form
  153. /// of a tuple (`contract_id`, `bincode`).
  154. /// Be careful as this will try to load everything in memory.
  155. pub fn get_all_wasm(&self) -> Result<Vec<(ContractId, Vec<u8>)>> {
  156. let mut bincodes = vec![];
  157. for bincode in self.wasm.iter() {
  158. let bincode = bincode.unwrap();
  159. let contract_id = deserialize(&bincode.0)?;
  160. bincodes.push((contract_id, bincode.1.to_vec()));
  161. }
  162. Ok(bincodes)
  163. }
  164. /// Retrieve all contract states from the store's state tree in the
  165. /// form of a tuple (`contract_id`, `state_hashes`).
  166. /// Be careful as this will try to load everything in memory.
  167. pub fn get_all_states(&self) -> Result<Vec<(ContractId, Vec<blake3::Hash>)>> {
  168. let mut contracts = vec![];
  169. for contract in self.state.iter() {
  170. contracts.push(parse_record(contract.unwrap())?);
  171. }
  172. Ok(contracts)
  173. }
  174. }
  175. /// Overlay structure over a [`ContractStore`] instance.
  176. pub struct ContractStoreOverlay(SledDbOverlayPtr);
  177. impl ContractStoreOverlay {
  178. pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
  179. overlay.lock().unwrap().open_tree(SLED_BINCODE_TREE, true)?;
  180. overlay.lock().unwrap().open_tree(SLED_CONTRACTS_TREE, true)?;
  181. Ok(Self(overlay.clone()))
  182. }
  183. /// Fetches the bincode for a given ContractId from the overlay's wasm tree.
  184. /// Returns an error if the bincode is not found.
  185. pub fn get(&self, contract_id: ContractId) -> Result<Vec<u8>> {
  186. if let Some(bincode) =
  187. self.0.lock().unwrap().get(SLED_BINCODE_TREE, &serialize(&contract_id))?
  188. {
  189. return Ok(bincode.to_vec())
  190. }
  191. Err(Error::WasmBincodeNotFound)
  192. }
  193. /// Inserts or replaces the bincode for a given ContractId into the overlay's
  194. /// wasm tree.
  195. pub fn insert(&self, contract_id: ContractId, bincode: &[u8]) -> Result<()> {
  196. if let Err(e) =
  197. self.0.lock().unwrap().insert(SLED_BINCODE_TREE, &serialize(&contract_id), bincode)
  198. {
  199. error!(target: "blockchain::contractstoreoverlay", "Failed to insert bincode to Wasm tree: {}", e);
  200. return Err(e.into())
  201. }
  202. Ok(())
  203. }
  204. /// Try to initialize a new contract state. Contracts can create a number
  205. /// of trees, separated by `tree_name`, which they can then use from the
  206. /// smart contract API. `init()` will look into the main `ContractStateStoreOverlay`
  207. /// tree to check if the smart contract was already deployed, and if so
  208. /// it will fetch a vector of these states that were initialized. If the
  209. /// state was already found, this function will return an error, because
  210. /// in this case the handle should be fetched using `lookup()`.
  211. /// If the tree was not initialized previously, it will be appended to
  212. /// the main `ContractStateStoreOverlay` tree and a handle to it will be
  213. /// returned.
  214. pub fn init(&self, contract_id: &ContractId, tree_name: &str) -> Result<[u8; 32]> {
  215. debug!(target: "blockchain::contractstoreoverlay", "Initializing state overlay tree for {}:{}", contract_id, tree_name);
  216. let contract_id_bytes = serialize(contract_id);
  217. let ptr = contract_id.hash_state_id(tree_name);
  218. let mut lock = self.0.lock().unwrap();
  219. // See if there are existing state trees.
  220. // If not, just start with an empty vector.
  221. let mut state_pointers: Vec<[u8; 32]> =
  222. if lock.contains_key(SLED_CONTRACTS_TREE, &contract_id_bytes)? {
  223. let bytes = lock.get(SLED_CONTRACTS_TREE, &contract_id_bytes)?.unwrap();
  224. deserialize(&bytes)?
  225. } else {
  226. vec![]
  227. };
  228. // If the db was never initialized, it should not be in here.
  229. if state_pointers.contains(&ptr) {
  230. return Err(Error::ContractAlreadyInitialized)
  231. }
  232. // Now we add it so it's marked as initialized and create its tree.
  233. state_pointers.push(ptr);
  234. lock.insert(SLED_CONTRACTS_TREE, &contract_id_bytes, &serialize(&state_pointers))?;
  235. lock.open_tree(&ptr, false)?;
  236. Ok(ptr)
  237. }
  238. /// Do a lookup of an existing contract state. In order to succeed, the
  239. /// state must have been previously initialized with `init()`. If the
  240. /// state has been found, a handle to it will be returned. Otherwise, we
  241. /// return an error.
  242. pub fn lookup(&self, contract_id: &ContractId, tree_name: &str) -> Result<[u8; 32]> {
  243. debug!(target: "blockchain::contractstoreoverlay", "Looking up state tree for {}:{}", contract_id, tree_name);
  244. let contract_id_bytes = serialize(contract_id);
  245. let ptr = contract_id.hash_state_id(tree_name);
  246. let mut lock = self.0.lock().unwrap();
  247. // A guard to make sure we went through init()
  248. if !lock.contains_key(SLED_CONTRACTS_TREE, &contract_id_bytes)? {
  249. return Err(Error::ContractNotFound(contract_id.to_string()))
  250. }
  251. let state_pointers = lock.get(SLED_CONTRACTS_TREE, &contract_id_bytes)?.unwrap();
  252. let state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  253. // We assume the tree has been created already, so it should be listed
  254. // in this array. If not, that's an error.
  255. if !state_pointers.contains(&ptr) {
  256. return Err(Error::ContractStateNotFound)
  257. }
  258. // We open the tree and return its handle
  259. lock.open_tree(&ptr, false)?;
  260. Ok(ptr)
  261. }
  262. /// Abstraction function for fetching a `ZkBinary` and its respective `VerifyingKey`
  263. /// from a contract's zkas sled tree.
  264. pub fn get_zkas(
  265. &self,
  266. contract_id: &ContractId,
  267. zkas_ns: &str,
  268. ) -> Result<(ZkBinary, VerifyingKey)> {
  269. debug!(target: "blockchain::contractstore", "Looking up \"{}:{}\" zkas circuit & vk", contract_id, zkas_ns);
  270. let zkas_tree = self.lookup(contract_id, SMART_CONTRACT_ZKAS_DB_NAME)?;
  271. let Some(zkas_bytes) = self.0.lock().unwrap().get(&zkas_tree, &serialize(&zkas_ns))? else {
  272. return Err(Error::ZkasBincodeNotFound)
  273. };
  274. // If anything in this function panics, that means corrupted data managed
  275. // to get into this sled tree. This should not be possible.
  276. let (zkbin, vkbin): (Vec<u8>, Vec<u8>) = deserialize(&zkas_bytes).unwrap();
  277. // The first vec is the compiled zkas binary
  278. let zkbin = ZkBinary::decode(&zkbin).unwrap();
  279. // Construct the circuit to be able to read the VerifyingKey
  280. let circuit = ZkCircuit::new(empty_witnesses(&zkbin).unwrap(), &zkbin);
  281. // The second one is the serialized VerifyingKey for it
  282. let mut vk_buf = Cursor::new(vkbin);
  283. let vk = VerifyingKey::read::<Cursor<Vec<u8>>, ZkCircuit>(&mut vk_buf, circuit).unwrap();
  284. Ok((zkbin, vk))
  285. }
  286. }