contract_store.rs 13 KB

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