Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: remove hash_digest type #4376

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions base_layer/common_types/src/types/bullet_rangeproofs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ use serde::{
};
use tari_utilities::{hex::*, ByteArray, ByteArrayError, Hashable};

use crate::types::HashDigest;
use crate::types::Blake256;

#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct BulletRangeProof(pub Vec<u8>);
/// Implement the hashing function for RangeProof for use in the MMR
impl Hashable for BulletRangeProof {
fn hash(&self) -> Vec<u8> {
HashDigest::new().chain(&self.0).finalize().to_vec()
Blake256::new().chain(&self.0).finalize().to_vec()
}
}

Expand Down
4 changes: 2 additions & 2 deletions base_layer/common_types/src/types/fixed_hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use digest::{consts::U32, generic_array, Digest};
use serde::{Deserialize, Serialize};
use tari_utilities::hex::{Hex, HexError};

use crate::types::HashDigest;
use crate::types::Blake256;

const ZERO_HASH: [u8; FixedHash::byte_size()] = [0u8; FixedHash::byte_size()];

Expand All @@ -57,7 +57,7 @@ impl FixedHash {
/// Hashes the bytes and returns the resulting `FixedHash`. Generally only be used as a convenience function for
/// tests.
pub fn hash_bytes<T: AsRef<[u8]>>(bytes: T) -> Self {
HashDigest::default().chain(bytes).finalize().into()
Blake256::default().chain(bytes).finalize().into()
}
}

Expand Down
5 changes: 1 addition & 4 deletions base_layer/common_types/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,13 @@ pub type BlindingFactor = RistrettoSecretKey;
/// Define the hash function that will be used to produce a signature challenge
pub type SignatureHasher = Blake256;

/// Specify the Hash function for general hashing
pub type HashDigest = Blake256;

/// Specify the digest type for signature challenges
pub type Challenge = Blake256;

/// The type of output that `Challenge` produces
pub type MessageHash = Vec<u8>;

/// Define the data type that is used to store results of `HashDigest`
/// Define the data type that is used to store results of a hash output
pub type HashOutput = Vec<u8>;

