0g-storage-node/common/merkle_light/src/test_cmh.rs
peilun-conflux 4eb2a50b0e
Use inner lock in storage and use async lock. (#92)
* Use inner lock in storage.

* Remove mut.

* Remove async lock for storage.

* Fix tests and warnings.

* Use spawn_blocking for storage task.

* Fix clippy.

* Finalize the new tx at last.

* Revert "Finalize the new tx at last."

This reverts commit b56ad5582d.

* Wait for old same-root txs to finalize.

* Use async storage in miner.

* Update rust version to 1.79.0.

* Use Vec to avoid stack overflow.

* Fix unused warning.

* Fix clippy.

* Fix test warning.

* Fix test.

* fmt.

* Use async storage in pruner.

* nit.
2024-06-29 17:08:02 +08:00

75 lines
1.5 KiB
Rust

use crate::hash::{Algorithm, Hashable};
use crate::merkle::MerkleTree;
use crate::test_item::Item;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
use std::iter::FromIterator;
/// Custom merkle hash util test
#[derive(Debug, Clone, Default)]
struct Cmh(DefaultHasher);
impl Cmh {
pub fn new() -> Cmh {
Cmh(DefaultHasher::new())
}
}
impl Hasher for Cmh {
#[inline]
fn write(&mut self, msg: &[u8]) {
self.0.write(msg)
}
#[inline]
fn finish(&self) -> u64 {
self.0.finish()
}
}
impl Algorithm<Item> for Cmh {
#[inline]
fn hash(&mut self) -> Item {
Item(self.finish())
}
#[inline]
fn reset(&mut self) {
*self = Cmh::default()
}
#[inline]
fn leaf(&mut self, leaf: Item) -> Item {
Item(leaf.0 & 0xff)
}
#[inline]
fn node(&mut self, left: Item, right: Item) -> Item {
self.write(&[1u8]);
self.write(left.as_ref());
self.write(&[2u8]);
self.write(right.as_ref());
Item(self.hash().0 & 0xffff)
}
}
#[test]
fn test_custom_merkle_hasher() {
let mut a = Cmh::new();
let mt: MerkleTree<Item, Cmh> = MerkleTree::from_iter([1, 2, 3, 4, 5].iter().map(|x| {
a.reset();
x.hash(&mut a);
a.hash()
}));
assert_eq!(
mt.as_slice()
.iter()
.take(mt.leafs())
.filter(|&&x| x.0 > 255)
.count(),
0
);
assert_eq!(mt.as_slice().iter().filter(|&&x| x.0 > 65535).count(), 0);
}