Skip to content

Commit b0c0cb7

Browse files
jpraynaudAlenar
andcommitted
refactor: MKTreeStores to avoid re-exporting of 'merkle_mountain_range' crate
Co-authored-by: DJO <[email protected]>
1 parent 29c9c72 commit b0c0cb7

File tree

3 files changed

+95
-57
lines changed

3 files changed

+95
-57
lines changed

mithril-common/src/crypto_helper/merkle_tree.rs

Lines changed: 81 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use anyhow::{anyhow, Context};
22
use blake2::{Blake2s256, Digest};
33
use ckb_merkle_mountain_range::{
4-
MMRStoreReadOps, MMRStoreWriteOps, Merge, MerkleProof, Result as MMRResult, MMR,
4+
Error as MMRError, MMRStoreReadOps, MMRStoreWriteOps, Merge, MerkleProof, Result as MMRResult,
5+
MMR,
56
};
67
use serde::{Deserialize, Serialize};
78
use std::{
@@ -210,25 +211,6 @@ impl MKTreeStoreInMemory {
210211
}
211212
}
212213

213-
impl MMRStoreReadOps<Arc<MKTreeNode>> for MKTreeStoreInMemory {
214-
fn get_elem(&self, pos: u64) -> MMRResult<Option<Arc<MKTreeNode>>> {
215-
let inner_store = self.inner_store.read().unwrap();
216-
217-
Ok((*inner_store).get(&pos).cloned())
218-
}
219-
}
220-
221-
impl MMRStoreWriteOps<Arc<MKTreeNode>> for MKTreeStoreInMemory {
222-
fn append(&mut self, pos: u64, elems: Vec<Arc<MKTreeNode>>) -> MMRResult<()> {
223-
let mut inner_store = self.inner_store.write().unwrap();
224-
for (i, elem) in elems.into_iter().enumerate() {
225-
(*inner_store).insert(pos + i as u64, elem);
226-
}
227-
228-
Ok(())
229-
}
230-
}
231-
232214
impl MKTreeLeafIndexer for MKTreeStoreInMemory {
233215
fn set_leaf_position(&self, pos: MKTreeLeafPosition, node: Arc<MKTreeNode>) -> StdResult<()> {
234216
let mut inner_leaves = self.inner_leaves.write().unwrap();
@@ -263,19 +245,88 @@ impl MKTreeStorer for MKTreeStoreInMemory {
263245
fn build() -> StdResult<Self> {
264246
Ok(Self::new())
265247
}
248+
249+
fn get_elem(&self, pos: u64) -> StdResult<Option<Arc<MKTreeNode>>> {
250+
let inner_store = self.inner_store.read().unwrap();
251+
252+
Ok((*inner_store).get(&pos).cloned())
253+
}
254+
255+
fn append(&self, pos: u64, elems: Vec<Arc<MKTreeNode>>) -> StdResult<()> {
256+
let mut inner_store = self.inner_store.write().unwrap();
257+
for (i, elem) in elems.into_iter().enumerate() {
258+
(*inner_store).insert(pos + i as u64, elem);
259+
}
260+
261+
Ok(())
262+
}
266263
}
267264

268265
/// The Merkle tree storer trait
269-
pub trait MKTreeStorer:
270-
Clone
271-
+ Send
272-
+ Sync
273-
+ MKTreeLeafIndexer
274-
+ MMRStoreReadOps<Arc<MKTreeNode>>
275-
+ MMRStoreWriteOps<Arc<MKTreeNode>>
276-
{
266+
pub trait MKTreeStorer: Clone + Send + Sync + MKTreeLeafIndexer {
277267
/// Try to create a new instance of the storer
278268
fn build() -> StdResult<Self>;
269+
270+
/// Get the element at the given position
271+
fn get_elem(&self, pos: u64) -> StdResult<Option<Arc<MKTreeNode>>>;
272+
273+
/// Append elements at the given position
274+
fn append(&self, pos: u64, elems: Vec<Arc<MKTreeNode>>) -> StdResult<()>;
275+
}
276+
277+
/// This struct exists only to implement for a [MkTreeStore] the [MMRStoreReadOps] and
278+
/// [MMRStoreWriteOps] from merkle_mountain_range crate without the need to reexport types
279+
/// from that crate.
280+
///
281+
/// Rust don't allow the following:
282+
/// ```ignore
283+
/// impl<S: MKTreeStorer> MMRStoreReadOps<Arc<MKTreeNode>> for S {}
284+
/// ```
285+
/// Since it disallows implementations of traits for arbitrary types which are not defined in
286+
/// the same crate as the trait itself (see [E0117](https://doc.rust-lang.org/error_codes/E0117.html)).
287+
struct MKTreeStore<S: MKTreeStorer> {
288+
storer: Box<S>,
289+
}
290+
291+
impl<S: MKTreeStorer> MKTreeStore<S> {
292+
fn build() -> StdResult<Self> {
293+
let storer = Box::new(S::build()?);
294+
Ok(Self { storer })
295+
}
296+
}
297+
298+
impl<S: MKTreeStorer> MMRStoreReadOps<Arc<MKTreeNode>> for MKTreeStore<S> {
299+
fn get_elem(&self, pos: u64) -> MMRResult<Option<Arc<MKTreeNode>>> {
300+
self.storer
301+
.get_elem(pos)
302+
.map_err(|e| MMRError::StoreError(e.to_string()))
303+
}
304+
}
305+
306+
impl<S: MKTreeStorer> MMRStoreWriteOps<Arc<MKTreeNode>> for MKTreeStore<S> {
307+
fn append(&mut self, pos: u64, elems: Vec<Arc<MKTreeNode>>) -> MMRResult<()> {
308+
self.storer
309+
.append(pos, elems)
310+
.map_err(|e| MMRError::StoreError(e.to_string()))
311+
}
312+
}
313+
314+
impl<S: MKTreeStorer> MKTreeLeafIndexer for MKTreeStore<S> {
315+
fn set_leaf_position(&self, pos: MKTreeLeafPosition, leaf: Arc<MKTreeNode>) -> StdResult<()> {
316+
self.storer.set_leaf_position(pos, leaf)
317+
}
318+
319+
fn get_leaf_position(&self, leaf: &MKTreeNode) -> Option<MKTreeLeafPosition> {
320+
self.storer.get_leaf_position(leaf)
321+
}
322+
323+
fn total_leaves(&self) -> usize {
324+
self.storer.total_leaves()
325+
}
326+
327+
fn leaves(&self) -> Vec<MKTreeNode> {
328+
self.storer.leaves()
329+
}
279330
}
280331

281332
/// The Merkle tree leaves indexer trait
@@ -300,13 +351,13 @@ pub trait MKTreeLeafIndexer {
300351

301352
/// A Merkle tree
302353
pub struct MKTree<S: MKTreeStorer> {
303-
inner_tree: MMR<Arc<MKTreeNode>, MergeMKTreeNode, S>,
354+
inner_tree: MMR<Arc<MKTreeNode>, MergeMKTreeNode, MKTreeStore<S>>,
304355
}
305356

306357
impl<S: MKTreeStorer> MKTree<S> {
307358
/// MKTree factory
308359
pub fn new<T: Into<MKTreeNode> + Clone>(leaves: &[T]) -> StdResult<Self> {
309-
let mut inner_tree = MMR::<_, _, _>::new(0, S::build()?);
360+
let mut inner_tree = MMR::<_, _, _>::new(0, MKTreeStore::<S>::build()?);
310361
for leaf in leaves {
311362
let leaf = Arc::new(leaf.to_owned().into());
312363
let inner_tree_position = inner_tree.push(leaf.clone())?;

mithril-common/src/crypto_helper/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ pub use cardano::{
2121
KESPeriod, OpCert, ProtocolInitializerErrorWrapper, ProtocolRegistrationErrorWrapper,
2222
SerDeShelleyFileFormat, Sum6KesBytes,
2323
};
24-
pub use ckb_merkle_mountain_range;
2524
pub use codec::*;
2625
pub use era::{
2726
EraMarkersSigner, EraMarkersVerifier, EraMarkersVerifierError, EraMarkersVerifierSecretKey,

mithril-signer/src/mktree_store_sqlite.rs

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,7 @@ use std::{
55

66
use anyhow::Context;
77
use mithril_common::{
8-
crypto_helper::{
9-
ckb_merkle_mountain_range::{
10-
Error as MMRError, MMRStoreReadOps, MMRStoreWriteOps, Result as MMRResult,
11-
},
12-
Bytes, MKTreeLeafIndexer, MKTreeLeafPosition, MKTreeNode, MKTreeStorer,
13-
},
8+
crypto_helper::{Bytes, MKTreeLeafIndexer, MKTreeLeafPosition, MKTreeNode, MKTreeStorer},
149
StdResult,
1510
};
1611

@@ -96,26 +91,6 @@ impl MKTreeStoreSqlite {
9691
}
9792
}
9893

99-
impl MMRStoreReadOps<Arc<MKTreeNode>> for MKTreeStoreSqlite {
100-
fn get_elem(&self, pos: u64) -> MMRResult<Option<Arc<MKTreeNode>>> {
101-
self.get_element_at_position(pos)
102-
.with_context(|| {
103-
format!("MKTreeStoreSqlite failed to retrieve element at position {pos}")
104-
})
105-
.map_err(|e| MMRError::StoreError(e.to_string()))
106-
}
107-
}
108-
109-
impl MMRStoreWriteOps<Arc<MKTreeNode>> for MKTreeStoreSqlite {
110-
fn append(&mut self, pos: u64, elems: Vec<Arc<MKTreeNode>>) -> MMRResult<()> {
111-
self.insert_elements_from_position(pos, elems)
112-
.with_context(|| {
113-
format!("MKTreeStoreSqlite failed to insert elements from position {pos}")
114-
})
115-
.map_err(|e| MMRError::StoreError(e.to_string()))
116-
}
117-
}
118-
11994
impl Clone for MKTreeStoreSqlite {
12095
fn clone(&self) -> Self {
12196
unimplemented!("Clone is not implemented for MKTreeStoreSqlite")
@@ -144,6 +119,19 @@ impl MKTreeStorer for MKTreeStoreSqlite {
144119
fn build() -> StdResult<Self> {
145120
Self::build()
146121
}
122+
123+
fn get_elem(&self, pos: u64) -> StdResult<Option<Arc<MKTreeNode>>> {
124+
self.get_element_at_position(pos).with_context(|| {
125+
format!("MKTreeStoreSqlite failed to retrieve element at position {pos}")
126+
})
127+
}
128+
129+
fn append(&self, pos: u64, elems: Vec<Arc<MKTreeNode>>) -> StdResult<()> {
130+
self.insert_elements_from_position(pos, elems)
131+
.with_context(|| {
132+
format!("MKTreeStoreSqlite failed to insert elements from position {pos}")
133+
})
134+
}
147135
}
148136

149137
#[cfg(test)]

0 commit comments

Comments
 (0)