pub const RANGE_PROOF_BIT_LENGTH: usize = 64; // 2^64
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ use std::{
use croaring::Bitmap;
use futures::{stream::FuturesUnordered, StreamExt};
use log::*;
use tari_common_types::types::{Commitment, HashDigest, RangeProofService};
use tari_common_types::types::{Commitment, RangeProofService};
use tari_comms::{connectivity::ConnectivityRequester, peer_manager::NodeId};
use tari_crypto::{
commitment::HomomorphicCommitment,
hash::blake2::Blake256,
tari_utilities::{hex::Hex, Hashable},
};
use tari_mmr::{MerkleMountainRange, MutableMmr};
Expand Down Expand Up @@ -325,7 +326,7 @@ impl<'a, B: BlockchainBackend + 'static> HorizonStateSynchronization<'a, B> {
.fetch_block_accumulated_data(current_header.header().prev_hash.clone())
.await?;
let kernel_pruned_set = block_data.dissolve().0;
let mut kernel_mmr = MerkleMountainRange::<HashDigest, _>::new(kernel_pruned_set);
let mut kernel_mmr = MerkleMountainRange::<Blake256, _>::new(kernel_pruned_set);

for hash in kernel_hashes.drain(..) {
kernel_mmr.push(hash)?;
Expand Down Expand Up @@ -486,8 +487,8 @@ impl<'a, B: BlockchainBackend + 'static> HorizonStateSynchronization<'a, B> {
.await?;
let (_, output_pruned_set, witness_pruned_set, _) = block_data.dissolve();

let mut output_mmr = MerkleMountainRange::<HashDigest, _>::new(output_pruned_set);
let mut witness_mmr = MerkleMountainRange::<HashDigest, _>::new(witness_pruned_set);
let mut output_mmr = MerkleMountainRange::<Blake256, _>::new(output_pruned_set);
let mut witness_mmr = MerkleMountainRange::<Blake256, _>::new(witness_pruned_set);
let mut constants = self.rules.consensus_constants(current_header.height()).clone();
let mut last_sync_timer = Instant::now();
let mut avg_latency = RollingAverageTime::new(20);
Expand Down Expand Up @@ -595,7 +596,7 @@ impl<'a, B: BlockchainBackend + 'static> HorizonStateSynchronization<'a, B> {
bitmap.run_optimize();

let pruned_output_set = output_mmr.get_pruned_hash_set()?;
let output_mmr = MutableMmr::<HashDigest, _>::new(pruned_output_set.clone(), bitmap.clone())?;
let output_mmr = MutableMmr::<Blake256, _>::new(pruned_output_set.clone(), bitmap.clone())?;

let mmr_root = output_mmr.get_merkle_root()?;
if mmr_root != current_header.header().output_mr {
Expand Down
7 changes: 4 additions & 3 deletions base_layer/core/src/blocks/block_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ use serde::{
};
use tari_common_types::{
array::{copy_into_fixed_array, copy_into_fixed_array_lossy},
types::{BlindingFactor, BlockHash, HashDigest, BLOCK_HASH_LENGTH},
types::{BlindingFactor, BlockHash, BLOCK_HASH_LENGTH},
};
use tari_crypto::hash::blake2::Blake256;
use tari_utilities::{epoch_time::EpochTime, hex::Hex, ByteArray, Hashable};
use thiserror::Error;

Expand Down Expand Up @@ -219,7 +220,7 @@ impl BlockHeader {
pub fn merged_mining_hash(&self) -> Vec<u8> {
if self.version <= 2 {
// TODO: Remove deprecated header hashing #testnetreset
HashDigest::new()
Blake256::new()
.chain(self.version.to_le_bytes())
.chain(self.height.to_le_bytes())
.chain(self.prev_hash.as_bytes())
Expand Down Expand Up @@ -295,7 +296,7 @@ impl From<NewBlockHeaderTemplate> for BlockHeader {
impl Hashable for BlockHeader {
fn hash(&self) -> Vec<u8> {
if self.version <= 2 {
HashDigest::new()
Blake256::new()
.chain(self.merged_mining_hash())
.chain(self.pow.to_bytes())
.chain(self.nonce.to_le_bytes())
Expand Down
17 changes: 9 additions & 8 deletions base_layer/core/src/blocks/genesis_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,17 +192,17 @@ pub fn get_dibbler_genesis_block() -> ChainBlock {
// NB: `dibbler_genesis_sanity_check` must pass

// use croaring::Bitmap;
// use tari_common_types::types::HashDigest;
// use tari_mmr::{MerkleMountainRange, MutableMmr};
// use tari_crypto::hash::blake2::Blake256;
//
// let mut kernel_mmr = MerkleMountainRange::<HashDigest, _>::new(Vec::new());
// let mut kernel_mmr = MerkleMountainRange::<Blake256, _>::new(Vec::new());
// for k in block.body.kernels() {
// println!("k: {}", k);
// kernel_mmr.push(k.hash()).unwrap();
// }
//
// let mut witness_mmr = MerkleMountainRange::<HashDigest, _>::new(Vec::new());
// let mut output_mmr = MutableMmr::<HashDigest, _>::new(Vec::new(), Bitmap::create()).unwrap();
// let mut witness_mmr = MerkleMountainRange::<Blake256, _>::new(Vec::new());
// let mut output_mmr = MutableMmr::<Blake256, _>::new(Vec::new(), Bitmap::create()).unwrap();
//
// for o in block.body.outputs() {
// witness_mmr.push(o.witness_hash()).unwrap();
Expand Down Expand Up @@ -316,7 +316,8 @@ fn get_dibbler_genesis_block_raw() -> Block {
#[cfg(test)]
mod test {
use croaring::Bitmap;
use tari_common_types::types::{Commitment, HashDigest};
use tari_common_types::types::Commitment;
use tari_crypto::hash::blake2::Blake256;
use tari_mmr::{MerkleMountainRange, MutableMmr};

use super::*;
Expand Down Expand Up @@ -360,13 +361,13 @@ mod test {
.any(|k| k.features.contains(KernelFeatures::COINBASE_KERNEL)));

// Check MMR
let mut kernel_mmr = MerkleMountainRange::<HashDigest, _>::new(Vec::new());
let mut kernel_mmr = MerkleMountainRange::<Blake256, _>::new(Vec::new());
for k in block.block().body.kernels() {
kernel_mmr.push(k.hash()).unwrap();
}

let mut witness_mmr = MerkleMountainRange::<HashDigest, _>::new(Vec::new());
let mut output_mmr = MutableMmr::<HashDigest, _>::new(Vec::new(), Bitmap::create()).unwrap();
let mut witness_mmr = MerkleMountainRange::<Blake256, _>::new(Vec::new());
let mut output_mmr = MutableMmr::<Blake256, _>::new(Vec::new(), Bitmap::create()).unwrap();

for o in block.block().body.outputs() {
witness_mmr.push(o.witness_hash()).unwrap();
Expand Down
11 changes: 6 additions & 5 deletions base_layer/core/src/chain_storage/blockchain_database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ use log::*;
use serde::{Deserialize, Serialize};
use tari_common_types::{
chain_metadata::ChainMetadata,
types::{BlockHash, Commitment, FixedHash, HashDigest, HashOutput, PublicKey, Signature},
types::{BlockHash, Commitment, FixedHash, HashOutput, PublicKey, Signature},
};
use tari_crypto::hash::blake2::Blake256;
use tari_mmr::{pruned_hashset::PrunedHashSet, MerkleMountainRange, MutableMmr};
use tari_utilities::{epoch_time::EpochTime, hex::Hex, ByteArray, Hashable};

Expand Down Expand Up @@ -1253,10 +1254,10 @@ pub fn calculate_mmr_roots<T: BlockchainBackend>(db: &T, block: &Block) -> Resul
value: header.prev_hash.to_hex(),
})?;

let mut kernel_mmr = MerkleMountainRange::<HashDigest, _>::new(kernels);
let mut output_mmr = MutableMmr::<HashDigest, _>::new(outputs, deleted)?;
let mut witness_mmr = MerkleMountainRange::<HashDigest, _>::new(range_proofs);
let mut input_mmr = MerkleMountainRange::<HashDigest, _>::new(PrunedHashSet::default());
let mut kernel_mmr = MerkleMountainRange::<Blake256, _>::new(kernels);
let mut output_mmr = MutableMmr::<Blake256, _>::new(outputs, deleted)?;
let mut witness_mmr = MerkleMountainRange::<Blake256, _>::new(range_proofs);
let mut input_mmr = MerkleMountainRange::<Blake256, _>::new(PrunedHashSet::default());

for kernel in body.kernels().iter() {
kernel_mmr.push(kernel.hash())?;
Expand Down
8 changes: 4 additions & 4 deletions base_layer/core/src/chain_storage/lmdb_db/contract_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,16 +538,16 @@ impl Display for ContractIndexKey {

#[cfg(test)]
mod tests {
use digest::Digest;
use tari_common_types::types::HashDigest;

use super::*;
mod contract_index_key {
use blake2::Digest;
use tari_crypto::hash::blake2::Blake256;

use super::*;

#[test]
fn it_represents_a_well_formed_contract_index_key() {
let hash = HashDigest::new().chain(b"foobar").finalize().into();
let hash = Blake256::new().chain(b"foobar").finalize().into();
let key = ContractIndexKey::new(hash, OutputType::ContractCheckpoint);
assert_eq!(key.as_lmdb_bytes()[0], KeyType::PerContract as u8);
assert_eq!(key.as_lmdb_bytes()[1..33], *hash.as_slice());
Expand Down
11 changes: 6 additions & 5 deletions base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ use log::*;
use serde::{Deserialize, Serialize};
use tari_common_types::{
chain_metadata::ChainMetadata,
types::{BlockHash, Commitment, FixedHash, HashDigest, HashOutput, PublicKey, Signature, BLOCK_HASH_LENGTH},
types::{BlockHash, Commitment, FixedHash, HashOutput, PublicKey, Signature, BLOCK_HASH_LENGTH},
};
use tari_crypto::hash::blake2::Blake256;
use tari_mmr::{Hash, MerkleMountainRange, MutableMmr};
use tari_storage::lmdb_store::{db, LMDBBuilder, LMDBConfig, LMDBStore};
use tari_utilities::{
Expand Down Expand Up @@ -1281,7 +1282,7 @@ impl LMDBDatabase {
..
} = data;

let mut kernel_mmr = MerkleMountainRange::<HashDigest, _>::new(pruned_kernel_set);
let mut kernel_mmr = MerkleMountainRange::<Blake256, _>::new(pruned_kernel_set);

for kernel in kernels {
total_kernel_sum = &total_kernel_sum + &kernel.excess;
Expand All @@ -1296,8 +1297,8 @@ impl LMDBDatabase {
})?;
self.insert_kernel(txn, &block_hash, &kernel, pos)?;
}
let mut output_mmr = MutableMmr::<HashDigest, _>::new(pruned_output_set, Bitmap::create())?;
let mut witness_mmr = MerkleMountainRange::<HashDigest, _>::new(pruned_proof_set);
let mut output_mmr = MutableMmr::<Blake256, _>::new(pruned_output_set, Bitmap::create())?;
let mut witness_mmr = MerkleMountainRange::<Blake256, _>::new(pruned_proof_set);

let leaf_count = witness_mmr.get_leaf_count()?;

Expand Down Expand Up @@ -2729,7 +2730,7 @@ impl UniqueIdIndexKey {
/// `parent_public_key` - the parent asset public key to which the token is assigned
/// `unique_id` - a series of bytes representing the token uniquely for the asset
pub fn new(parent_public_key: Option<&PublicKey>, unique_id: &[u8]) -> Self {
let unique_id_hash = HashDigest::default().chain(unique_id).finalize();
let unique_id_hash = Blake256::default().chain(unique_id).finalize();
Self::from_raw_parts(
parent_public_key.map(|p| p.as_bytes()).unwrap_or(&[0; 32][..]),
&unique_id_hash,
Expand Down
12 changes: 7 additions & 5 deletions base_layer/core/src/consensus/consensus_encoding/hashing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
use std::{io, io::Write, marker::PhantomData};

use digest::{consts::U32, Digest};
use tari_common_types::types::HashDigest;
use tari_crypto::hashing::{DomainSeparatedHasher, DomainSeparation};
use tari_crypto::{
hash::blake2::Blake256,
hashing::{DomainSeparatedHasher, DomainSeparation},
};

use crate::consensus::ConsensusEncoding;

Expand All @@ -33,7 +35,7 @@ pub struct DomainSeparatedConsensusHasher<M: DomainSeparation>(PhantomData<M>);

impl<M: DomainSeparation> DomainSeparatedConsensusHasher<M> {
#[allow(clippy::new_ret_no_self)]
pub fn new(label: &'static str) -> ConsensusHasher<DomainSeparatedHasher<HashDigest, M>> {
pub fn new(label: &'static str) -> ConsensusHasher<DomainSeparatedHasher<Blake256, M>> {
ConsensusHasher::new(DomainSeparatedHasher::new_with_label(label))
}
}
Expand Down Expand Up @@ -70,9 +72,9 @@ where D: Digest<OutputSize = U32>
}
}

impl Default for ConsensusHasher<HashDigest> {
impl Default for ConsensusHasher<Blake256> {
fn default() -> Self {
ConsensusHasher::new(HashDigest::new())
ConsensusHasher::new(Blake256::new())
}
}

Expand Down
8 changes: 4 additions & 4 deletions base_layer/core/src/covenants/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use std::{

use digest::Digest;
use integer_encoding::VarIntWriter;
use tari_common_types::types::HashDigest;
use tari_crypto::hash::blake2::Blake256;

use crate::{
consensus::ToConsensusBytes,
Expand Down Expand Up @@ -367,8 +367,8 @@ impl OutputFields {
self.fields.is_empty()
}

pub fn construct_challenge_from(&self, output: &TransactionOutput) -> HashDigest {
let mut challenge = HashDigest::new();
pub fn construct_challenge_from(&self, output: &TransactionOutput) -> Blake256 {
let mut challenge = Blake256::new();
for field in &self.fields {
challenge.update(field.get_field_value_bytes(output));
}
Expand Down Expand Up @@ -596,7 +596,7 @@ mod test {
output.features.consensus_encode(&mut challenge).unwrap();
output.commitment.consensus_encode(&mut challenge).unwrap();
output.script.consensus_encode(&mut challenge).unwrap();
let expected_hash = HashDigest::new().chain(&challenge).finalize();
let expected_hash = Blake256::new().chain(&challenge).finalize();
assert_eq!(hash, expected_hash);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ use std::{
use digest::Digest;
use log::*;
use serde::{Deserialize, Serialize};
use tari_common_types::types::{HashDigest, HashOutput, PrivateKey, PublicKey, Signature};
use tari_common_types::types::{HashOutput, PrivateKey, PublicKey, Signature};
use tari_crypto::hash::blake2::Blake256;
use tari_utilities::{hex::Hex, ByteArray, Hashable};

use crate::{
Expand Down Expand Up @@ -659,7 +660,7 @@ fn get_output_token_id(output: &TransactionOutput) -> Option<[u8; 32]> {
.as_ref()
.map(|pk| pk.as_bytes())
.unwrap_or_else(|| root_pk.as_bytes());
HashDigest::new()
Blake256::new()
.chain(parent_pk_bytes)
.chain(unique_id)
.finalize()
Expand All @@ -671,7 +672,6 @@ fn get_output_token_id(output: &TransactionOutput) -> Option<[u8; 32]> {
mod test {
use rand::rngs::OsRng;
use tari_common::configuration::Network;
use tari_common_types::types::HashDigest;
use tari_crypto::keys::PublicKey as PublicKeyTrait;

use super::*;
Expand Down Expand Up @@ -788,7 +788,7 @@ mod test {
.unwrap();

let factories = CryptoFactories::default();
let mut stx_protocol = stx_builder.build::<HashDigest>(&factories, None, u64::MAX).unwrap();
let mut stx_protocol = stx_builder.build::<Blake256>(&factories, None, u64::MAX).unwrap();
stx_protocol
.finalize(KernelFeatures::empty(), &factories, None, u64::MAX)
.unwrap();
Expand Down Expand Up @@ -1029,7 +1029,7 @@ mod test {
unconfirmed_pool
.insert_many(vec![tx1.clone(), tx2.clone(), tx3.clone(), tx4.clone()], &tx_weight)
.unwrap();
let expected_hash: [u8; 32] = HashDigest::new()
let expected_hash: [u8; 32] = Blake256::new()
.chain(parent_pk.as_bytes())
.chain(&unique_id)
.finalize()
Expand Down
2 changes: 1 addition & 1 deletion base_layer/core/src/proto/types.proto
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ syntax = "proto3";

package tari.types;

// Define the data type that is used to store results of `HashDigest`
// Define the data type that is used to store results of `Blake256`
message HashOutput {
bytes data = 1;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use digest::Digest;
use tari_common_types::types::{Commitment, FixedHash, HashDigest};
use tari_common_types::types::{Commitment, FixedHash};
use tari_crypto::hash::blake2::Blake256;
use tari_utilities::ByteArray;

#[derive(Debug, Clone, Copy)]
Expand All @@ -30,7 +31,7 @@ pub struct ContractAcceptanceChallenge(FixedHash);
impl ContractAcceptanceChallenge {
pub fn new(constiution_commitment: &Commitment, contract_id: &FixedHash) -> Self {
// TODO: Use new tari_crypto domain-separated hashing
let hash = HashDigest::new()
let hash = Blake256::new()
.chain(constiution_commitment.as_bytes())
.chain(contract_id.as_slice())
.finalize()
Expand Down
Loading