Skip to content

Commit

Permalink
feat!: add hashing API use to base layer (see issue #4394) (#4447)
Browse files Browse the repository at this point in the history
Description
--- 
Refactor base_layer repo to use the hashing API.

Motivation and Context
--- 
Fixes #4394.

How Has This Been Tested?
--- 
Unit tests
  • Loading branch information
jorgeantonio21 committed Aug 19, 2022
1 parent 30dd70e commit f9af875
Show file tree
Hide file tree
Showing 19 changed files with 161 additions and 84 deletions.
9 changes: 6 additions & 3 deletions base_layer/common_types/src/types/bullet_rangeproofs.rs
Expand Up @@ -22,7 +22,6 @@

use std::fmt;

use digest::Digest;
use serde::{
de::{self, Visitor},
Deserialize,
Expand All @@ -32,14 +31,18 @@ use serde::{
};
use tari_utilities::{hex::*, ByteArray, ByteArrayError, Hashable};

use crate::types::Blake256;
use super::BulletRangeProofHasherBlake256;

#[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> {
Blake256::new().chain(&self.0).finalize().to_vec()
BulletRangeProofHasherBlake256::new()
.chain(&self.0)
.finalize()
.as_ref()
.to_vec()
}
}

Expand Down
9 changes: 9 additions & 0 deletions base_layer/common_types/src/types/mod.rs
Expand Up @@ -78,3 +78,12 @@ pub type RangeProofService = BulletproofsPlusService;

/// Specify the range proof
pub type RangeProof = BulletRangeProof;

use tari_crypto::{hash_domain, hashing::DomainSeparatedHasher};

hash_domain!(
BulletRangeProofHashDomain,
"com.tari.tari-project.base_layer.common_types.bullet_rangeproofs"
);

pub type BulletRangeProofHasherBlake256 = DomainSeparatedHasher<Blake256, BulletRangeProofHashDomain>;
7 changes: 7 additions & 0 deletions base_layer/core/src/chain_storage/lmdb_db/mod.rs
Expand Up @@ -23,6 +23,7 @@
pub use lmdb_db::{create_lmdb_database, create_recovery_lmdb_database, LMDBDatabase};
use serde::{Deserialize, Serialize};
use tari_common_types::types::HashOutput;
use tari_crypto::hash_domain;

use crate::transactions::transaction_components::{TransactionInput, TransactionKernel, TransactionOutput};

Expand Down Expand Up @@ -71,3 +72,9 @@ pub(crate) struct TransactionKernelRowData {
pub mmr_position: u32,
pub hash: HashOutput,
}

