cache.rs 11 KB

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