cache.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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. * 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::collections::HashMap;
  19. use darkfi::{blockchain::HeaderHash, Error, Result};
  20. use darkfi_sdk::{
  21. crypto::{
  22. pasta_prelude::PrimeField,
  23. smt::{PoseidonFp, SparseMerkleTree, StorageAdapter, SMT_FP_DEPTH},
  24. MerkleTree,
  25. },
  26. error::{ContractError, ContractResult},
  27. pasta::pallas,
  28. };
  29. use darkfi_serial::{deserialize, serialize};
  30. use log::error;
  31. use num_bigint::BigUint;
  32. use sled_overlay::{sled, SledDbOverlay, SledDbOverlayStateDiff};
  33. pub const SLED_SCANNED_BLOCKS_TREE: &[u8] = b"_scanned_blocks";
  34. pub const SLED_STATE_INVERSE_DIFF_TREE: &[u8] = b"_state_inverse_diff";
  35. pub const SLED_MERKLE_TREES_TREE: &[u8] = b"_merkle_trees";
  36. pub const SLED_MONEY_SMT_TREE: &[u8] = b"_money_smt";
  37. /// Structure holding all sled trees that define the blockchain cache.
  38. #[derive(Clone)]
  39. pub struct Cache {
  40. /// Main pointer to the sled db connection
  41. pub sled_db: sled::Db,
  42. /// The `sled` tree storing the scanned blocks from the blockchain,
  43. /// where the key is the height number, and the value is the blocks'
  44. /// hash.
  45. pub scanned_blocks: sled::Tree,
  46. /// The `sled` tree storing each blocks' full database state inverse
  47. /// changes, where the key is the block height number, and the value
  48. /// is the serialized database inverse diff.
  49. pub state_inverse_diff: sled::Tree,
  50. /// The `sled` tree storing the merkle trees of the blockchain,
  51. /// where the key is the tree name, and the value is the serialized
  52. /// merkle tree itself.
  53. pub merkle_trees: sled::Tree,
  54. /// The `sled` tree storing the Sparse Merkle Tree of the Money
  55. /// contract.
  56. // TODO: this could be a map of trees so more contracts can open
  57. // SMTs if needed
  58. pub money_smt: sled::Tree,
  59. // TODO: Perhaps we should also move transactions history here
  60. }
  61. impl Cache {
  62. /// Instantiate a new `Cache` with the given `sled` database.
  63. pub fn new(db: &sled::Db) -> Result<Self> {
  64. let scanned_blocks = db.open_tree(SLED_SCANNED_BLOCKS_TREE)?;
  65. let state_inverse_diff = db.open_tree(SLED_STATE_INVERSE_DIFF_TREE)?;
  66. let merkle_trees = db.open_tree(SLED_MERKLE_TREES_TREE)?;
  67. let money_smt = db.open_tree(SLED_MONEY_SMT_TREE)?;
  68. Ok(Self {
  69. sled_db: db.clone(),
  70. scanned_blocks,
  71. state_inverse_diff,
  72. merkle_trees,
  73. money_smt,
  74. })
  75. }
  76. /// Fetch given block height numbers from the store's state inverse
  77. /// diffs tree. The function will fail if a block height number was
  78. /// not found.
  79. pub fn get_state_inverse_diff(&self, heights: &[u32]) -> Result<Vec<SledDbOverlayStateDiff>> {
  80. let mut ret = Vec::with_capacity(heights.len());
  81. for height in heights {
  82. match self.state_inverse_diff.get(height.to_be_bytes())? {
  83. Some(found) => ret.push(deserialize(&found)?),
  84. None => return Err(Error::BlockStateInverseDiffNotFound(*height)),
  85. };
  86. }
  87. Ok(ret)
  88. }
  89. }
  90. /// Overlay structure over a [`Cache`] instance.
  91. pub struct CacheOverlay(pub SledDbOverlay);
  92. impl CacheOverlay {
  93. /// Instantiate a new `CacheOverlay` over the given [`Cache`] instance.
  94. pub fn new(cache: &Cache) -> Result<CacheOverlay> {
  95. // Here we configure all our cache sled trees to be protected in the overlay
  96. let protected_trees = vec![
  97. SLED_SCANNED_BLOCKS_TREE,
  98. SLED_STATE_INVERSE_DIFF_TREE,
  99. SLED_MERKLE_TREES_TREE,
  100. SLED_MONEY_SMT_TREE,
  101. ];
  102. let mut overlay = SledDbOverlay::new(&cache.sled_db, protected_trees);
  103. // Open all our cache sled trees in the overlay
  104. overlay.open_tree(SLED_SCANNED_BLOCKS_TREE, true)?;
  105. overlay.open_tree(SLED_STATE_INVERSE_DIFF_TREE, true)?;
  106. overlay.open_tree(SLED_MERKLE_TREES_TREE, true)?;
  107. overlay.open_tree(SLED_MONEY_SMT_TREE, true)?;
  108. Ok(Self(overlay))
  109. }
  110. /// Insert a `u32` and a block hash into overlay's scanned blocks
  111. /// tree. The block height is used as the key, and the serialized
  112. /// blockhash string is used as value.
  113. pub fn insert_scanned_block(&mut self, height: &u32, hash: &HeaderHash) -> Result<()> {
  114. self.0.insert(
  115. SLED_SCANNED_BLOCKS_TREE,
  116. &height.to_be_bytes(),
  117. &serialize(&hash.to_string()),
  118. )?;
  119. Ok(())
  120. }
  121. /// Insert a `u32` and a block inverse diff into overlay's inverse
  122. /// diffs tree. The block height is used as the key, and the
  123. /// serialized database inverse diff is used as value.
  124. pub fn insert_state_inverse_diff(
  125. &mut self,
  126. height: &u32,
  127. diff: &SledDbOverlayStateDiff,
  128. ) -> Result<()> {
  129. self.0.insert(SLED_STATE_INVERSE_DIFF_TREE, &height.to_be_bytes(), &serialize(diff))?;
  130. Ok(())
  131. }
  132. /// Insert a bytes slice and a merkle tree into overlay's merkle
  133. /// trees tree. The provided bytes slice is used as the key, and
  134. /// the serialized merkle tree is used as value.
  135. pub fn insert_merkle_tree(&mut self, key: &[u8], tree: &MerkleTree) -> Result<()> {
  136. self.0.insert(SLED_MERKLE_TREES_TREE, key, &serialize(tree))?;
  137. Ok(())
  138. }
  139. }
  140. pub type CacheSmt = SparseMerkleTree<
  141. 'static,
  142. SMT_FP_DEPTH,
  143. { SMT_FP_DEPTH + 1 },
  144. pallas::Base,
  145. PoseidonFp,
  146. CacheSmtStorage,
  147. >;
  148. pub struct CacheSmtStorage {
  149. pub overlay: CacheOverlay,
  150. tree: Vec<u8>,
  151. }
  152. impl CacheSmtStorage {
  153. pub fn new(overlay: CacheOverlay, tree: &[u8]) -> Self {
  154. Self { overlay, tree: tree.to_vec() }
  155. }
  156. pub fn snapshot(&self) -> Result<HashMap<BigUint, pallas::Base>> {
  157. let mut smt = HashMap::new();
  158. for record in self.overlay.0.iter(&self.tree)? {
  159. let (key, value) = record?;
  160. let mut repr = [0; 32];
  161. repr.copy_from_slice(&value);
  162. let Some(value) = pallas::Base::from_repr(repr).into() else {
  163. return Err(Error::ParseFailed(
  164. "[cache::CacheSmtStorage::snapshot] Value conversion failed",
  165. ))
  166. };
  167. smt.insert(BigUint::from_bytes_le(&key), value);
  168. }
  169. Ok(smt)
  170. }
  171. }
  172. impl StorageAdapter for CacheSmtStorage {
  173. type Value = pallas::Base;
  174. fn put(&mut self, key: BigUint, value: pallas::Base) -> ContractResult {
  175. if let Err(e) = self.overlay.0.insert(&self.tree, &key.to_bytes_le(), &value.to_repr()) {
  176. error!(target: "cache::StorageAdapter::put", "Inserting key {key:?}, value {value:?} into DB failed: {e:?}");
  177. return Err(ContractError::SmtPutFailed)
  178. }
  179. Ok(())
  180. }
  181. fn get(&self, key: &BigUint) -> Option<pallas::Base> {
  182. let value = match self.overlay.0.get(&self.tree, &key.to_bytes_le()) {
  183. Ok(v) => v,
  184. Err(e) => {
  185. error!(target: "cache::StorageAdapter::get", "Fetching key {key:?} from DB failed: {e:?}");
  186. return None
  187. }
  188. };
  189. let value = value?;
  190. let mut repr = [0; 32];
  191. repr.copy_from_slice(&value);
  192. pallas::Base::from_repr(repr).into()
  193. }
  194. fn del(&mut self, key: &BigUint) -> ContractResult {
  195. if let Err(e) = self.overlay.0.remove(&self.tree, &key.to_bytes_le()) {
  196. error!(target: "cache::StorageAdapter::del", "Removing key {key:?} from DB failed: {e:?}");
  197. return Err(ContractError::SmtDelFailed)
  198. }
  199. Ok(())
  200. }
  201. }
  202. #[cfg(test)]
  203. mod tests {
  204. use darkfi::{zk::halo2::Field, Result};
  205. use darkfi_sdk::{
  206. crypto::smt::{gen_empty_nodes, util::FieldHasher, PoseidonFp, SparseMerkleTree},
  207. pasta::pallas,
  208. };
  209. use rand::rngs::OsRng;
  210. use sled_overlay::sled;
  211. use crate::cache::{Cache, CacheOverlay, CacheSmtStorage, SLED_MONEY_SMT_TREE};
  212. #[test]
  213. fn test_cache_smt() -> Result<()> {
  214. // Setup cache and its overlay
  215. let sled_db = sled::Config::new().temporary(true).open()?;
  216. let cache = Cache::new(&sled_db)?;
  217. let overlay = CacheOverlay::new(&cache)?;
  218. // Setup SMT
  219. const HEIGHT: usize = 3;
  220. let hasher = PoseidonFp::new();
  221. let empty_leaf = pallas::Base::ZERO;
  222. let empty_nodes = gen_empty_nodes::<{ HEIGHT + 1 }, _, _>(&hasher, empty_leaf);
  223. let store = CacheSmtStorage::new(overlay, SLED_MONEY_SMT_TREE);
  224. let mut smt = SparseMerkleTree::<HEIGHT, { HEIGHT + 1 }, _, _, _>::new(
  225. store,
  226. hasher.clone(),
  227. &empty_nodes,
  228. );
  229. // Verify database is empty
  230. assert!(cache.money_smt.is_empty());
  231. let leaves = vec![
  232. (pallas::Base::from(1), pallas::Base::random(&mut OsRng)),
  233. (pallas::Base::from(2), pallas::Base::random(&mut OsRng)),
  234. (pallas::Base::from(3), pallas::Base::random(&mut OsRng)),
  235. ];
  236. smt.insert_batch(leaves.clone()).unwrap();
  237. let hash1 = leaves[0].1;
  238. let hash2 = leaves[1].1;
  239. let hash3 = leaves[2].1;
  240. let hash = |l, r| hasher.hash([l, r]);
  241. let hash01 = hash(empty_nodes[3], hash1);
  242. let hash23 = hash(hash2, hash3);
  243. let hash0123 = hash(hash01, hash23);
  244. let root = hash(hash0123, empty_nodes[1]);
  245. assert_eq!(root, smt.root());
  246. // Now try to construct a membership proof for leaf 3
  247. let pos = leaves[2].0;
  248. let path = smt.prove_membership(&pos);
  249. assert_eq!(path.path[0], empty_nodes[1]);
  250. assert_eq!(path.path[1], hash01);
  251. assert_eq!(path.path[2], hash2);
  252. assert_eq!(hash23, hash(path.path[2], hash3));
  253. assert_eq!(hash0123, hash(path.path[1], hash(path.path[2], hash3)));
  254. assert_eq!(root, hash(hash(path.path[1], hash(path.path[2], hash3)), path.path[0]));
  255. assert!(path.verify(&root, &hash3, &pos));
  256. // Grab the overlay diff
  257. let diff = smt.store.overlay.0.diff(&[])?;
  258. // Apply the overlay
  259. smt.store.overlay.0.apply_diff(&diff)?;
  260. // Verify database contains keys
  261. assert!(!cache.money_smt.is_empty());
  262. // We are now going to rollback the changes
  263. smt.store.overlay.0.apply_diff(&diff.inverse())?;
  264. // Verify database is empty again
  265. assert!(cache.money_smt.is_empty());
  266. Ok(())
  267. }
  268. }