contract_store.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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. blockchain::SledDbOverlayPtr,
  24. runtime::vm_runtime::SMART_CONTRACT_ZKAS_DB_NAME,
  25. zk::{VerifyingKey, ZkCircuit},
  26. zkas::ZkBinary,
  27. Error, Result,
  28. };
  29. const SLED_CONTRACTS_TREE: &[u8] = b"_contracts";
  30. const SLED_BINCODE_TREE: &[u8] = b"_wasm_bincode";
  31. /// The `WasmStore` is a `sled` tree that stores the wasm bincode for deployed
  32. /// contracts.
  33. #[derive(Clone)]
  34. pub struct WasmStore(sled::Tree);
  35. impl WasmStore {
  36. /// Opens or creates a `WasmStore`. This tree holds the wasm bincode.
  37. /// The layout looks like this:
  38. /// ```plaintext
  39. /// tree: "_wasm_bincode"
  40. /// key: ContractId
  41. /// value: Vec<u8>
  42. pub fn new(db: &sled::Db) -> Result<Self> {
  43. let tree = db.open_tree(SLED_BINCODE_TREE)?;
  44. Ok(Self(tree))
  45. }
  46. /// Fetches the bincode for a given ContractId
  47. /// Returns an error if the bincode is not found.
  48. pub fn get(&self, contract_id: ContractId) -> Result<Vec<u8>> {
  49. if let Some(bincode) = self.0.get(serialize(&contract_id))? {
  50. return Ok(bincode.to_vec())
  51. }
  52. Err(Error::WasmBincodeNotFound)
  53. }
  54. }
  55. /// Overlay structure over a [`WasmStore`] instance.
  56. pub struct WasmStoreOverlay(SledDbOverlayPtr);
  57. impl WasmStoreOverlay {
  58. pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
  59. overlay.lock().unwrap().open_tree(SLED_BINCODE_TREE)?;
  60. Ok(Self(overlay))
  61. }
  62. /// Inserts or replaces the bincode for a given ContractId
  63. pub fn insert(&self, contract_id: ContractId, bincode: &[u8]) -> Result<()> {
  64. if let Err(e) =
  65. self.0.lock().unwrap().insert(SLED_BINCODE_TREE, &serialize(&contract_id), bincode)
  66. {
  67. error!(target: "blockchain::contractstoreoverlay", "Failed to insert bincode to WasmStore: {}", e);
  68. return Err(e.into())
  69. }
  70. Ok(())
  71. }
  72. }
  73. /// The `ContractStateStore` is a `sled` tree that stores pointers to contracts'
  74. /// databases. See the rustdoc for the impl functions for more info.
  75. #[derive(Clone)]
  76. pub struct ContractStateStore(sled::Tree);
  77. impl ContractStateStore {
  78. /// Opens or creates a `ContractStateStore`. This main tree holds the links
  79. /// of contracts' states.
  80. /// The layout looks like this:
  81. /// ```plaintext
  82. /// tree: "_contracts"
  83. /// key: ContractId
  84. /// value: Vec<blake3(ContractId || tree_name)>
  85. /// ```
  86. /// These values get mutated with `init()` and `remove()`.
  87. pub fn new(db: &sled::Db) -> Result<Self> {
  88. let tree = db.open_tree(SLED_CONTRACTS_TREE)?;
  89. Ok(Self(tree))
  90. }
  91. /// Do a lookup of an existing contract state. In order to succeed, the
  92. /// state must have been previously initialized with `init()`. If the
  93. /// state has been found, a handle to it will be returned. Otherwise, we
  94. /// return an error.
  95. pub fn lookup(
  96. &self,
  97. db: &sled::Db,
  98. contract_id: &ContractId,
  99. tree_name: &str,
  100. ) -> Result<sled::Tree> {
  101. debug!(target: "blockchain::contractstore", "Looking up state tree for {}:{}", contract_id, tree_name);
  102. let contract_id_bytes = serialize(contract_id);
  103. let ptr = contract_id.hash_state_id(tree_name);
  104. // A guard to make sure we went through init()
  105. if !self.0.contains_key(&contract_id_bytes)? {
  106. return Err(Error::ContractNotFound(contract_id.to_string()))
  107. }
  108. let state_pointers = self.0.get(&contract_id_bytes)?.unwrap();
  109. let state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  110. // We assume the tree has been created already, so it should be listed
  111. // in this array. If not, that's an error.
  112. if !state_pointers.contains(&ptr) {
  113. return Err(Error::ContractStateNotFound)
  114. }
  115. // We open the tree and return its handle
  116. let tree = db.open_tree(ptr)?;
  117. Ok(tree)
  118. }
  119. /// Attempt to remove an existing contract state. In order to succeed, the
  120. /// state must have been previously initialized with `init()`. If the state
  121. /// has been found, its contents in the tree will be cleared, and the pointer
  122. /// will be removed from the main `ContractStateStore`. If anything is not
  123. /// found as initialized, an error is returned.
  124. pub fn remove(&self, db: &sled::Db, contract_id: &ContractId, tree_name: &str) -> Result<()> {
  125. debug!(target: "blockchain::contractstore", "Removing state tree for {}:{}", contract_id, tree_name);
  126. let contract_id_bytes = serialize(contract_id);
  127. let ptr = contract_id.hash_state_id(tree_name);
  128. // A guard to make sure we went through init()
  129. if !self.0.contains_key(&contract_id_bytes)? {
  130. return Err(Error::ContractNotFound(contract_id.to_string()))
  131. }
  132. let state_pointers = self.0.get(&contract_id_bytes)?.unwrap();
  133. let mut state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  134. // We assume the tree has been created already, so it should be listed
  135. // in this array. If not, that's an error.
  136. if !state_pointers.contains(&ptr) {
  137. return Err(Error::ContractStateNotFound)
  138. }
  139. // We open the tree and clear it. This is unfortunately not atomic.
  140. let tree = db.open_tree(ptr)?;
  141. tree.clear()?;
  142. // Remove the deleted tree from the state pointer set.
  143. state_pointers.retain(|x| *x != ptr);
  144. self.0.insert(contract_id_bytes, serialize(&state_pointers))?;
  145. Ok(())
  146. }
  147. /// Abstraction function for fetching a `ZkBinary` and its respective `VerifyingKey`
  148. /// from a contract's zkas sled tree.
  149. pub fn get_zkas(
  150. &self,
  151. db: &sled::Db,
  152. contract_id: &ContractId,
  153. zkas_ns: &str,
  154. ) -> Result<(ZkBinary, VerifyingKey)> {
  155. debug!(target: "blockchain::contractstore", "Looking up \"{}:{}\" zkas circuit & vk", contract_id, zkas_ns);
  156. let zkas_tree = self.lookup(db, contract_id, SMART_CONTRACT_ZKAS_DB_NAME)?;
  157. let Some(zkas_bytes) = zkas_tree.get(serialize(&zkas_ns))? else {
  158. return Err(Error::ZkasBincodeNotFound)
  159. };
  160. // If anything in this function panics, that means corrupted data managed
  161. // to get into this sled tree. This should not be possible.
  162. let (zkbin, vkbin): (Vec<u8>, Vec<u8>) = deserialize(&zkas_bytes).unwrap();
  163. // The first vec is the compiled zkas binary
  164. let zkbin = ZkBinary::decode(&zkbin).unwrap();
  165. // The second one is the serialized VerifyingKey for it
  166. let mut vk_buf = Cursor::new(vkbin);
  167. let vk = VerifyingKey::read::<Cursor<Vec<u8>>, ZkCircuit>(&mut vk_buf).unwrap();
  168. Ok((zkbin, vk))
  169. }
  170. }
  171. /// Overlay structure over a [`ContractStateStore`] instance.
  172. pub struct ContractStateStoreOverlay(SledDbOverlayPtr);
  173. impl ContractStateStoreOverlay {
  174. pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
  175. overlay.lock().unwrap().open_tree(SLED_CONTRACTS_TREE)?;
  176. Ok(Self(overlay))
  177. }
  178. /// Try to initialize a new contract state. Contracts can create a number
  179. /// of trees, separated by `tree_name`, which they can then use from the
  180. /// smart contract API. `init()` will look into the main `ContractStateStoreOverlay`
  181. /// tree to check if the smart contract was already deployed, and if so
  182. /// it will fetch a vector of these states that were initialized. If the
  183. /// state was already found, this function will return an error, because
  184. /// in this case the handle should be fetched using `lookup()`.
  185. /// If the tree was not initialized previously, it will be appended to
  186. /// the main `ContractStateStoreOverlay` tree and a handle to it will be
  187. /// returned.
  188. pub fn init(&self, contract_id: &ContractId, tree_name: &str) -> Result<[u8; 32]> {
  189. debug!(target: "blockchain::contractstoreoverlay", "Initializing state overlay tree for {}:{}", contract_id, tree_name);
  190. let contract_id_bytes = serialize(contract_id);
  191. let ptr = contract_id.hash_state_id(tree_name);
  192. let mut lock = self.0.lock().unwrap();
  193. // See if there are existing state trees.
  194. // If not, just start with an empty vector.
  195. let mut state_pointers: Vec<[u8; 32]> =
  196. if lock.contains_key(SLED_CONTRACTS_TREE, &contract_id_bytes)? {
  197. let bytes = lock.get(SLED_CONTRACTS_TREE, &contract_id_bytes)?.unwrap();
  198. deserialize(&bytes)?
  199. } else {
  200. vec![]
  201. };
  202. // If the db was never initialized, it should not be in here.
  203. if state_pointers.contains(&ptr) {
  204. return Err(Error::ContractAlreadyInitialized)
  205. }
  206. // Now we add it so it's marked as initialized and create its tree.
  207. state_pointers.push(ptr);
  208. lock.insert(SLED_CONTRACTS_TREE, &contract_id_bytes, &serialize(&state_pointers))?;
  209. lock.open_tree(&ptr)?;
  210. Ok(ptr)
  211. }
  212. /// Do a lookup of an existing contract state. In order to succeed, the
  213. /// state must have been previously initialized with `init()`. If the
  214. /// state has been found, a handle to it will be returned. Otherwise, we
  215. /// return an error.
  216. pub fn lookup(&self, contract_id: &ContractId, tree_name: &str) -> Result<[u8; 32]> {
  217. debug!(target: "blockchain::contractstoreoverlay", "Looking up state tree for {}:{}", contract_id, tree_name);
  218. let contract_id_bytes = serialize(contract_id);
  219. let ptr = contract_id.hash_state_id(tree_name);
  220. let mut lock = self.0.lock().unwrap();
  221. // A guard to make sure we went through init()
  222. if !lock.contains_key(SLED_CONTRACTS_TREE, &contract_id_bytes)? {
  223. return Err(Error::ContractNotFound(contract_id.to_string()))
  224. }
  225. let state_pointers = lock.get(SLED_CONTRACTS_TREE, &contract_id_bytes)?.unwrap();
  226. let state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  227. // We assume the tree has been created already, so it should be listed
  228. // in this array. If not, that's an error.
  229. if !state_pointers.contains(&ptr) {
  230. return Err(Error::ContractStateNotFound)
  231. }
  232. // We open the tree and return its handle
  233. lock.open_tree(&ptr)?;
  234. Ok(ptr)
  235. }
  236. }