contract_store.rs 13 KB

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