contractstore.rs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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 darkfi_sdk::crypto::ContractId;
  19. use darkfi_serial::{deserialize, serialize};
  20. use log::{debug, error};
  21. use crate::{Error, Result};
  22. const SLED_CONTRACTS_TREE: &[u8] = b"_contracts";
  23. const SLED_BINCODE_TREE: &[u8] = b"_wasm_bincode";
  24. // Logger targets
  25. const CS_TGT_INIT: &str = "blockchain::contractstatestore::init";
  26. const CS_TGT_LKUP: &str = "blockchain::contractstatestore::lookup";
  27. const CS_TGT_DROP: &str = "blockchain::contractstatestore::remove";
  28. /// The `WasmStore` is a `sled` tree that stores the wasm bincode for deployed
  29. /// contracts.
  30. #[derive(Clone)]
  31. pub struct WasmStore(sled::Tree);
  32. impl WasmStore {
  33. /// Opens or creates a `WasmStore`. This tree holds the wasm bincode.
  34. /// The layout looks like this:
  35. /// ```plaintext
  36. /// tree: "_wasm_bincode"
  37. /// key: ContractId
  38. /// value: Vec<u8>
  39. pub fn new(db: &sled::Db) -> Result<Self> {
  40. let tree = db.open_tree(SLED_BINCODE_TREE)?;
  41. Ok(Self(tree))
  42. }
  43. /// Fetches the bincode for a given ContractId
  44. /// Returns an error if the bincode is not found.
  45. pub fn get(&self, contract_id: ContractId) -> Result<Vec<u8>> {
  46. if let Some(bincode) = self.0.get(&serialize(&contract_id))? {
  47. return Ok(bincode.to_vec())
  48. }
  49. Err(Error::WasmBincodeNotFound)
  50. }
  51. /// Inserts or replaces the bincode for a given ContractId
  52. pub fn insert(&self, contract_id: ContractId, bincode: &[u8]) -> Result<()> {
  53. if let Err(e) = self.0.insert(&serialize(&contract_id), bincode) {
  54. error!("Failed to insert bincode to WasmStore: {}", e);
  55. return Err(e.into())
  56. }
  57. Ok(())
  58. }
  59. }
  60. /// The `ContractStateStore` is a `sled` tree that stores pointers to contracts'
  61. /// databases. See the rustdoc for the impl functions for more info.
  62. #[derive(Clone)]
  63. pub struct ContractStateStore(sled::Tree);
  64. impl ContractStateStore {
  65. /// Opens or creates a `ContractStateStore`. This main tree holds the links
  66. /// of contracts' states.
  67. /// The layout looks like this:
  68. /// ```plaintext
  69. /// tree: "_contracts"
  70. /// key: ContractId
  71. /// value: Vec<blake3(ContractId || tree_name)>
  72. /// ```
  73. /// These values get mutated with `init()` and `remove()`.
  74. pub fn new(db: &sled::Db) -> Result<Self> {
  75. let tree = db.open_tree(SLED_CONTRACTS_TREE)?;
  76. Ok(Self(tree))
  77. }
  78. /// Try to initialize a new contract state. Contracts can create a number
  79. /// of trees, separated by `tree_name`, which they can then use from the
  80. /// smart contract API. `init()` will look into the main `ContractStateStore`
  81. /// tree to check if the smart contract was already deployed, and if so
  82. /// it will fetch a vector of these states that were initialized. If the
  83. /// state was already found, this function will return an error, because
  84. /// in this case the handle should be fetched using `lookup()`.
  85. /// If the tree was not initialized previously, it will be appended to
  86. /// the main `ContractStateStore` tree and a `sled::Tree` handle will be
  87. /// returned.
  88. pub fn init(
  89. &self,
  90. db: &sled::Db,
  91. contract_id: &ContractId,
  92. tree_name: &str,
  93. ) -> Result<sled::Tree> {
  94. debug!(target: CS_TGT_INIT, "Initializing state tree for {}:{}", contract_id, tree_name);
  95. let contract_id_bytes = serialize(contract_id);
  96. let ptr = contract_id.hash_state_id(tree_name);
  97. // See if there are existing state trees. If not, just start with an
  98. // empty vector.
  99. let mut state_pointers: Vec<[u8; 32]> = if self.0.contains_key(&contract_id_bytes)? {
  100. let bytes = self.0.get(&contract_id_bytes)?.unwrap();
  101. deserialize(&bytes)?
  102. } else {
  103. vec![]
  104. };
  105. // If the db was never initialized, it should not be in here.
  106. if state_pointers.contains(&ptr) {
  107. return Err(Error::ContractAlreadyInitialized)
  108. }
  109. // Now we add it so it's marked as initialized
  110. state_pointers.push(ptr);
  111. // We do this as a batch so in case of not being able to open the tree
  112. // we don't write that it's initialized.
  113. let mut batch = sled::Batch::default();
  114. batch.insert(contract_id_bytes, serialize(&state_pointers));
  115. // We open the tree and return its handle
  116. let tree = db.open_tree(ptr)?;
  117. // On success, apply the batch
  118. self.0.apply_batch(batch)?;
  119. Ok(tree)
  120. }
  121. /// Do a lookup of an existing contract state. In order to succeed, the
  122. /// state must have been previously initialized with `init()`. If the
  123. /// state has been found, a handle to it will be returned. Otherwise, we
  124. /// return an error.
  125. pub fn lookup(
  126. &self,
  127. db: &sled::Db,
  128. contract_id: &ContractId,
  129. tree_name: &str,
  130. ) -> Result<sled::Tree> {
  131. debug!(target: CS_TGT_LKUP, "Looking up state tree for {}:{}", contract_id, tree_name);
  132. let contract_id_bytes = serialize(contract_id);
  133. let ptr = contract_id.hash_state_id(tree_name);
  134. // A guard to make sure we went through init()
  135. if !self.0.contains_key(&contract_id_bytes)? {
  136. return Err(Error::ContractNotFound(contract_id.to_string()))
  137. }
  138. let state_pointers = self.0.get(&contract_id_bytes)?.unwrap();
  139. let state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  140. // We assume the tree has been created already, so it should be listed
  141. // in this array. If not, that's an error.
  142. if !state_pointers.contains(&ptr) {
  143. return Err(Error::ContractStateNotFound)
  144. }
  145. // We open the tree and return its handle
  146. let tree = db.open_tree(ptr)?;
  147. Ok(tree)
  148. }
  149. /// Attempt to remove an existing contract state. In order to succeed, the
  150. /// state must have been previously initialized with `init()`. If the state
  151. /// has been found, its contents in the tree will be cleared, and the pointer
  152. /// will be removed from the main `ContractStateStore`. If anything is not
  153. /// found as initialized, an error is returned.
  154. pub fn remove(&self, db: &sled::Db, contract_id: &ContractId, tree_name: &str) -> Result<()> {
  155. debug!(target: CS_TGT_DROP, "Removing state tree for {}:{}", contract_id, tree_name);
  156. let contract_id_bytes = serialize(contract_id);
  157. let ptr = contract_id.hash_state_id(tree_name);
  158. // A guard to make sure we went through init()
  159. if !self.0.contains_key(&contract_id_bytes)? {
  160. return Err(Error::ContractNotFound(contract_id.to_string()))
  161. }
  162. let state_pointers = self.0.get(&contract_id_bytes)?.unwrap();
  163. let mut state_pointers: Vec<[u8; 32]> = deserialize(&state_pointers)?;
  164. // We assume the tree has been created already, so it should be listed
  165. // in this array. If not, that's an error.
  166. if !state_pointers.contains(&ptr) {
  167. return Err(Error::ContractStateNotFound)
  168. }
  169. // We open the tree and clear it. This is unfortunately not atomic.
  170. let tree = db.open_tree(ptr)?;
  171. tree.clear()?;
  172. state_pointers.retain(|x| *x != ptr);
  173. self.0.insert(contract_id_bytes, serialize(&state_pointers))?;
  174. Ok(())
  175. }
  176. }