contract_store.rs 7.8 KB

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