hash_domain!(
CoreChainStorageHashDomain,
"com.tari.tari-project.base_layer.core.lmdb_db",
1
);
26 changes: 17 additions & 9 deletions base_layer/core/src/covenants/fields.rs
Expand Up @@ -29,8 +29,9 @@ use std::{

use digest::Digest;
use integer_encoding::VarIntWriter;
use tari_crypto::hash::blake2::Blake256;
use tari_crypto::{hash::blake2::Blake256, hashing::DomainSeparation};

use super::{BaseLayerCovenantsDomain, COVENANTS_FIELD_HASHER_LABEL};
use crate::{
consensus::ToConsensusBytes,
covenants::{
Expand Down Expand Up @@ -307,8 +308,9 @@ impl OutputFields {

pub fn construct_challenge_from(&self, output: &TransactionOutput) -> Blake256 {
let mut challenge = Blake256::new();
BaseLayerCovenantsDomain::add_domain_separation_tag(&mut challenge, COVENANTS_FIELD_HASHER_LABEL);
for field in &self.fields {
challenge.update(field.get_field_value_bytes(output));
challenge.update(&field.get_field_value_bytes(output).as_slice());
}
challenge
}
Expand Down Expand Up @@ -338,7 +340,6 @@ mod test {

use super::*;
use crate::{
consensus::ConsensusEncoding,
covenant,
covenants::test::{create_input, create_outputs},
transactions::{
Expand Down Expand Up @@ -487,6 +488,9 @@ mod test {
use super::*;

mod construct_challenge_from {
use blake2::Digest;
use tari_crypto::hashing::DomainSeparation;

use super::*;

#[test]
Expand All @@ -508,12 +512,16 @@ mod test {
fields.push(OutputField::Commitment);
fields.push(OutputField::Script);
let hash = fields.construct_challenge_from(&output).finalize();

let mut challenge = Vec::new();
output.features.consensus_encode(&mut challenge).unwrap();
output.commitment.consensus_encode(&mut challenge).unwrap();
output.script.consensus_encode(&mut challenge).unwrap();
let expected_hash = Blake256::new().chain(&challenge).finalize();
let hash = hash.to_vec();

let mut hasher = Blake256::new();
BaseLayerCovenantsDomain::add_domain_separation_tag(&mut hasher, COVENANTS_FIELD_HASHER_LABEL);
let expected_hash = hasher
.chain(output.features.to_consensus_bytes())
.chain(output.commitment.to_consensus_bytes())
.chain(output.script.to_consensus_bytes())
.finalize()
.to_vec();
assert_eq!(hash, expected_hash);
}
}
Expand Down
19 changes: 12 additions & 7 deletions base_layer/core/src/covenants/filters/fields_hashed_eq.rs
Expand Up @@ -23,7 +23,6 @@
use digest::Digest;

use crate::covenants::{context::CovenantContext, error::CovenantError, filters::Filter, output_set::OutputSet};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldsHashedEqFilter;

Expand All @@ -32,8 +31,8 @@ impl Filter for FieldsHashedEqFilter {
let fields = context.next_arg()?.require_outputfields()?;
let hash = context.next_arg()?.require_hash()?;
output_set.retain(|output| {
let challenge = fields.construct_challenge_from(output);
Ok(challenge.finalize()[..] == *hash)
let challenge = fields.construct_challenge_from(output).finalize();
Ok(challenge[..] == *hash)
})?;
Ok(())
}
Expand All @@ -42,12 +41,18 @@ impl Filter for FieldsHashedEqFilter {
#[cfg(test)]
mod test {
use tari_common_types::types::Challenge;
use tari_crypto::hashing::DomainSeparation;

use super::*;
use crate::{
consensus::ToConsensusBytes,
covenant,
covenants::{filters::test::setup_filter_test, test::create_input},
covenants::{
filters::test::setup_filter_test,
test::create_input,
BaseLayerCovenantsDomain,
COVENANTS_FIELD_HASHER_LABEL,
},
transactions::transaction_components::{OutputFeatures, SideChainFeatures},
};

Expand All @@ -58,9 +63,9 @@ mod test {
sidechain_features: Some(Box::new(SideChainFeatures {})),
..Default::default()
};
let hashed = Challenge::new().chain(features.to_consensus_bytes()).finalize();
let mut hash = [0u8; 32];
hash.copy_from_slice(hashed.as_slice());
let mut hasher = Challenge::new();
BaseLayerCovenantsDomain::add_domain_separation_tag(&mut hasher, COVENANTS_FIELD_HASHER_LABEL);
let hash = hasher.chain(&features.to_consensus_bytes()).finalize();
let covenant = covenant!(fields_hashed_eq(@fields(@field::features), @hash(hash.into())));
let input = create_input();
let (mut context, outputs) = setup_filter_test(&covenant, &input, 0, |outputs| {
Expand Down
10 changes: 10 additions & 0 deletions base_layer/core/src/covenants/mod.rs
Expand Up @@ -51,3 +51,13 @@ mod macros;

#[cfg(test)]
mod test;

use tari_crypto::hash_domain;

hash_domain!(
BaseLayerCovenantsDomain,
"com.tari.tari-project.base_layer.covenants",
1
);

pub(crate) const COVENANTS_FIELD_HASHER_LABEL: &str = "fields";
7 changes: 7 additions & 0 deletions base_layer/core/src/mempool/unconfirmed_pool/mod.rs
Expand Up @@ -26,4 +26,11 @@ mod unconfirmed_pool;

// Public re-exports
pub use error::UnconfirmedPoolError;
use tari_crypto::hash_domain;
pub use unconfirmed_pool::{UnconfirmedPool, UnconfirmedPoolConfig};

hash_domain!(
UnconfirmedPoolOutputTokenIdHashDomain,
"com.tari.tari-project.base_layer.core.mempool.unconfirmed_pool_output_token_id",
1
);
Expand Up @@ -40,7 +40,6 @@ use crate::{
},
transactions::{tari_amount::MicroTari, transaction_components::Transaction, weight::TransactionWeight},
};

pub const LOG_TARGET: &str = "c::mp::unconfirmed_pool::unconfirmed_pool_storage";

type TransactionKey = usize;
Expand Down Expand Up @@ -619,7 +618,6 @@ impl UnconfirmedPool {
#[cfg(test)]
mod test {
use tari_common::configuration::Network;
use tari_crypto::hash::blake2::Blake256;

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

let factories = CryptoFactories::default();
let mut stx_protocol = stx_builder.build::<Blake256>(&factories, None, u64::MAX).unwrap();
let mut stx_protocol = stx_builder.build(&factories, None, u64::MAX).unwrap();
stx_protocol.finalize(&factories, None, u64::MAX).unwrap();

let tx3 = stx_protocol.get_transaction().unwrap().clone();
Expand Down
5 changes: 2 additions & 3 deletions base_layer/core/src/transactions/test_helpers.rs
Expand Up @@ -27,7 +27,6 @@ use tari_common::configuration::Network;
use tari_common_types::types::{Commitment, CommitmentFactory, PrivateKey, PublicKey, Signature};
use tari_crypto::{
commitment::HomomorphicCommitmentFactory,
hash::blake2::Blake256,
keys::{PublicKey as PK, SecretKey},
range_proof::RangeProofService,
};
Expand Down Expand Up @@ -613,7 +612,7 @@ pub fn create_sender_transaction_protocol_with(
stx_builder.with_output(utxo, script_offset_pvt_key).unwrap();
});

let mut stx_protocol = stx_builder.build::<Blake256>(&factories, None, u64::MAX).unwrap();
let mut stx_protocol = stx_builder.build(&factories, None, u64::MAX).unwrap();
stx_protocol.finalize(&factories, None, u64::MAX)?;

Ok(stx_protocol)
Expand Down Expand Up @@ -704,7 +703,7 @@ pub fn create_stx_protocol(schema: TransactionSchema) -> (SenderTransactionProto
.unwrap();
}

let stx_protocol = stx_builder.build::<Blake256>(&factories, None, u64::MAX).unwrap();
let stx_protocol = stx_builder.build(&factories, None, u64::MAX).unwrap();
let change = stx_protocol.get_change_amount().unwrap();
// The change output is assigned its own random script offset private key
let change_sender_offset_public_key = stx_protocol.get_change_sender_offset_public_key().unwrap().unwrap();
Expand Down
Expand Up @@ -29,3 +29,21 @@ pub type FixedString = [u8; FIXED_STR_LEN];
pub fn bytes_into_fixed_string<T: AsRef<[u8]>>(value: T) -> FixedString {
tari_common_types::array::copy_into_fixed_array_lossy::<_, FIXED_STR_LEN>(value.as_ref())
}

use tari_crypto::{hash::blake2::Blake256, hash_domain, hashing::DomainSeparatedHasher};

hash_domain!(
ContractAcceptanceHashDomain,
"com.tari.tari-project.base_layer.core.transactions.side_chain.contract_acceptance_challenge",
1
);

pub type ContractAcceptanceHasherBlake256 = DomainSeparatedHasher<Blake256, ContractAcceptanceHashDomain>;

hash_domain!(
SignerSignatureHashDomain,
"com.tari.tari-project.base_layer.core.transactions.side_chain.signer_signature",
1
);

pub type SignerSignatureHasherBlake256 = DomainSeparatedHasher<Blake256, SignerSignatureHashDomain>;
22 changes: 17 additions & 5 deletions base_layer/core/src/transactions/transaction_components/test.rs
Expand Up @@ -20,10 +20,8 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use digest::Digest;
use rand::{self, rngs::OsRng};
use tari_common_types::types::{BlindingFactor, ComSignature, CommitmentFactory, PrivateKey, PublicKey, Signature};
use tari_comms::types::CommsChallenge;
use tari_crypto::{
commitment::HomomorphicCommitmentFactory,
errors::RangeProofError,
Expand Down Expand Up @@ -539,8 +537,15 @@ mod output_features {

mod validate_internal_consistency {

use digest::Digest;
use tari_common_types::types::FixedHash;
use tari_crypto::{hash::blake2::Blake256, hashing::DomainSeparation};

use super::*;
use crate::consensus::ToConsensusBytes;
use crate::{
consensus::ToConsensusBytes,
covenants::{BaseLayerCovenantsDomain, COVENANTS_FIELD_HASHER_LABEL},
};

fn test_case(
input_params: &UtxoTestParams,
Expand Down Expand Up @@ -589,9 +594,16 @@ mod validate_internal_consistency {
.unwrap();

//---------------------------------- Case2 - PASS --------------------------------------------//
let hash = CommsChallenge::new().chain(features.to_consensus_bytes()).finalize();
let mut hasher = Blake256::new();
BaseLayerCovenantsDomain::add_domain_separation_tag(&mut hasher, COVENANTS_FIELD_HASHER_LABEL);

let hash = hasher.chain(features.to_consensus_bytes()).finalize().to_vec();

let mut slice = [0u8; FixedHash::byte_size()];
slice.copy_from_slice(hash.as_ref());
let hash = FixedHash::from(slice);

let covenant = covenant!(fields_hashed_eq(@fields(@field::features), @hash(hash.into())));
let covenant = covenant!(fields_hashed_eq(@fields(@field::features), @hash(hash)));

test_case(
&UtxoTestParams {
Expand Down
13 changes: 12 additions & 1 deletion base_layer/core/src/transactions/transaction_protocol/mod.rs
Expand Up @@ -88,7 +88,7 @@
use derivative::Derivative;
use serde::{Deserialize, Serialize};
use tari_common_types::types::PrivateKey;
use tari_crypto::{errors::RangeProofError, signatures::SchnorrSignatureError};
use tari_crypto::{errors::RangeProofError, hash::blake2::Blake256, signatures::SchnorrSignatureError};
use thiserror::Error;

use crate::transactions::{tari_amount::*, transaction_components::TransactionError};
Expand All @@ -99,6 +99,7 @@ pub mod sender;
pub mod single_receiver;
pub mod transaction_initializer;
use tari_common_types::types::Commitment;
use tari_crypto::{hash_domain, hashing::DomainSeparatedHasher};

use crate::transactions::transaction_components::KernelFeatures;

Expand Down Expand Up @@ -176,3 +177,13 @@ pub struct RewindData {
pub rewind_blinding_key: PrivateKey,
pub encryption_key: PrivateKey,
}

// hash domain
hash_domain!(
CalculateTxIdTransactionProtocolHashDomain,
"com.tari.tari-project.base_layer.core.transactions.transaction_protocol.calculate_tx_id",
1
);

pub type CalculateTxIdTransactionProtocolHasherBlake256 =
DomainSeparatedHasher<Blake256, CalculateTxIdTransactionProtocolHashDomain>;

0 comments on commit f9af875

Please sign in to comment.