contract_store.rs 14 KB

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