Skip to content

Commit

Permalink
smt: Switch to SHA-256 hashing (#2401)
Browse files Browse the repository at this point in the history
  • Loading branch information
popcnt1 committed Aug 28, 2024
1 parent 94b9a99 commit 9e0622c
Show file tree
Hide file tree
Showing 8 changed files with 26 additions and 68 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified crates/rooch-genesis/released/main
Binary file not shown.
Binary file modified crates/rooch-genesis/released/test
Binary file not shown.
3 changes: 2 additions & 1 deletion crates/rooch-genesis/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ struct GenesisOpts {
chain_id: BuiltinChainID,
}

fn main() -> Result<()> {
#[tokio::main]
async fn main() -> Result<()> {
let _ = tracing_subscriber::fmt::try_init();
let opts: GenesisOpts = GenesisOpts::parse();
match &opts.chain_id {
Expand Down
11 changes: 5 additions & 6 deletions moveos/smt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,25 @@ rust-version = { workspace = true }
[dependencies]

anyhow = { workspace = true }
backtrace = { workspace = true }
bcs = { workspace = true }
bytes = { workspace = true }
byteorder = { workspace = true }
backtrace = { workspace = true }
bitcoin = { workspace = true }
function_name = { workspace = true }
hex = { workspace = true }
log = { workspace = true }
metrics = { workspace = true }
more-asserts = { workspace = true }
num-derive = { workspace = true }
num-traits = { workspace = true }
once_cell = { workspace = true }
primitive-types = { workspace = true }
prometheus = { workspace = true }
proptest = { workspace = true }
proptest-derive = { workspace = true }
parking_lot = { workspace = true }
rand = { workspace = true }
serde = { workspace = true, features = ["derive", "rc"] }
serde_bytes = { workspace = true }
thiserror = { workspace = true }
tiny-keccak = { workspace = true, features = ["keccak", "sha3"] }
prometheus = { workspace = true }
function_name = { workspace = true }

metrics = { workspace = true }
44 changes: 13 additions & 31 deletions moveos/smt/src/jellyfish_merkle/hash.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use bitcoin::hashes::{sha256t_hash_newtype, Hash};
use bytes::Bytes;
use hex::FromHex;
use more_asserts::debug_assert_lt;
Expand All @@ -14,15 +15,20 @@ use std::{
fmt::{self, Debug},
str::FromStr,
};
use tiny_keccak::{Hasher, Sha3};

sha256t_hash_newtype! {
pub struct RoochSmtTag = hash_str("rooch-smt");

#[hash_newtype(forward)]
pub struct RoochSmtHash(_);
}

pub(crate) fn merkle_hash(left: HashValue, right: HashValue) -> HashValue {
let mut value = left.to_vec();
value.extend(right.to_vec());
HashValue::sha3_256_of(&value)
HashValue::tag_sha256(&value)
}

//TODO replace HashValue with H256
/// Output value of our hash function. Intentionally opaque for safety and modularity.
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
Expand Down Expand Up @@ -73,41 +79,17 @@ impl HashValue {
HashValue { hash }
}

/// Convenience function that computes a `HashValue` internally equal to
/// the sha3_256 of a byte buffer. It will handle hasher creation, data
/// feeding and finalization.
///
/// Note this will not result in the `<T as CryptoHash>::hash()` for any
/// reasonable struct T, as this computes a sha3 without any ornaments.
pub fn sha3_256_of(buffer: &[u8]) -> Self {
let mut sha3 = Sha3::v256();
sha3.update(buffer);
HashValue::from_keccak(sha3)
}

#[cfg(test)]
pub fn from_iter_sha3<'a, I>(buffers: I) -> Self
where
I: IntoIterator<Item = &'a [u8]>,
{
let mut sha3 = Sha3::v256();
for buffer in buffers {
sha3.update(buffer);
}
HashValue::from_keccak(sha3)
/// Creates a new `HashValue` by tagging the given `data` with `rooch-smt`.
pub fn tag_sha256(data: &[u8]) -> Self {
let digest = RoochSmtHash::hash(data);
HashValue::new(digest.to_byte_array())
}

/// Returns the mut reference array
pub fn as_ref_mut(&mut self) -> &mut [u8] {
&mut self.hash[..]
}

fn from_keccak(state: Sha3) -> Self {
let mut hash = Self::zero();
state.finalize(hash.as_ref_mut());
hash
}

/// Returns the `index`-th bit in the bytes.
pub fn bit(&self, index: usize) -> bool {
assert!(index < Self::LENGTH_IN_BITS);
Expand Down
26 changes: 0 additions & 26 deletions moveos/smt/src/jellyfish_merkle/jellyfish_merkle_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1015,29 +1015,3 @@ where
.next()
.map(|(k, _v)| k.clone())
}

//TODO: add test
// #[test]
// fn blob_crypto_hash_test() -> Result<()> {
// let buf = hex::decode(
// "0xfa000000000000007b161ceeef010000000000000000000000000000000000000000000000000000"
// .strip_prefix("0x")
// .ok_or_else(|| format_err!("strip_prefix error"))?,
// )?;
// let blob = Blob::from(buf);
// let hash = blob.merkle_hash();

// let name = starcoin_crypto::_serde_name::trace_name::<Blob>()
// .expect("The `CryptoHasher` macro only applies to structs and enums");
// assert_eq!(name, "Blob");
// let salt_prefix: &[u8] = b"STARCOIN::Blob";
// let ser = bcs::to_bytes(&blob)?;
// let salt = [
// HashValue::sha3_256_of(salt_prefix).as_slice(),
// ser.as_slice(),
// ]
// .concat();
// let hash1 = HashValue::sha3_256_of(&salt[..]);
// assert_eq!(hash, hash1);
// Ok(())
// }
8 changes: 5 additions & 3 deletions moveos/smt/src/smt_object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::jellyfish_merkle::hash::{HashValue, SMTHash};
use std::{cell::Cell, fmt};

use anyhow::Result;
use primitive_types::H256;
use serde::{
de::{self, DeserializeOwned},
Deserialize, Serialize,
};
use std::{cell::Cell, fmt};

use crate::jellyfish_merkle::hash::{HashValue, SMTHash};

pub trait Key: std::cmp::Ord + Copy + Into<H256> + From<H256> {}

Expand Down Expand Up @@ -197,7 +199,7 @@ impl<T> SMTHash for SMTObject<T> {
match self.cached_hash.get() {
Some(hash) => hash,
None => {
let hash = HashValue::sha3_256_of(&self.raw);
let hash = HashValue::tag_sha256(&self.raw);
self.cached_hash.set(Some(hash));
hash
}
Expand Down

0 comments on commit 9e0622c

Please sign in to comment.