From 000d939a2c8fcb1d0fa229acb2ca3c21dfa037e3 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Wed, 3 Aug 2022 12:36:25 +0100 Subject: [PATCH 01/38] clear pending coinbase transactions now rely on utxo hashes --- base_layer/core/src/transactions/coinbase_builder.rs | 2 +- .../wallet/src/output_manager_service/service.rs | 4 ++-- .../output_manager_service/storage/database/backend.rs | 4 ++-- .../src/output_manager_service/storage/database/mod.rs | 6 +++--- .../output_manager_service/storage/sqlite_db/mod.rs | 8 ++++---- .../storage/sqlite_db/output_sql.rs | 10 ++++++++++ 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/base_layer/core/src/transactions/coinbase_builder.rs b/base_layer/core/src/transactions/coinbase_builder.rs index 6363831374..ecdce58e26 100644 --- a/base_layer/core/src/transactions/coinbase_builder.rs +++ b/base_layer/core/src/transactions/coinbase_builder.rs @@ -203,7 +203,7 @@ impl CoinbaseBuilder { let sig = Signature::sign(spending_key.clone(), nonce, &challenge) .map_err(|_| CoinbaseBuildError::BuildError("Challenge could not be represented as a scalar".into()))?; - let sender_offset_private_key = PrivateKey::random(&mut OsRng); + let sender_offset_private_key = PrivateKey::from_bytes(Blake256::digest(spending_key)); // H(spending_key) <- Blake256 let sender_offset_public_key = PublicKey::from_secret_key(&sender_offset_private_key); let covenant = self.covenant; diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index cc16d39468..c50c7da0aa 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -1012,12 +1012,12 @@ where match self .resources .db - .clear_pending_coinbase_transaction_at_block_height(block_height) + .clear_pending_coinbase_transaction_with_hash(output.hash.as_slice()) { Ok(_) => { debug!( target: LOG_TARGET, - "An existing pending coinbase was cleared for block height {}", block_height + "An existing pending coinbase was cleared with hash {}", output.hash.to_hex() ) }, Err(e) => match e { diff --git a/base_layer/wallet/src/output_manager_service/storage/database/backend.rs b/base_layer/wallet/src/output_manager_service/storage/database/backend.rs index 4527e1b561..e3a7cad923 100644 --- a/base_layer/wallet/src/output_manager_service/storage/database/backend.rs +++ b/base_layer/wallet/src/output_manager_service/storage/database/backend.rs @@ -97,9 +97,9 @@ pub trait OutputManagerBackend: Send + Sync + Clone { /// Get the output that was most recently spent, ordered descending by mined height fn get_last_spent_output(&self) -> Result, OutputManagerStorageError>; /// Check if there is a pending coinbase transaction at this block height, if there is clear it. - fn clear_pending_coinbase_transaction_at_block_height( + fn clear_pending_coinbase_transaction_with_hash( &self, - block_height: u64, + hash: &[u8], ) -> Result<(), OutputManagerStorageError>; /// Set if a coinbase output is abandoned or not fn set_coinbase_abandoned(&self, tx_id: TxId, abandoned: bool) -> Result<(), OutputManagerStorageError>; diff --git a/base_layer/wallet/src/output_manager_service/storage/database/mod.rs b/base_layer/wallet/src/output_manager_service/storage/database/mod.rs index 91c15e1bbb..d5af1bcbae 100644 --- a/base_layer/wallet/src/output_manager_service/storage/database/mod.rs +++ b/base_layer/wallet/src/output_manager_service/storage/database/mod.rs @@ -220,11 +220,11 @@ where T: OutputManagerBackend + 'static } /// Check if there is a pending coinbase transaction at this block height, if there is clear it. - pub fn clear_pending_coinbase_transaction_at_block_height( + pub fn clear_pending_coinbase_transaction_with_hash( &self, - block_height: u64, + hash: &[u8], ) -> Result<(), OutputManagerStorageError> { - self.db.clear_pending_coinbase_transaction_at_block_height(block_height) + self.db.clear_pending_coinbase_transaction_with_hash(hash) } pub fn fetch_all_unspent_outputs(&self) -> Result, OutputManagerStorageError> { diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs index 09fdafe15d..f2d0a21e03 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs @@ -1074,21 +1074,21 @@ impl OutputManagerBackend for OutputManagerSqliteDatabase { Ok(()) } - fn clear_pending_coinbase_transaction_at_block_height( + fn clear_pending_coinbase_transaction_with_hash( &self, - block_height: u64, + hash: &[u8], ) -> Result<(), OutputManagerStorageError> { let start = Instant::now(); let conn = self.database_connection.get_pooled_connection()?; let acquire_lock = start.elapsed(); - let output = OutputSql::find_pending_coinbase_at_block_height(block_height, &conn)?; + let output = OutputSql::find_pending_coinbase_with_hash(hash, &conn)?; output.delete(&conn)?; if start.elapsed().as_millis() > 0 { trace!( target: LOG_TARGET, - "sqlite profile - clear_pending_coinbase_transaction_at_block_height: lock {} + db_op {} = {} ms", + "sqlite profile - clear_pending_coinbase_transaction_with_hash: lock {} + db_op {} = {} ms", acquire_lock.as_millis(), (start.elapsed() - acquire_lock).as_millis(), start.elapsed().as_millis() diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs index 63480ee86c..804681ab59 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs @@ -576,6 +576,16 @@ impl OutputSql { .first::(conn)?) } + pub fn find_pending_coinbase_with_hash( + hash: &[u8], + conn: &SqliteConnection, + ) -> Result { + Ok(outputs::table + .filter(outputs::status.ne(OutputStatus::Unspent as i32)) + .filter(outputs::hash.eq(Some(hash))) + .first::(conn)?) + } + /// Find a particular Output, if it exists and is in the specified Spent state pub fn find_pending_coinbase_at_block_height( block_height: u64, From aa225a474a69c0cf0ad02f203c1de853063742b2 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Mon, 8 Aug 2022 12:15:51 +0100 Subject: [PATCH 02/38] sync with dev --- base_layer/core/src/transactions/coinbase_builder.rs | 2 +- .../wallet/src/output_manager_service/service.rs | 4 ++-- .../output_manager_service/storage/database/backend.rs | 4 ++-- .../src/output_manager_service/storage/database/mod.rs | 6 +++--- .../output_manager_service/storage/sqlite_db/mod.rs | 8 ++++---- .../storage/sqlite_db/output_sql.rs | 10 ---------- 6 files changed, 12 insertions(+), 22 deletions(-) diff --git a/base_layer/core/src/transactions/coinbase_builder.rs b/base_layer/core/src/transactions/coinbase_builder.rs index 5b984352cf..0b55b78e6d 100644 --- a/base_layer/core/src/transactions/coinbase_builder.rs +++ b/base_layer/core/src/transactions/coinbase_builder.rs @@ -205,7 +205,7 @@ impl CoinbaseBuilder { let sig = Signature::sign(spending_key.clone(), nonce, &challenge) .map_err(|_| CoinbaseBuildError::BuildError("Challenge could not be represented as a scalar".into()))?; - let sender_offset_private_key = PrivateKey::from_bytes(Blake256::digest(spending_key)); // H(spending_key) <- Blake256 + let sender_offset_private_key = PrivateKey::random(&mut OsRng); let sender_offset_public_key = PublicKey::from_secret_key(&sender_offset_private_key); let covenant = self.covenant; diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index 9e8395c57a..97bdfd64a3 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -1014,12 +1014,12 @@ where match self .resources .db - .clear_pending_coinbase_transaction_with_hash(output.hash.as_slice()) + .clear_pending_coinbase_transaction_at_block_height(block_height) { Ok(_) => { debug!( target: LOG_TARGET, - "An existing pending coinbase was cleared with hash {}", output.hash.to_hex() + "An existing pending coinbase was cleared for block height {}", block_height ) }, Err(e) => match e { diff --git a/base_layer/wallet/src/output_manager_service/storage/database/backend.rs b/base_layer/wallet/src/output_manager_service/storage/database/backend.rs index e3a7cad923..4527e1b561 100644 --- a/base_layer/wallet/src/output_manager_service/storage/database/backend.rs +++ b/base_layer/wallet/src/output_manager_service/storage/database/backend.rs @@ -97,9 +97,9 @@ pub trait OutputManagerBackend: Send + Sync + Clone { /// Get the output that was most recently spent, ordered descending by mined height fn get_last_spent_output(&self) -> Result, OutputManagerStorageError>; /// Check if there is a pending coinbase transaction at this block height, if there is clear it. - fn clear_pending_coinbase_transaction_with_hash( + fn clear_pending_coinbase_transaction_at_block_height( &self, - hash: &[u8], + block_height: u64, ) -> Result<(), OutputManagerStorageError>; /// Set if a coinbase output is abandoned or not fn set_coinbase_abandoned(&self, tx_id: TxId, abandoned: bool) -> Result<(), OutputManagerStorageError>; diff --git a/base_layer/wallet/src/output_manager_service/storage/database/mod.rs b/base_layer/wallet/src/output_manager_service/storage/database/mod.rs index d5af1bcbae..91c15e1bbb 100644 --- a/base_layer/wallet/src/output_manager_service/storage/database/mod.rs +++ b/base_layer/wallet/src/output_manager_service/storage/database/mod.rs @@ -220,11 +220,11 @@ where T: OutputManagerBackend + 'static } /// Check if there is a pending coinbase transaction at this block height, if there is clear it. - pub fn clear_pending_coinbase_transaction_with_hash( + pub fn clear_pending_coinbase_transaction_at_block_height( &self, - hash: &[u8], + block_height: u64, ) -> Result<(), OutputManagerStorageError> { - self.db.clear_pending_coinbase_transaction_with_hash(hash) + self.db.clear_pending_coinbase_transaction_at_block_height(block_height) } pub fn fetch_all_unspent_outputs(&self) -> Result, OutputManagerStorageError> { diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs index 9fab53d2d1..73af04cd9c 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs @@ -1074,21 +1074,21 @@ impl OutputManagerBackend for OutputManagerSqliteDatabase { Ok(()) } - fn clear_pending_coinbase_transaction_with_hash( + fn clear_pending_coinbase_transaction_at_block_height( &self, - hash: &[u8], + block_height: u64, ) -> Result<(), OutputManagerStorageError> { let start = Instant::now(); let conn = self.database_connection.get_pooled_connection()?; let acquire_lock = start.elapsed(); - let output = OutputSql::find_pending_coinbase_with_hash(hash, &conn)?; + let output = OutputSql::find_pending_coinbase_at_block_height(block_height, &conn)?; output.delete(&conn)?; if start.elapsed().as_millis() > 0 { trace!( target: LOG_TARGET, - "sqlite profile - clear_pending_coinbase_transaction_with_hash: lock {} + db_op {} = {} ms", + "sqlite profile - clear_pending_coinbase_transaction_at_block_height: lock {} + db_op {} = {} ms", acquire_lock.as_millis(), (start.elapsed() - acquire_lock).as_millis(), start.elapsed().as_millis() diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs index cfedab1288..8e6cbdd476 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/output_sql.rs @@ -576,16 +576,6 @@ impl OutputSql { .first::(conn)?) } - pub fn find_pending_coinbase_with_hash( - hash: &[u8], - conn: &SqliteConnection, - ) -> Result { - Ok(outputs::table - .filter(outputs::status.ne(OutputStatus::Unspent as i32)) - .filter(outputs::hash.eq(Some(hash))) - .first::(conn)?) - } - /// Find a particular Output, if it exists and is in the specified Spent state pub fn find_pending_coinbase_at_block_height( block_height: u64, From bfcc7ed66c0fbc2d71a7a5a987735c64fe5c9d3e Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Wed, 10 Aug 2022 09:52:31 +0100 Subject: [PATCH 03/38] add hashing api domain separation for base_layer/common_types --- .../common_types/src/types/bullet_rangeproofs.rs | 9 ++++++--- base_layer/common_types/src/types/mod.rs | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/base_layer/common_types/src/types/bullet_rangeproofs.rs b/base_layer/common_types/src/types/bullet_rangeproofs.rs index 7306878791..386217ce93 100644 --- a/base_layer/common_types/src/types/bullet_rangeproofs.rs +++ b/base_layer/common_types/src/types/bullet_rangeproofs.rs @@ -22,7 +22,6 @@ use std::fmt; -use digest::Digest; use serde::{ de::{self, Visitor}, Deserialize, @@ -32,14 +31,18 @@ use serde::{ }; use tari_utilities::{hex::*, ByteArray, ByteArrayError, Hashable}; -use crate::types::Blake256; +use super::{base_layer_common_types_domain_hasher, BULLET_RANGEPROOFS_HASHER_LABEL}; #[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct BulletRangeProof(pub Vec); /// Implement the hashing function for RangeProof for use in the MMR impl Hashable for BulletRangeProof { fn hash(&self) -> Vec { - Blake256::new().chain(&self.0).finalize().to_vec() + base_layer_common_types_domain_hasher(BULLET_RANGEPROOFS_HASHER_LABEL) + .chain(&self.0) + .finalize() + .as_ref() + .to_vec() } } diff --git a/base_layer/common_types/src/types/mod.rs b/base_layer/common_types/src/types/mod.rs index dd20bd9f73..52425f3708 100644 --- a/base_layer/common_types/src/types/mod.rs +++ b/base_layer/common_types/src/types/mod.rs @@ -78,3 +78,18 @@ pub type RangeProofService = BulletproofsPlusService; /// Specify the range proof pub type RangeProof = BulletRangeProof; + +use tari_crypto::{hash_domain, hashing::DomainSeparatedHasher}; + +pub(crate) const BULLET_RANGEPROOFS_HASHER_LABEL: &str = "bullet_rangeproofs.hasher"; + +hash_domain!( + BaseLayerCommonTypesDomain, + "com.tari.tari-project.base_layer.common_types" +); + +pub(crate) fn base_layer_common_types_domain_hasher( + label: &'static str, +) -> DomainSeparatedHasher { + DomainSeparatedHasher::::new_with_label(label) +} From 303cf64603c01dc067428fbb6d409d6223c2d5fb Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Thu, 11 Aug 2022 11:19:12 +0100 Subject: [PATCH 04/38] add hashing API to base layer --- .../core/src/chain_storage/lmdb_db/lmdb_db.rs | 8 +++-- .../core/src/chain_storage/lmdb_db/mod.rs | 15 ++++++++ base_layer/core/src/covenants/fields.rs | 35 ++++++++++++++----- .../src/covenants/filters/fields_hashed_eq.rs | 22 +++++++----- base_layer/core/src/covenants/mod.rs | 10 ++++++ base_layer/core/src/hashing.rs | 10 ++++++ .../core/src/mempool/unconfirmed_pool/mod.rs | 19 ++++++++++ .../unconfirmed_pool/unconfirmed_pool.rs | 21 ++++++----- .../contract_acceptance_challenge.rs | 15 ++++---- .../transaction_components/side_chain/mod.rs | 17 +++++++++ .../side_chain/signer_signature.rs | 15 ++++---- .../transaction_components/test.rs | 34 +++++++++++++----- .../transactions/transaction_protocol/mod.rs | 17 +++++++++ .../transaction_protocol/sender.rs | 5 +-- 14 files changed, 191 insertions(+), 52 deletions(-) create mode 100644 base_layer/core/src/hashing.rs diff --git a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs index 437a5e2073..3fddc17533 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs @@ -38,7 +38,6 @@ use std::{ time::Instant, }; -use blake2::Digest; use croaring::Bitmap; use fs2::FileExt; use lmdb_zero::{open, ConstTransaction, Database, Environment, ReadTransaction, WriteTransaction}; @@ -57,6 +56,7 @@ use tari_utilities::{ ByteArray, }; +use super::{base_layer_core_chain_storage_lmdb_hasher, LMDB_STORAGE_HASH_LABEL}; use crate::{ blocks::{ Block, @@ -2730,10 +2730,12 @@ 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 = Blake256::default().chain(unique_id).finalize(); + let unique_id_hash = base_layer_core_chain_storage_lmdb_hasher::(LMDB_STORAGE_HASH_LABEL) + .chain(unique_id) + .finalize(); Self::from_raw_parts( parent_public_key.map(|p| p.as_bytes()).unwrap_or(&[0; 32][..]), - &unique_id_hash, + unique_id_hash.as_ref(), // u64::MAX &[0xff; 8][..], ) diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index 5cd39d864a..c8a37aaf8d 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -20,9 +20,14 @@ // 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; 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, + hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, +}; use crate::transactions::transaction_components::{TransactionInput, TransactionKernel, TransactionOutput}; @@ -72,3 +77,13 @@ pub(crate) struct TransactionKernelRowData { pub mmr_position: u32, pub hash: HashOutput, } + +hash_domain!(BaseLayerCoreDomain, "com.tari.tari-project.base_layer.core"); + +pub(crate) const LMDB_STORAGE_HASH_LABEL: &str = "lmdb_db"; + +pub(crate) fn base_layer_core_chain_storage_lmdb_hasher( + label: &'static str, +) -> DomainSeparatedHasher { + DomainSeparatedHasher::::new_with_label(label) +} diff --git a/base_layer/core/src/covenants/fields.rs b/base_layer/core/src/covenants/fields.rs index bfac573fcc..238e05f315 100644 --- a/base_layer/core/src/covenants/fields.rs +++ b/base_layer/core/src/covenants/fields.rs @@ -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::{ @@ -369,8 +370,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 } @@ -402,7 +404,6 @@ mod test { use super::*; use crate::{ - consensus::ConsensusEncoding, covenant, covenants::test::{create_input, create_outputs}, transactions::{ @@ -570,6 +571,9 @@ mod test { use super::*; mod construct_challenge_from { + use blake2::Digest; + use tari_crypto::hashing::DomainSeparation; + use super::*; #[test] @@ -591,12 +595,25 @@ 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 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 = + // DomainSeparatedConsensusHasher::::new(COVENANTS_FIELD_HASHER_LABEL) + // .chain(&challenge) + // .finalize(); + + 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); } } diff --git a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs index f701525493..e933be7d8f 100644 --- a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs +++ b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs @@ -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; @@ -32,8 +31,9 @@ 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(); + let challenge = challenge.to_vec(); + Ok(challenge[..] == *hash) })?; Ok(()) } @@ -41,13 +41,19 @@ impl Filter for FieldsHashedEqFilter { #[cfg(test)] mod test { - use tari_common_types::types::{Challenge, FixedHash}; + use tari_common_types::types::FixedHash; + use tari_crypto::{hash::blake2::Blake256, 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}, }; @@ -58,9 +64,9 @@ mod test { sidechain_features: Some(Box::new(SideChainFeatures::new(FixedHash::hash_bytes("A")))), ..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 = Blake256::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| { diff --git a/base_layer/core/src/covenants/mod.rs b/base_layer/core/src/covenants/mod.rs index 74cf99b0af..1d75725495 100644 --- a/base_layer/core/src/covenants/mod.rs +++ b/base_layer/core/src/covenants/mod.rs @@ -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"; diff --git a/base_layer/core/src/hashing.rs b/base_layer/core/src/hashing.rs new file mode 100644 index 0000000000..5c2bbdc51e --- /dev/null +++ b/base_layer/core/src/hashing.rs @@ -0,0 +1,10 @@ +use digest::Digest; +use tari_crypto::{hash_domain, hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}}; + +hash_domain!(BaseLayerCoreDomain, "com.tari.tari-project.base_layer.core"); + +pub(crate) const LMDB_STORAGE_HASH_LABEL: &str = "lmdb_db"; + +pub(crate) fn base_layer_core_domain_separation(label: &'static str) -> DomainSeparatedHasher { + DomainSeparatedHasher::::new_with_label(label) +} \ No newline at end of file diff --git a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs index 3ce8d80931..2894d09040 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs @@ -25,5 +25,24 @@ mod error; mod unconfirmed_pool; // Public re-exports +use digest::Digest; pub use error::UnconfirmedPoolError; +use tari_crypto::{ + hash_domain, + hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, +}; pub use unconfirmed_pool::{UnconfirmedPool, UnconfirmedPoolConfig}; + +hash_domain!( + BaseLayerCoreMemPoolDomain, + "com.tari.tari-project.base_layer.core.mempool", + 1 +); + +pub(crate) const UNCONFIRMED_POOL_HASH_DOMAIN_LABEL: &str = "uncorfimed_pool_output_token_id"; + +pub(crate) fn base_layer_core_mempool_hash_domain( + label: &'static str, +) -> DomainSeparatedHasher { + DomainSeparatedHasher::::new_with_label(label) +} diff --git a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs index a3b12a56b5..e523506c9c 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs @@ -26,13 +26,13 @@ use std::{ sync::Arc, }; -use digest::Digest; use log::*; use serde::{Deserialize, Serialize}; use tari_common_types::types::{HashOutput, PrivateKey, PublicKey, Signature}; use tari_crypto::hash::blake2::Blake256; use tari_utilities::{hex::Hex, ByteArray, Hashable}; +use super::{base_layer_core_mempool_hash_domain, UNCONFIRMED_POOL_HASH_DOMAIN_LABEL}; use crate::{ blocks::Block, mempool::{ @@ -46,7 +46,6 @@ use crate::{ weight::TransactionWeight, }, }; - pub const LOG_TARGET: &str = "c::mp::unconfirmed_pool::unconfirmed_pool_storage"; type TransactionKey = usize; @@ -660,11 +659,14 @@ fn get_output_token_id(output: &TransactionOutput) -> Option<[u8; 32]> { .as_ref() .map(|pk| pk.as_bytes()) .unwrap_or_else(|| root_pk.as_bytes()); - Blake256::new() + let hash = base_layer_core_mempool_hash_domain::(UNCONFIRMED_POOL_HASH_DOMAIN_LABEL) .chain(parent_pk_bytes) .chain(unique_id) - .finalize() - .into() + .finalize(); + + let mut output = [0u8; 32]; + output.copy_from_slice(hash.as_ref()); + output }) } @@ -1027,11 +1029,14 @@ mod test { unconfirmed_pool .insert_many(vec![tx1.clone(), tx2.clone(), tx3.clone(), tx4.clone()], &tx_weight) .unwrap(); - let expected_hash: [u8; 32] = Blake256::new() + + let domain_separated_hash = base_layer_core_mempool_hash_domain::(UNCONFIRMED_POOL_HASH_DOMAIN_LABEL) .chain(parent_pk.as_bytes()) .chain(&unique_id) - .finalize() - .into(); + .finalize(); + + let mut expected_hash: [u8; 32] = [0u8; 32]; + expected_hash.copy_from_slice(domain_separated_hash.as_ref()); let entry = unconfirmed_pool.txs_by_unique_id.get(&expected_hash).unwrap(); let tx_id1 = unconfirmed_pool .txs_by_signature diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs b/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs index d1324dd9d9..b831bca574 100644 --- a/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs +++ b/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs @@ -20,22 +20,25 @@ // 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 tari_common_types::types::{Commitment, FixedHash}; -use tari_crypto::hash::blake2::Blake256; use tari_utilities::ByteArray; +use super::{base_layer_core_transactions_side_chain_domain, CONTRACT_ACCEPTANCE_CHALLENGE_LABEL}; #[derive(Debug, Clone, Copy)] 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 = Blake256::new() + let hash = base_layer_core_transactions_side_chain_domain(CONTRACT_ACCEPTANCE_CHALLENGE_LABEL) .chain(constiution_commitment.as_bytes()) .chain(contract_id.as_slice()) - .finalize() - .into(); + .finalize(); + + let mut slice = [0u8; FixedHash::byte_size()]; + slice.copy_from_slice(hash.as_ref()); + + let hash = FixedHash::from(slice); + Self(hash) } } diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs b/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs index e640c16c94..71b91b644d 100644 --- a/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs +++ b/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs @@ -77,3 +77,20 @@ pub type FixedString = [u8; FIXED_STR_LEN]; pub fn bytes_into_fixed_string>(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!( + BaseLayerCoreTransactionsSideChainDomain, + "com.tari.tari-project.base_layer.core.transactions.side_chain", + 1 +); + +pub(crate) const CONTRACT_ACCEPTANCE_CHALLENGE_LABEL: &str = "contract_acceptance_challenge"; +pub(crate) const SIGNER_SIGNATURE_LABEL: &str = "signer_signature"; + +pub(crate) fn base_layer_core_transactions_side_chain_domain( + label: &'static str, +) -> DomainSeparatedHasher { + DomainSeparatedHasher::::new_with_label(label) +} diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs b/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs index e3c9308299..75ee3b55bc 100644 --- a/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs +++ b/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs @@ -22,13 +22,13 @@ use std::io; -use digest::{Digest, Output}; use rand::rngs::OsRng; use serde::{Deserialize, Serialize}; use tari_common_types::types::{PrivateKey, PublicKey, Signature}; -use tari_crypto::{hash::blake2::Blake256, keys::PublicKey as PublicKeyT}; +use tari_crypto::{hash::blake2::Blake256, hashing::DomainSeparatedHash, keys::PublicKey as PublicKeyT}; use tari_utilities::ByteArray; +use super::{base_layer_core_transactions_side_chain_domain, SIGNER_SIGNATURE_LABEL}; use crate::consensus::{ConsensusDecoding, ConsensusEncoding, ConsensusEncodingSized}; #[derive(Debug, Clone, Hash, PartialEq, Deserialize, Serialize, Eq, Default)] @@ -47,24 +47,23 @@ impl SignerSignature { let (nonce, public_nonce) = PublicKey::random_keypair(&mut OsRng); let final_challenge = Self::build_final_challenge(&signer, challenge, &public_nonce); - let signature = - Signature::sign(signer_secret.clone(), nonce, &*final_challenge).expect("challenge is the correct length"); + let signature = Signature::sign(signer_secret.clone(), nonce, final_challenge.as_ref()) + .expect("challenge is the correct length"); Self { signer, signature } } pub fn verify>(signature: &Signature, signer: &PublicKey, challenge: C) -> bool { let public_nonce = signature.get_public_nonce(); let final_challenge = Self::build_final_challenge(signer, challenge, public_nonce); - signature.verify_challenge(signer, &final_challenge) + signature.verify_challenge(signer, final_challenge.as_ref()) } fn build_final_challenge>( signer: &PublicKey, challenge: C, public_nonce: &PublicKey, - ) -> Output { - // TODO: Use domain-seperated hasher from tari_crypto - Blake256::new() + ) -> DomainSeparatedHash { + base_layer_core_transactions_side_chain_domain(SIGNER_SIGNATURE_LABEL) .chain(signer.as_bytes()) .chain(public_nonce.as_bytes()) .chain(challenge) diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index a588843fdc..b3c93ac946 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -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, @@ -543,8 +541,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, @@ -598,12 +603,25 @@ mod validate_internal_consistency { //---------------------------------- Case2 - PASS --------------------------------------------// features.parent_public_key = Some(PublicKey::default()); - let hash = CommsChallenge::new() - .chain(Some(PublicKey::default()).to_consensus_bytes()) - .chain(Some(unique_id.clone()).to_consensus_bytes()) - .finalize(); + let mut hasher = Blake256::new(); + BaseLayerCovenantsDomain::add_domain_separation_tag(&mut hasher, COVENANTS_FIELD_HASHER_LABEL); + + let hash = hasher + .chain(&Some(PublicKey::default()).to_consensus_bytes()) + .chain(&Some(unique_id.clone()).to_consensus_bytes()) + .finalize() + .to_vec(); + + // let hash = DomainSeparatedConsensusHasher::::new(COVENANTS_FIELD_HASHER_LABEL) + // .chain(&Some(PublicKey::default()).to_consensus_bytes()) + // .chain(&Some(unique_id.clone()).to_consensus_bytes()) + // .finalize(); + + 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_parent_public_key, @field::features_unique_id), @hash(hash.into()))); + let covenant = covenant!(fields_hashed_eq(@fields(@field::features_parent_public_key, @field::features_unique_id), @hash(hash))); test_case( &UtxoTestParams { diff --git a/base_layer/core/src/transactions/transaction_protocol/mod.rs b/base_layer/core/src/transactions/transaction_protocol/mod.rs index 1df53f532d..9b0ff10215 100644 --- a/base_layer/core/src/transactions/transaction_protocol/mod.rs +++ b/base_layer/core/src/transactions/transaction_protocol/mod.rs @@ -86,6 +86,7 @@ // #![allow(clippy::op_ref)] use derivative::Derivative; +use digest::Digest; use serde::{Deserialize, Serialize}; use tari_common_types::types::PrivateKey; use tari_crypto::{errors::RangeProofError, signatures::SchnorrSignatureError}; @@ -99,6 +100,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; @@ -176,3 +178,18 @@ pub struct RewindData { pub rewind_blinding_key: PrivateKey, pub encryption_key: PrivateKey, } + +// hash domain +hash_domain!( + BaseLayerCoreTransactionProtocolDomain, + "com.tari.tari-project.base_layer.core.transactions.transaction_protocol", + 1 +); + +pub(crate) const CALCULATE_TX_ID_LABEL: &str = "calculate_tx_id"; + +pub(crate) fn base_layer_core_transaction_protocol_domain( + label: &'static str, +) -> DomainSeparatedHasher { + DomainSeparatedHasher::::new_with_label(label) +} diff --git a/base_layer/core/src/transactions/transaction_protocol/sender.rs b/base_layer/core/src/transactions/transaction_protocol/sender.rs index 60142f0b10..ff09da218a 100644 --- a/base_layer/core/src/transactions/transaction_protocol/sender.rs +++ b/base_layer/core/src/transactions/transaction_protocol/sender.rs @@ -45,6 +45,7 @@ use tari_crypto::{ }; use tari_script::TariScript; +use super::{base_layer_core_transaction_protocol_domain, CALCULATE_TX_ID_LABEL}; use crate::{ consensus::ConsensusConstants, covenants::Covenant, @@ -702,12 +703,12 @@ impl fmt::Display for SenderTransactionProtocol { } pub fn calculate_tx_id(pub_nonce: &PublicKey, index: usize) -> TxId { - let hash = D::new() + let hash = base_layer_core_transaction_protocol_domain::(CALCULATE_TX_ID_LABEL) .chain(pub_nonce.as_bytes()) .chain(index.to_le_bytes()) .finalize(); let mut bytes: [u8; 8] = [0u8; 8]; - bytes.copy_from_slice(&hash[..8]); + bytes.copy_from_slice(&hash.as_ref()[..8]); u64::from_le_bytes(bytes).into() } From 1ec6c9d016a270c0c97f0e6ffa76ab759faec765 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Thu, 11 Aug 2022 11:19:49 +0100 Subject: [PATCH 05/38] remove unused code --- .../core/src/transactions/transaction_components/test.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index b3c93ac946..a1763eceea 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -612,11 +612,6 @@ mod validate_internal_consistency { .finalize() .to_vec(); - // let hash = DomainSeparatedConsensusHasher::::new(COVENANTS_FIELD_HASHER_LABEL) - // .chain(&Some(PublicKey::default()).to_consensus_bytes()) - // .chain(&Some(unique_id.clone()).to_consensus_bytes()) - // .finalize(); - let mut slice = [0u8; FixedHash::byte_size()]; slice.copy_from_slice(hash.as_ref()); let hash = FixedHash::from(slice); From 7d4b991cfd67aea2804b2218bbe197066961bb36 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Thu, 11 Aug 2022 12:13:19 +0100 Subject: [PATCH 06/38] cleaning --- base_layer/core/src/covenants/fields.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/base_layer/core/src/covenants/fields.rs b/base_layer/core/src/covenants/fields.rs index 238e05f315..df0cb7ff5a 100644 --- a/base_layer/core/src/covenants/fields.rs +++ b/base_layer/core/src/covenants/fields.rs @@ -597,15 +597,6 @@ mod test { let hash = fields.construct_challenge_from(&output).finalize(); let hash = hash.to_vec(); - // 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 = - // DomainSeparatedConsensusHasher::::new(COVENANTS_FIELD_HASHER_LABEL) - // .chain(&challenge) - // .finalize(); - let mut hasher = Blake256::new(); BaseLayerCovenantsDomain::add_domain_separation_tag(&mut hasher, COVENANTS_FIELD_HASHER_LABEL); let expected_hash = hasher From 1ce46e9cfc0fb8b32a812f5df9c939cea9938516 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Thu, 11 Aug 2022 12:16:41 +0100 Subject: [PATCH 07/38] remove unused hashing.rs --- base_layer/core/src/hashing.rs | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 base_layer/core/src/hashing.rs diff --git a/base_layer/core/src/hashing.rs b/base_layer/core/src/hashing.rs deleted file mode 100644 index 5c2bbdc51e..0000000000 --- a/base_layer/core/src/hashing.rs +++ /dev/null @@ -1,10 +0,0 @@ -use digest::Digest; -use tari_crypto::{hash_domain, hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}}; - -hash_domain!(BaseLayerCoreDomain, "com.tari.tari-project.base_layer.core"); - -pub(crate) const LMDB_STORAGE_HASH_LABEL: &str = "lmdb_db"; - -pub(crate) fn base_layer_core_domain_separation(label: &'static str) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} \ No newline at end of file From a80f0f34bb4f74a01cd2616d7d43fb780c263967 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 08:20:44 +0100 Subject: [PATCH 08/38] add suggestions on PR --- .../common_types/src/types/bullet_rangeproofs.rs | 4 ++-- base_layer/common_types/src/types/mod.rs | 12 +++--------- .../core/src/chain_storage/lmdb_db/lmdb_db.rs | 4 ++-- base_layer/core/src/chain_storage/lmdb_db/mod.rs | 13 ++++++------- 4 files changed, 13 insertions(+), 20 deletions(-) diff --git a/base_layer/common_types/src/types/bullet_rangeproofs.rs b/base_layer/common_types/src/types/bullet_rangeproofs.rs index 386217ce93..571717fb89 100644 --- a/base_layer/common_types/src/types/bullet_rangeproofs.rs +++ b/base_layer/common_types/src/types/bullet_rangeproofs.rs @@ -31,14 +31,14 @@ use serde::{ }; use tari_utilities::{hex::*, ByteArray, ByteArrayError, Hashable}; -use super::{base_layer_common_types_domain_hasher, BULLET_RANGEPROOFS_HASHER_LABEL}; +use super::BulletRangeProofHasherBlake256; #[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct BulletRangeProof(pub Vec); /// Implement the hashing function for RangeProof for use in the MMR impl Hashable for BulletRangeProof { fn hash(&self) -> Vec { - base_layer_common_types_domain_hasher(BULLET_RANGEPROOFS_HASHER_LABEL) + BulletRangeProofHasherBlake256::new() .chain(&self.0) .finalize() .as_ref() diff --git a/base_layer/common_types/src/types/mod.rs b/base_layer/common_types/src/types/mod.rs index 52425f3708..e265f21844 100644 --- a/base_layer/common_types/src/types/mod.rs +++ b/base_layer/common_types/src/types/mod.rs @@ -81,15 +81,9 @@ pub type RangeProof = BulletRangeProof; use tari_crypto::{hash_domain, hashing::DomainSeparatedHasher}; -pub(crate) const BULLET_RANGEPROOFS_HASHER_LABEL: &str = "bullet_rangeproofs.hasher"; - hash_domain!( - BaseLayerCommonTypesDomain, - "com.tari.tari-project.base_layer.common_types" + BulletRangeProofHashDomain, + "com.tari.tari-project.base_layer.common_types.bullet_rangeproofs" ); -pub(crate) fn base_layer_common_types_domain_hasher( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} +pub type BulletRangeProofHasherBlake256 = DomainSeparatedHasher; diff --git a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs index c250e384cd..01a273ef23 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs @@ -56,7 +56,7 @@ use tari_utilities::{ ByteArray, }; -use super::{base_layer_core_chain_storage_lmdb_hasher, LMDB_STORAGE_HASH_LABEL}; +use super::CoreChainStorageHasherBlake256; use crate::{ blocks::{ Block, @@ -2736,7 +2736,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 = base_layer_core_chain_storage_lmdb_hasher::(LMDB_STORAGE_HASH_LABEL) + let unique_id_hash = CoreChainStorageHasherBlake256::new() .chain(unique_id) .finalize(); Self::from_raw_parts( diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index c8a37aaf8d..67c11ab177 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -80,10 +80,9 @@ pub(crate) struct TransactionKernelRowData { hash_domain!(BaseLayerCoreDomain, "com.tari.tari-project.base_layer.core"); -pub(crate) const LMDB_STORAGE_HASH_LABEL: &str = "lmdb_db"; - -pub(crate) fn base_layer_core_chain_storage_lmdb_hasher( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} +hash_domain!( + CoreChainStorageHashDomain, + "com.tari.tari-project.base_layer.core.lmdb_db", + 1 +); +pub type CoreChainStorageHasherBlake256 = DomainSeparatedHasher; From 8c9fd22dacd61e9450c79ee010d79a867f6122dc Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 08:25:20 +0100 Subject: [PATCH 09/38] run cargo fmt --- base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs index 01a273ef23..5f488b7e53 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs @@ -2736,9 +2736,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 = CoreChainStorageHasherBlake256::new() - .chain(unique_id) - .finalize(); + let unique_id_hash = CoreChainStorageHasherBlake256::new().chain(unique_id).finalize(); Self::from_raw_parts( parent_public_key.map(|p| p.as_bytes()).unwrap_or(&[0; 32][..]), unique_id_hash.as_ref(), From 8bcbfa99c6571715766da07efcf83549ea45eb9d Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 08:30:54 +0100 Subject: [PATCH 10/38] add blak256 import --- base_layer/core/src/chain_storage/lmdb_db/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index 67c11ab177..8d6dc9e9ee 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -26,6 +26,7 @@ use serde::{Deserialize, Serialize}; use tari_common_types::types::HashOutput; use tari_crypto::{ hash_domain, + hash::blake2::Blake256, hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, }; From 8301c746f2443004a462548fce9b5c2209e900a3 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 08:32:30 +0100 Subject: [PATCH 11/38] cargo fmt --- base_layer/core/src/chain_storage/lmdb_db/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index 8d6dc9e9ee..c19a5b6287 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -25,8 +25,8 @@ pub use lmdb_db::{create_lmdb_database, create_recovery_lmdb_database, LMDBDatab use serde::{Deserialize, Serialize}; use tari_common_types::types::HashOutput; use tari_crypto::{ - hash_domain, hash::blake2::Blake256, + hash_domain, hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, }; From 597861bc550548067e9e73b05cf8818a7a258e10 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 08:37:30 +0100 Subject: [PATCH 12/38] remove unused imports --- base_layer/core/src/chain_storage/lmdb_db/mod.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index c19a5b6287..4f1263dba1 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -20,15 +20,10 @@ // 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; 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::blake2::Blake256, - hash_domain, - hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, -}; +use tari_crypto::{hash::blake2::Blake256, hash_domain, hashing::DomainSeparatedHasher}; use crate::transactions::transaction_components::{TransactionInput, TransactionKernel, TransactionOutput}; From ff7f66197ffdfaf1a3e7faade698a7183788d90d Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 10:06:46 +0100 Subject: [PATCH 13/38] add further simplifications --- .../core/src/mempool/unconfirmed_pool/mod.rs | 18 ++++-------------- .../unconfirmed_pool/unconfirmed_pool.rs | 7 +++---- .../contract_acceptance_challenge.rs | 4 ++-- .../transaction_components/side_chain/mod.rs | 19 ++++++++++--------- .../side_chain/signer_signature.rs | 4 ++-- .../transactions/transaction_protocol/mod.rs | 16 +++++----------- .../transaction_protocol/sender.rs | 4 ++-- 7 files changed, 28 insertions(+), 44 deletions(-) diff --git a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs index 2894d09040..cd88a5afe1 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs @@ -25,24 +25,14 @@ mod error; mod unconfirmed_pool; // Public re-exports -use digest::Digest; pub use error::UnconfirmedPoolError; -use tari_crypto::{ - hash_domain, - hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, -}; +use tari_crypto::{hash::blake2::Blake256, hash_domain, hashing::DomainSeparatedHasher}; pub use unconfirmed_pool::{UnconfirmedPool, UnconfirmedPoolConfig}; hash_domain!( - BaseLayerCoreMemPoolDomain, - "com.tari.tari-project.base_layer.core.mempool", + UnconfirmedPoolOutputTokenIdHashDomain, + "com.tari.tari-project.base_layer.core.mempool.unconfirmed_pool_output_token_id", 1 ); -pub(crate) const UNCONFIRMED_POOL_HASH_DOMAIN_LABEL: &str = "uncorfimed_pool_output_token_id"; - -pub(crate) fn base_layer_core_mempool_hash_domain( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} +pub type UnconfirmedPoolOutputHasherBlake256 = DomainSeparatedHasher; diff --git a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs index e523506c9c..e3291db99f 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs @@ -29,10 +29,9 @@ use std::{ use log::*; use serde::{Deserialize, Serialize}; use tari_common_types::types::{HashOutput, PrivateKey, PublicKey, Signature}; -use tari_crypto::hash::blake2::Blake256; use tari_utilities::{hex::Hex, ByteArray, Hashable}; -use super::{base_layer_core_mempool_hash_domain, UNCONFIRMED_POOL_HASH_DOMAIN_LABEL}; +use super::UnconfirmedPoolOutputHasherBlake256; use crate::{ blocks::Block, mempool::{ @@ -659,7 +658,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()); - let hash = base_layer_core_mempool_hash_domain::(UNCONFIRMED_POOL_HASH_DOMAIN_LABEL) + let hash = UnconfirmedPoolOutputHasherBlake256::new() .chain(parent_pk_bytes) .chain(unique_id) .finalize(); @@ -1030,7 +1029,7 @@ mod test { .insert_many(vec![tx1.clone(), tx2.clone(), tx3.clone(), tx4.clone()], &tx_weight) .unwrap(); - let domain_separated_hash = base_layer_core_mempool_hash_domain::(UNCONFIRMED_POOL_HASH_DOMAIN_LABEL) + let domain_separated_hash = UnconfirmedPoolOutputHasherBlake256::new() .chain(parent_pk.as_bytes()) .chain(&unique_id) .finalize(); diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs b/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs index b831bca574..7dbece6097 100644 --- a/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs +++ b/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs @@ -23,13 +23,13 @@ use tari_common_types::types::{Commitment, FixedHash}; use tari_utilities::ByteArray; -use super::{base_layer_core_transactions_side_chain_domain, CONTRACT_ACCEPTANCE_CHALLENGE_LABEL}; +use super::ContractAcceptanceHasherBlake256; #[derive(Debug, Clone, Copy)] pub struct ContractAcceptanceChallenge(FixedHash); impl ContractAcceptanceChallenge { pub fn new(constiution_commitment: &Commitment, contract_id: &FixedHash) -> Self { - let hash = base_layer_core_transactions_side_chain_domain(CONTRACT_ACCEPTANCE_CHALLENGE_LABEL) + let hash = ContractAcceptanceHasherBlake256::new() .chain(constiution_commitment.as_bytes()) .chain(contract_id.as_slice()) .finalize(); diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs b/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs index 71b91b644d..e296cb9b87 100644 --- a/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs +++ b/base_layer/core/src/transactions/transaction_components/side_chain/mod.rs @@ -81,16 +81,17 @@ pub fn bytes_into_fixed_string>(value: T) -> FixedString { use tari_crypto::{hash::blake2::Blake256, hash_domain, hashing::DomainSeparatedHasher}; hash_domain!( - BaseLayerCoreTransactionsSideChainDomain, - "com.tari.tari-project.base_layer.core.transactions.side_chain", + ContractAcceptanceHashDomain, + "com.tari.tari-project.base_layer.core.transactions.side_chain.contract_acceptance_challenge", 1 ); -pub(crate) const CONTRACT_ACCEPTANCE_CHALLENGE_LABEL: &str = "contract_acceptance_challenge"; -pub(crate) const SIGNER_SIGNATURE_LABEL: &str = "signer_signature"; +pub type ContractAcceptanceHasherBlake256 = DomainSeparatedHasher; -pub(crate) fn base_layer_core_transactions_side_chain_domain( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} +hash_domain!( + SignerSignatureHashDomain, + "com.tari.tari-project.base_layer.core.transactions.side_chain.signer_signature", + 1 +); + +pub type SignerSignatureHasherBlake256 = DomainSeparatedHasher; diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs b/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs index 75ee3b55bc..877261eac0 100644 --- a/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs +++ b/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs @@ -28,7 +28,7 @@ use tari_common_types::types::{PrivateKey, PublicKey, Signature}; use tari_crypto::{hash::blake2::Blake256, hashing::DomainSeparatedHash, keys::PublicKey as PublicKeyT}; use tari_utilities::ByteArray; -use super::{base_layer_core_transactions_side_chain_domain, SIGNER_SIGNATURE_LABEL}; +use super::SignerSignatureHasherBlake256; use crate::consensus::{ConsensusDecoding, ConsensusEncoding, ConsensusEncodingSized}; #[derive(Debug, Clone, Hash, PartialEq, Deserialize, Serialize, Eq, Default)] @@ -63,7 +63,7 @@ impl SignerSignature { challenge: C, public_nonce: &PublicKey, ) -> DomainSeparatedHash { - base_layer_core_transactions_side_chain_domain(SIGNER_SIGNATURE_LABEL) + SignerSignatureHasherBlake256::new() .chain(signer.as_bytes()) .chain(public_nonce.as_bytes()) .chain(challenge) diff --git a/base_layer/core/src/transactions/transaction_protocol/mod.rs b/base_layer/core/src/transactions/transaction_protocol/mod.rs index 9b0ff10215..4ef2e90871 100644 --- a/base_layer/core/src/transactions/transaction_protocol/mod.rs +++ b/base_layer/core/src/transactions/transaction_protocol/mod.rs @@ -86,10 +86,9 @@ // #![allow(clippy::op_ref)] use derivative::Derivative; -use digest::Digest; 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}; @@ -181,15 +180,10 @@ pub struct RewindData { // hash domain hash_domain!( - BaseLayerCoreTransactionProtocolDomain, - "com.tari.tari-project.base_layer.core.transactions.transaction_protocol", + CalculateTxIdTransactionProtocolHashDomain, + "com.tari.tari-project.base_layer.core.transactions.transaction_protocol.calculate_tx_id", 1 ); -pub(crate) const CALCULATE_TX_ID_LABEL: &str = "calculate_tx_id"; - -pub(crate) fn base_layer_core_transaction_protocol_domain( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} +pub type CalculateTxIdTransactionProtocolHasherBlake256 = + DomainSeparatedHasher; diff --git a/base_layer/core/src/transactions/transaction_protocol/sender.rs b/base_layer/core/src/transactions/transaction_protocol/sender.rs index ff09da218a..f85a224268 100644 --- a/base_layer/core/src/transactions/transaction_protocol/sender.rs +++ b/base_layer/core/src/transactions/transaction_protocol/sender.rs @@ -45,7 +45,7 @@ use tari_crypto::{ }; use tari_script::TariScript; -use super::{base_layer_core_transaction_protocol_domain, CALCULATE_TX_ID_LABEL}; +use super::CalculateTxIdTransactionProtocolHasherBlake256; use crate::{ consensus::ConsensusConstants, covenants::Covenant, @@ -703,7 +703,7 @@ impl fmt::Display for SenderTransactionProtocol { } pub fn calculate_tx_id(pub_nonce: &PublicKey, index: usize) -> TxId { - let hash = base_layer_core_transaction_protocol_domain::(CALCULATE_TX_ID_LABEL) + let hash = CalculateTxIdTransactionProtocolHasherBlake256::new() .chain(pub_nonce.as_bytes()) .chain(index.to_le_bytes()) .finalize(); From 9d9c5ad37b7caa84e7666c6f56b36e9a18e1ca88 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 10:30:10 +0100 Subject: [PATCH 14/38] add necesary dependency on tests --- .../core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs index e3291db99f..909be08a07 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs @@ -673,7 +673,7 @@ fn get_output_token_id(output: &TransactionOutput) -> Option<[u8; 32]> { mod test { use rand::rngs::OsRng; use tari_common::configuration::Network; - use tari_crypto::keys::PublicKey as PublicKeyTrait; + use tari_crypto::{hash::blake2::Blake256, keys::PublicKey as PublicKeyTrait}; use super::*; use crate::{ From e181364aed7eda81fa121382563971d7cc02ca49 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 12:18:24 +0100 Subject: [PATCH 15/38] change getTransactionOutputHash js test and remove generic type from calculate_tx_id and build transaction methods --- .../unconfirmed_pool/unconfirmed_pool.rs | 2 +- .../core/src/transactions/test_helpers.rs | 5 +- .../transaction_protocol/sender.rs | 17 +++-- .../transaction_initializer.rs | 27 ++++---- .../src/output_manager_service/service.rs | 18 ++--- .../transaction_service/storage/sqlite_db.rs | 2 +- .../output_manager_service_tests/service.rs | 2 +- .../transaction_service_tests/service.rs | 10 +-- .../transaction_service_tests/storage.rs | 2 +- integration_tests/helpers/util.js | 65 +++---------------- 10 files changed, 51 insertions(+), 99 deletions(-) diff --git a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs index 909be08a07..4d625d6892 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs @@ -789,7 +789,7 @@ mod test { .unwrap(); let factories = CryptoFactories::default(); - let mut stx_protocol = stx_builder.build::(&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(); diff --git a/base_layer/core/src/transactions/test_helpers.rs b/base_layer/core/src/transactions/test_helpers.rs index 66fdbf5fb1..4f6978b6e6 100644 --- a/base_layer/core/src/transactions/test_helpers.rs +++ b/base_layer/core/src/transactions/test_helpers.rs @@ -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, }; @@ -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::(&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) @@ -704,7 +703,7 @@ pub fn create_stx_protocol(schema: TransactionSchema) -> (SenderTransactionProto .unwrap(); } - let stx_protocol = stx_builder.build::(&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(); diff --git a/base_layer/core/src/transactions/transaction_protocol/sender.rs b/base_layer/core/src/transactions/transaction_protocol/sender.rs index f85a224268..a350dce39b 100644 --- a/base_layer/core/src/transactions/transaction_protocol/sender.rs +++ b/base_layer/core/src/transactions/transaction_protocol/sender.rs @@ -23,7 +23,6 @@ use std::fmt; use derivative::Derivative; -use digest::Digest; use serde::{Deserialize, Serialize}; use tari_common_types::{ transaction::TxId, @@ -702,7 +701,7 @@ impl fmt::Display for SenderTransactionProtocol { } } -pub fn calculate_tx_id(pub_nonce: &PublicKey, index: usize) -> TxId { +pub fn calculate_tx_id(pub_nonce: &PublicKey, index: usize) -> TxId { let hash = CalculateTxIdTransactionProtocolHasherBlake256::new() .chain(pub_nonce.as_bytes()) .chain(index.to_le_bytes()) @@ -987,7 +986,7 @@ mod test { p2.sender_offset_private_key.clone(), ) .unwrap(); - let mut sender = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut sender = builder.build(&factories, None, u64::MAX).unwrap(); assert!(!sender.is_failed()); assert!(sender.is_finalizing()); match sender.finalize(&factories, None, u64::MAX) { @@ -1020,7 +1019,7 @@ mod test { .with_change_script(script, ExecutionStack::default(), PrivateKey::default()) // A little twist: Check the case where the change is less than the cost of another output .with_amount(0, MicroTari(1200) - fee - MicroTari(10)); - let mut alice = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut alice = builder.build(&factories, None, u64::MAX).unwrap(); assert!(alice.is_single_round_message_ready()); let msg = alice.build_single_round_message().unwrap(); // Send message down the wire....and wait for response @@ -1088,7 +1087,7 @@ mod test { ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()) .with_amount(0, MicroTari(5000)); - let mut alice = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut alice = builder.build(&factories, None, u64::MAX).unwrap(); assert!(alice.is_single_round_message_ready()); let msg = alice.build_single_round_message().unwrap(); println!( @@ -1168,7 +1167,7 @@ mod test { ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()) .with_amount(0, (2u64.pow(32) + 1).into()); - let mut alice = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut alice = builder.build(&factories, None, u64::MAX).unwrap(); assert!(alice.is_single_round_message_ready()); let msg = alice.build_single_round_message().unwrap(); // Send message down the wire....and wait for response @@ -1215,7 +1214,7 @@ mod test { ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); // Verify that the initial 'fee greater than amount' check rejects the transaction when it is constructed - match builder.build::(&factories, None, u64::MAX) { + match builder.build(&factories, None, u64::MAX) { Ok(_) => panic!("'BuildError(\"Fee is greater than amount\")' not caught"), Err(e) => assert_eq!(e.message, "Fee is greater than amount".to_string()), }; @@ -1250,7 +1249,7 @@ mod test { ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); // Test if the transaction passes the initial 'fee greater than amount' check when it is constructed - match builder.build::(&factories, None, u64::MAX) { + match builder.build(&factories, None, u64::MAX) { Ok(_) => {}, Err(e) => panic!("Unexpected error: {:?}", e), }; @@ -1288,7 +1287,7 @@ mod test { MicroTari::zero(), ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); - let mut alice = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut alice = builder.build(&factories, None, u64::MAX).unwrap(); assert!(alice.is_single_round_message_ready()); let msg = alice.build_single_round_message().unwrap(); diff --git a/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs b/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs index c81ca5b380..ba5696b22c 100644 --- a/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs +++ b/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs @@ -25,7 +25,6 @@ use std::{ fmt::{Debug, Error, Formatter}, }; -use digest::Digest; use log::*; use rand::rngs::OsRng; use tari_common_types::{ @@ -487,7 +486,7 @@ impl SenderTransactionInitializer { /// If all the input data is present, but one or more fields are invalid, the function will return a /// `SenderTransactionProtocol` instance in the Failed state. #[allow(clippy::too_many_lines)] - pub fn build( + pub fn build( mut self, factories: &CryptoFactories, prev_header: Option, @@ -631,7 +630,7 @@ impl SenderTransactionInitializer { let tx_id = match self.tx_id { Some(id) => id, - None => calculate_tx_id::(&public_nonce, 0), + None => calculate_tx_id(&public_nonce, 0), }; let recipient_output_features = self.recipient_output_features.clone().into_vec(); @@ -739,7 +738,7 @@ mod test { let p = TestParams::new(); // Start the builder let builder = SenderTransactionInitializer::new(0, &create_consensus_constants(0)); - let err = builder.build::(&factories, None, u64::MAX).unwrap_err(); + let err = builder.build(&factories, None, u64::MAX).unwrap_err(); let script = script!(Nop); // We should have a bunch of fields missing still, but we can recover and continue assert_eq!( @@ -780,12 +779,12 @@ mod test { .fee() .calculate(MicroTari(20), 1, 1, 2, p.get_size_for_default_metadata(2)); // We needed a change input, so this should fail - let err = builder.build::(&factories, None, u64::MAX).unwrap_err(); + let err = builder.build(&factories, None, u64::MAX).unwrap_err(); assert_eq!(err.message, "Change spending key was not provided"); // Ok, give them a change output let mut builder = err.builder; builder.with_change_secret(p.change_spend_key); - let result = builder.build::(&factories, None, u64::MAX).unwrap(); + let result = builder.build(&factories, None, u64::MAX).unwrap(); // Peek inside and check the results if let SenderState::Finalizing(info) = result.into_state() { assert_eq!(info.num_recipients, 0, "Number of receivers"); @@ -833,7 +832,7 @@ mod test { .with_input(utxo, input) .with_fee_per_gram(MicroTari(4)) .with_prevent_fee_gt_amount(false); - let result = builder.build::(&factories, None, u64::MAX).unwrap(); + let result = builder.build(&factories, None, u64::MAX).unwrap(); // Peek inside and check the results if let SenderState::Finalizing(info) = result.into_state() { assert_eq!(info.num_recipients, 0, "Number of receivers"); @@ -884,7 +883,7 @@ mod test { .with_input(utxo, input) .with_fee_per_gram(MicroTari(1)) .with_prevent_fee_gt_amount(false); - let result = builder.build::(&factories, None, u64::MAX).unwrap(); + let result = builder.build(&factories, None, u64::MAX).unwrap(); // Peek inside and check the results if let SenderState::Finalizing(info) = result.into_state() { assert_eq!(info.num_recipients, 0, "Number of receivers"); @@ -921,7 +920,7 @@ mod test { let (utxo, input) = create_test_input(MicroTari(50), 0, &factories.commitment); builder.with_input(utxo, input); } - let err = builder.build::(&factories, None, u64::MAX).unwrap_err(); + let err = builder.build(&factories, None, u64::MAX).unwrap_err(); assert_eq!(err.message, "Too many inputs in transaction"); } @@ -958,7 +957,7 @@ mod test { MicroTari::zero(), ); // .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); - let err = builder.build::(&factories, None, u64::MAX).unwrap_err(); + let err = builder.build(&factories, None, u64::MAX).unwrap_err(); assert_eq!(err.message, "Fee is less than the minimum"); } @@ -992,7 +991,7 @@ mod test { MicroTari::zero(), ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); - let err = builder.build::(&factories, None, u64::MAX).unwrap_err(); + let err = builder.build(&factories, None, u64::MAX).unwrap_err(); assert_eq!( err.message, "You are spending (472 µT) more than you're providing (400 µT)." @@ -1040,7 +1039,7 @@ mod test { MicroTari::zero(), ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); - let result = builder.build::(&factories, None, u64::MAX).unwrap(); + let result = builder.build(&factories, None, u64::MAX).unwrap(); // Peek inside and check the results if let SenderState::Failed(TransactionProtocolError::UnsupportedError(s)) = result.into_state() { assert_eq!(s, "Multiple recipients are not supported yet") @@ -1096,7 +1095,7 @@ mod test { MicroTari::zero(), ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); - let result = builder.build::(&factories, None, u64::MAX).unwrap(); + let result = builder.build(&factories, None, u64::MAX).unwrap(); // Peek inside and check the results if let SenderState::SingleRoundMessageReady(info) = result.into_state() { assert_eq!(info.num_recipients, 1, "Number of receivers"); @@ -1149,7 +1148,7 @@ mod test { MicroTari::zero(), ) .with_change_script(script, ExecutionStack::default(), PrivateKey::default()); - let result = builder.build::(&factories, None, u64::MAX); + let result = builder.build(&factories, None, u64::MAX); match result { Ok(_) => panic!("Range proof should have failed to verify"), diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index 924a060264..375e6645c9 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -926,7 +926,7 @@ where } let stp = builder - .build::( + .build( &self.resources.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), @@ -1138,7 +1138,7 @@ where // } let mut stp = builder - .build::(&self.resources.factories, None, u64::MAX) + .build(&self.resources.factories, None, u64::MAX) .map_err(|e| OutputManagerError::BuildError(e.message))?; // if let Some((spending_key, script_private_key)) = change_keys { // // let change_script_offset_public_key = stp.get_change_sender_offset_public_key()?.ok_or_else(|| { @@ -1298,7 +1298,7 @@ where let factories = CryptoFactories::default(); let mut stp = builder - .build::( + .build( &self.resources.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), @@ -1795,8 +1795,8 @@ where } let mut stp = tx_builder - .build::( - &self.resources.factories, + .build( + &self.resource/snap/code/103/usr/share/code/resources/app/out/vs/code/electron-sandbox/workbench/workbench.htmls.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), ) @@ -2027,7 +2027,7 @@ where } let mut stp = tx_builder - .build::( + .build( &self.resources.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), @@ -2215,7 +2215,7 @@ where .map_err(|e| OutputManagerError::BuildError(e.message))?; let mut stp = tx_builder - .build::( + .build( &self.resources.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), @@ -2350,7 +2350,7 @@ where let factories = CryptoFactories::default(); let mut stp = builder - .build::( + .build( &self.resources.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), @@ -2437,7 +2437,7 @@ where let factories = CryptoFactories::default(); let mut stp = builder - .build::( + .build( &self.resources.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), diff --git a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs index 6dad2f66ef..243f444363 100644 --- a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs +++ b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs @@ -2289,7 +2289,7 @@ mod test { ) .with_change_script(script!(Nop), ExecutionStack::default(), PrivateKey::random(&mut OsRng)); - let mut stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut stp = builder.build(&factories, None, u64::MAX).unwrap(); let outbound_tx1 = OutboundTransaction { tx_id: 1u64.into(), diff --git a/base_layer/wallet/tests/output_manager_service_tests/service.rs b/base_layer/wallet/tests/output_manager_service_tests/service.rs index 20b34de2b6..599bb435d5 100644 --- a/base_layer/wallet/tests/output_manager_service_tests/service.rs +++ b/base_layer/wallet/tests/output_manager_service_tests/service.rs @@ -339,7 +339,7 @@ async fn generate_sender_transaction_message(amount: MicroTari) -> (TxId, Transa script_private_key, ); - let mut stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut stp = builder.build(&factories, None, u64::MAX).unwrap(); let tx_id = stp.get_tx_id().unwrap(); ( tx_id, diff --git a/base_layer/wallet/tests/transaction_service_tests/service.rs b/base_layer/wallet/tests/transaction_service_tests/service.rs index 02a7a55505..36d0aef54d 100644 --- a/base_layer/wallet/tests/transaction_service_tests/service.rs +++ b/base_layer/wallet/tests/transaction_service_tests/service.rs @@ -2163,7 +2163,7 @@ async fn test_transaction_cancellation() { ) .with_change_script(script!(Nop), ExecutionStack::default(), PrivateKey::random(&mut OsRng)); - let mut stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut stp = builder.build(&factories, None, u64::MAX).unwrap(); let tx_sender_msg = stp.build_single_round_message().unwrap(); let tx_id2 = tx_sender_msg.tx_id; let proto_message = proto::TransactionSenderMessage::single(tx_sender_msg.into()); @@ -2245,7 +2245,7 @@ async fn test_transaction_cancellation() { ) .with_change_script(script!(Nop), ExecutionStack::default(), PrivateKey::random(&mut OsRng)); - let mut stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut stp = builder.build(&factories, None, u64::MAX).unwrap(); let tx_sender_msg = stp.build_single_round_message().unwrap(); let tx_id3 = tx_sender_msg.tx_id; let proto_message = proto::TransactionSenderMessage::single(tx_sender_msg.into()); @@ -2908,7 +2908,7 @@ async fn test_restarting_transaction_protocols() { inputs!(PublicKey::from_secret_key(&script_private_key)), script_private_key, ); - let mut bob_stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut bob_stp = builder.build(&factories, None, u64::MAX).unwrap(); let msg = bob_stp.build_single_round_message().unwrap(); let bob_pre_finalize = bob_stp.clone(); @@ -4251,7 +4251,7 @@ async fn test_resend_on_startup() { ) .with_change_script(script!(Nop), ExecutionStack::default(), PrivateKey::random(&mut OsRng)); - let mut stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut stp = builder.build(&factories, None, u64::MAX).unwrap(); let stp_msg = stp.build_single_round_message().unwrap(); let tx_sender_msg = TransactionSenderMessage::Single(Box::new(stp_msg)); @@ -4728,7 +4728,7 @@ async fn test_transaction_timeout_cancellation() { ) .with_change_script(script!(Nop), ExecutionStack::default(), PrivateKey::random(&mut OsRng)); - let mut stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let mut stp = builder.build(&factories, None, u64::MAX).unwrap(); let stp_msg = stp.build_single_round_message().unwrap(); let tx_sender_msg = TransactionSenderMessage::Single(Box::new(stp_msg)); diff --git a/base_layer/wallet/tests/transaction_service_tests/storage.rs b/base_layer/wallet/tests/transaction_service_tests/storage.rs index 2ac80380b5..92c1cd5cc2 100644 --- a/base_layer/wallet/tests/transaction_service_tests/storage.rs +++ b/base_layer/wallet/tests/transaction_service_tests/storage.rs @@ -104,7 +104,7 @@ pub fn test_db_backend(backend: T) { ) .with_change_script(script!(Nop), ExecutionStack::default(), PrivateKey::random(&mut OsRng)); - let stp = builder.build::(&factories, None, u64::MAX).unwrap(); + let stp = builder.build(&factories, None, u64::MAX).unwrap(); let messages = vec!["Hey!".to_string(), "Yo!".to_string(), "Sup!".to_string()]; let amounts = vec![MicroTari::from(10_000), MicroTari::from(23_000), MicroTari::from(5_000)]; diff --git a/integration_tests/helpers/util.js b/integration_tests/helpers/util.js index cebaf4161d..da8ac85831 100644 --- a/integration_tests/helpers/util.js +++ b/integration_tests/helpers/util.js @@ -244,40 +244,23 @@ const encodeOption = function (value) { }; const getTransactionOutputHash = function (output) { - const KEY = null; // optional key - const OUTPUT_LENGTH = 32; // bytes - const context = blake2bInit(OUTPUT_LENGTH, KEY); - let encodedBytesLength = 0; // version const version = Buffer.from([0]); - encodedBytesLength += version.length; - blake2bUpdate(context, version); // features let features = Buffer.concat([ // features.version Buffer.from([0]), // features.maturity - Buffer.from([parseInt(output.features.maturity)]), + Buffer.from(varint.encode(output.features.maturity)), // features.output_type Buffer.from([output.features.output_type]), - ]); - // features.parent_public_key - features = Buffer.concat([ - Buffer.from(features), + // features.parent_public_key encodeOption(output.features.parent_public_key), - ]); - // features.unique_id - features = Buffer.concat([ - Buffer.from(features), + // features.unique_id encodeOption(output.features.unique_id), - ]); - // features.sidechain_features - features = Buffer.concat([ - Buffer.from(features), - encodeOption(output.features.sidechain_features), - ]); // features.asset - features = Buffer.concat([ - Buffer.from(features), + // features.sidechain_features + Buffer.from(encodeOption(null)), + // features.asset encodeOption(output.features.asset), ]); // features.mint_non_fungible @@ -296,38 +279,10 @@ const getTransactionOutputHash = function (output) { Buffer.from([output.features.metadata.length]), Buffer.from(output.features.metadata), ]); - encodedBytesLength += features.length; - blake2bUpdate(context, features); - // commitment - encodedBytesLength += output.commitment.length; - blake2bUpdate(context, output.commitment); - // script - const script = Buffer.concat([ - Buffer.from([output.script.length]), - Buffer.from(output.script), - ]); - encodedBytesLength += script.length; - blake2bUpdate(context, script); - // covenant - const covenant = Buffer.concat([ - Buffer.from([output.covenant.length]), - Buffer.from(output.covenant), - ]); - encodedBytesLength += covenant.length; - blake2bUpdate(context, covenant); - // encrypted_value - encodedBytesLength += output.encrypted_value.length; - blake2bUpdate(context, output.encrypted_value); - - expect(context.c).to.equal(encodedBytesLength); - const hash = blake2bFinal(context); - const hashBuffer = Buffer.from(hash); - // console.log( - // "\ngetTransactionOutputHash - hash", - // hashBuffer.toString("hex"), - // "\n" - // ); - return hashBuffer; + + return new Blake256() + .chain(version) + .chain(features) }; function consoleLogTransactionDetails(txnDetails) { From 8d4f49591917338834916c937797709a8ae67704 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 12:20:41 +0100 Subject: [PATCH 16/38] run cargo fmt --- base_layer/wallet/src/output_manager_service/service.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index 375e6645c9..6ca61d9492 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -1796,7 +1796,8 @@ where let mut stp = tx_builder .build( - &self.resource/snap/code/103/usr/share/code/resources/app/out/vs/code/electron-sandbox/workbench/workbench.htmls.factories, + &self.resource / snap / code / 103 / usr / share / code / resources / app / out / vs / code / electron - + sandbox / workbench / workbench.htmls.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), ) From 11b6da1aacc0df449f0ea212814738a1e50719a7 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 12:36:37 +0100 Subject: [PATCH 17/38] refactor incorrect add of path --- .../core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs | 2 +- .../core/src/transactions/transaction_protocol/sender.rs | 1 - .../transaction_protocol/transaction_initializer.rs | 2 +- base_layer/wallet/src/output_manager_service/service.rs | 3 +-- integration_tests/helpers/util.js | 8 ++++++++ 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs index 4d625d6892..f6d4adec98 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs @@ -673,7 +673,7 @@ fn get_output_token_id(output: &TransactionOutput) -> Option<[u8; 32]> { mod test { use rand::rngs::OsRng; use tari_common::configuration::Network; - use tari_crypto::{hash::blake2::Blake256, keys::PublicKey as PublicKeyTrait}; + use tari_crypto::{keys::PublicKey as PublicKeyTrait}; use super::*; use crate::{ diff --git a/base_layer/core/src/transactions/transaction_protocol/sender.rs b/base_layer/core/src/transactions/transaction_protocol/sender.rs index a350dce39b..2aae5728cb 100644 --- a/base_layer/core/src/transactions/transaction_protocol/sender.rs +++ b/base_layer/core/src/transactions/transaction_protocol/sender.rs @@ -797,7 +797,6 @@ mod test { use tari_crypto::{ commitment::HomomorphicCommitmentFactory, errors::RangeProofError::ProofConstructionError, - hash::blake2::Blake256, keys::{PublicKey as PublicKeyTrait, SecretKey as SecretKeyTrait}, range_proof::RangeProofService, tari_utilities::{hex::Hex, ByteArray}, diff --git a/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs b/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs index ba5696b22c..13166f3141 100644 --- a/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs +++ b/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs @@ -710,7 +710,7 @@ impl SenderTransactionInitializer { mod test { use rand::rngs::OsRng; use tari_common_types::types::PrivateKey; - use tari_crypto::{hash::blake2::Blake256, keys::SecretKey}; + use tari_crypto::keys::SecretKey; use tari_script::{script, ExecutionStack, TariScript}; use crate::{ diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index 6ca61d9492..54c9a2d704 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -1796,8 +1796,7 @@ where let mut stp = tx_builder .build( - &self.resource / snap / code / 103 / usr / share / code / resources / app / out / vs / code / electron - - sandbox / workbench / workbench.htmls.factories, + &self.resource.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), ) diff --git a/integration_tests/helpers/util.js b/integration_tests/helpers/util.js index da8ac85831..ec5dddede7 100644 --- a/integration_tests/helpers/util.js +++ b/integration_tests/helpers/util.js @@ -6,6 +6,7 @@ const varint = require("varint"); const { blake2bInit, blake2bUpdate, blake2bFinal } = require("blakejs"); const { expect } = require("chai"); +const { encode } = require("punycode"); const NO_CONNECTION = 14; @@ -244,8 +245,10 @@ const encodeOption = function (value) { }; const getTransactionOutputHash = function (output) { + let encodeBytesLength = 0; // version const version = Buffer.from([0]); + encodeBytesLength += version.length; // features let features = Buffer.concat([ // features.version @@ -280,6 +283,11 @@ const getTransactionOutputHash = function (output) { Buffer.from(output.features.metadata), ]); + encodeBytesLength += features.length; + + // commitment + encodeBytesLength += output.commitment.length; + return new Blake256() .chain(version) .chain(features) From 1b53ac7ddef2c04d9a999ff84330bf1766534fcd Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 12:38:01 +0100 Subject: [PATCH 18/38] run cargo fmt --- .../core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs index f6d4adec98..bd1ec66a9b 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs @@ -673,7 +673,7 @@ fn get_output_token_id(output: &TransactionOutput) -> Option<[u8; 32]> { mod test { use rand::rngs::OsRng; use tari_common::configuration::Network; - use tari_crypto::{keys::PublicKey as PublicKeyTrait}; + use tari_crypto::keys::PublicKey as PublicKeyTrait; use super::*; use crate::{ From a273740ae5df818f3eaf8c9076d6509197c861c7 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 12:45:36 +0100 Subject: [PATCH 19/38] refactor some code --- base_layer/wallet/src/output_manager_service/service.rs | 3 +-- base_layer/wallet/src/transaction_service/storage/sqlite_db.rs | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index 54c9a2d704..3a78cd6926 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -62,7 +62,6 @@ use tari_core::{ use tari_crypto::{ commitment::HomomorphicCommitmentFactory, errors::RangeProofError, - hash::blake2::Blake256, keys::{DiffieHellmanSharedSecret, PublicKey as PublicKeyTrait, SecretKey}, ristretto::RistrettoSecretKey, }; @@ -1796,7 +1795,7 @@ where let mut stp = tx_builder .build( - &self.resource.factories, + &self.resources.factories, None, self.last_seen_tip_height.unwrap_or(u64::MAX), ) diff --git a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs index 243f444363..59798362d0 100644 --- a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs +++ b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs @@ -2214,7 +2214,6 @@ mod test { }, }; use tari_crypto::{ - hash::blake2::Blake256, keys::{PublicKey as PublicKeyTrait, SecretKey as SecretKeyTrait}, }; use tari_script::{script, ExecutionStack, TariScript}; From a98a4619d5d658a1881585a3f1010965a81af14f Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 12:51:07 +0100 Subject: [PATCH 20/38] run cargo fmt --- .../wallet/src/transaction_service/storage/sqlite_db.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs index 59798362d0..5fb0682997 100644 --- a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs +++ b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs @@ -2213,9 +2213,7 @@ mod test { SenderTransactionProtocol, }, }; - use tari_crypto::{ - keys::{PublicKey as PublicKeyTrait, SecretKey as SecretKeyTrait}, - }; + use tari_crypto::keys::{PublicKey as PublicKeyTrait, SecretKey as SecretKeyTrait}; use tari_script::{script, ExecutionStack, TariScript}; use tari_test_utils::random::string; use tempfile::tempdir; From 47839c532112cca6397346709b507199ce947ba1 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 13:03:01 +0100 Subject: [PATCH 21/38] remove unused imports --- .../wallet/tests/output_manager_service_tests/service.rs | 1 - base_layer/wallet/tests/transaction_service_tests/storage.rs | 5 +---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/base_layer/wallet/tests/output_manager_service_tests/service.rs b/base_layer/wallet/tests/output_manager_service_tests/service.rs index 599bb435d5..a3f22b8728 100644 --- a/base_layer/wallet/tests/output_manager_service_tests/service.rs +++ b/base_layer/wallet/tests/output_manager_service_tests/service.rs @@ -58,7 +58,6 @@ use tari_core::{ }; use tari_crypto::{ commitment::HomomorphicCommitmentFactory, - hash::blake2::Blake256, keys::{PublicKey as PublicKeyTrait, SecretKey}, }; use tari_key_manager::{cipher_seed::CipherSeed, mnemonic::Mnemonic}; diff --git a/base_layer/wallet/tests/transaction_service_tests/storage.rs b/base_layer/wallet/tests/transaction_service_tests/storage.rs index 92c1cd5cc2..c05a90d978 100644 --- a/base_layer/wallet/tests/transaction_service_tests/storage.rs +++ b/base_layer/wallet/tests/transaction_service_tests/storage.rs @@ -42,10 +42,7 @@ use tari_core::{ SenderTransactionProtocol, }, }; -use tari_crypto::{ - hash::blake2::Blake256, - keys::{PublicKey as PublicKeyTrait, SecretKey as SecretKeyTrait}, -}; +use tari_crypto::keys::{PublicKey as PublicKeyTrait, SecretKey as SecretKeyTrait}; use tari_script::{script, ExecutionStack, TariScript}; use tari_test_utils::random; use tari_wallet::{ From d5a894f40688ac67c3bdd6ab4a9b052697e02fd2 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 13:25:07 +0100 Subject: [PATCH 22/38] refactor cucumber tests --- integration_tests/helpers/util.js | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/integration_tests/helpers/util.js b/integration_tests/helpers/util.js index ec5dddede7..9455cf29ec 100644 --- a/integration_tests/helpers/util.js +++ b/integration_tests/helpers/util.js @@ -4,7 +4,7 @@ const net = require("net"); const varint = require("varint"); -const { blake2bInit, blake2bUpdate, blake2bFinal } = require("blakejs"); +const { Blake256 } = require("blakejs"); const { expect } = require("chai"); const { encode } = require("punycode"); @@ -245,10 +245,8 @@ const encodeOption = function (value) { }; const getTransactionOutputHash = function (output) { - let encodeBytesLength = 0; // version const version = Buffer.from([0]); - encodeBytesLength += version.length; // features let features = Buffer.concat([ // features.version @@ -282,15 +280,28 @@ const getTransactionOutputHash = function (output) { Buffer.from([output.features.metadata.length]), Buffer.from(output.features.metadata), ]); - - encodeBytesLength += features.length; - // commitment - encodeBytesLength += output.commitment.length; - + const commitment = Buffer.from([output.commitments]); + // script + const script = Buffer.concat([ + Buffer.from([output.script.length]), + Buffer.from(output.script), + ]); + // covenant + const covenant = Buffer.concat([ + Buffer.from([output.covenant.length]), + Buffer.from([output.covenant]), + ]); + // encrypted value + const encryptedValue = Buffer.from([output.encrypted_value]); + return new Blake256() .chain(version) .chain(features) + .chain(commitment) + .chain(script) + .chain(covenant) + .chain(encryptedValue); }; function consoleLogTransactionDetails(txnDetails) { From a3bc2994f4c99edd5973d8cdf0792812284e1e38 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Fri, 12 Aug 2022 14:43:41 +0100 Subject: [PATCH 23/38] add changes --- integration_tests/helpers/util.js | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/integration_tests/helpers/util.js b/integration_tests/helpers/util.js index 9455cf29ec..ab309d6768 100644 --- a/integration_tests/helpers/util.js +++ b/integration_tests/helpers/util.js @@ -5,8 +5,6 @@ const net = require("net"); const varint = require("varint"); const { Blake256 } = require("blakejs"); -const { expect } = require("chai"); -const { encode } = require("punycode"); const NO_CONNECTION = 14; @@ -294,14 +292,14 @@ const getTransactionOutputHash = function (output) { ]); // encrypted value const encryptedValue = Buffer.from([output.encrypted_value]); - + return new Blake256() - .chain(version) - .chain(features) - .chain(commitment) - .chain(script) - .chain(covenant) - .chain(encryptedValue); + .chain(version) + .chain(features) + .chain(commitment) + .chain(script) + .chain(covenant) + .chain(encryptedValue); }; function consoleLogTransactionDetails(txnDetails) { From edc0c88fedae61111d7ac734307edcca8af651bb Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 11:43:34 +0100 Subject: [PATCH 24/38] removed unused hash domain --- base_layer/core/src/chain_storage/lmdb_db/mod.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index 4f1263dba1..428cddb31c 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -74,8 +74,6 @@ pub(crate) struct TransactionKernelRowData { pub hash: HashOutput, } -hash_domain!(BaseLayerCoreDomain, "com.tari.tari-project.base_layer.core"); - hash_domain!( CoreChainStorageHashDomain, "com.tari.tari-project.base_layer.core.lmdb_db", From f3c39afc9a8482f50e209eb035143d2ae3a3ff2d Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 12:23:07 +0100 Subject: [PATCH 25/38] resolve further issues --- .../core/src/chain_storage/lmdb_db/lmdb_db.rs | 1 - .../core/src/chain_storage/lmdb_db/mod.rs | 1 - .../src/covenants/filters/fields_hashed_eq.rs | 1 - .../core/src/mempool/unconfirmed_pool/mod.rs | 2 -- .../unconfirmed_pool/unconfirmed_pool.rs | 2 -- .../transaction_components/test.rs | 20 ++++--------------- 6 files changed, 4 insertions(+), 23 deletions(-) diff --git a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs index ed31a8a257..a13096c61a 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs @@ -45,7 +45,6 @@ use tari_utilities::{ ByteArray, }; -use super::CoreChainStorageHasherBlake256; use crate::{ blocks::{ Block, diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index 303f294812..5a2a773e6a 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -78,4 +78,3 @@ hash_domain!( "com.tari.tari-project.base_layer.core.lmdb_db", 1 ); -pub type CoreChainStorageHasherBlake256 = DomainSeparatedHasher; diff --git a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs index f7a4bc2a1f..194f999721 100644 --- a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs +++ b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs @@ -41,7 +41,6 @@ impl Filter for FieldsHashedEqFilter { #[cfg(test)] mod test { - use tari_common_types::types::FixedHash; use tari_crypto::hashing::DomainSeparation; use tari_common_types::types::Challenge; diff --git a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs index cd88a5afe1..1533e3a927 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs @@ -34,5 +34,3 @@ hash_domain!( "com.tari.tari-project.base_layer.core.mempool.unconfirmed_pool_output_token_id", 1 ); - -pub type UnconfirmedPoolOutputHasherBlake256 = DomainSeparatedHasher; diff --git a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs index 85ea989410..d2a8cf1e3f 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/unconfirmed_pool.rs @@ -31,7 +31,6 @@ use serde::{Deserialize, Serialize}; use tari_common_types::types::{HashOutput, PrivateKey, Signature}; use tari_utilities::{hex::Hex, Hashable}; -use super::UnconfirmedPoolOutputHasherBlake256; use crate::{ blocks::Block, mempool::{ @@ -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::{ diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index 0113006be4..b457750edd 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -537,9 +537,9 @@ 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 tari_comms::types::CommsChallenge; + use tari_crypto::hashing::DomainSeparation; use super::*; use crate::{ @@ -594,21 +594,9 @@ mod validate_internal_consistency { .unwrap(); //---------------------------------- Case2 - PASS --------------------------------------------// - features.parent_public_key = Some(PublicKey::default()); - let mut hasher = CommsChallenge::new(); - BaseLayerCovenantsDomain::add_domain_separation_tag(&mut hasher, COVENANTS_FIELD_HASHER_LABEL); + let hash = CommsChallenge::new().chain(features.to_consensus_bytes()).finalize(); - let hash = hasher - .chain(&Some(PublicKey::default()).to_consensus_bytes()) - .chain(&Some(unique_id.clone()).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_parent_public_key, @field::features_unique_id), @hash(hash))); + let covenant = covenant!(fields_hashed_eq(@fields(@field::features), @hash(hash.into()))); test_case( &UtxoTestParams { From 573c075fc1e082c39a401f435522ce1bb1219a6c Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 12:25:33 +0100 Subject: [PATCH 26/38] resolve further issues --- base_layer/core/src/chain_storage/lmdb_db/mod.rs | 2 +- base_layer/core/src/mempool/unconfirmed_pool/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/base_layer/core/src/chain_storage/lmdb_db/mod.rs b/base_layer/core/src/chain_storage/lmdb_db/mod.rs index 5a2a773e6a..e462684b17 100644 --- a/base_layer/core/src/chain_storage/lmdb_db/mod.rs +++ b/base_layer/core/src/chain_storage/lmdb_db/mod.rs @@ -23,7 +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::blake2::Blake256, hash_domain, hashing::DomainSeparatedHasher}; +use tari_crypto::hash_domain; use crate::transactions::transaction_components::{TransactionInput, TransactionKernel, TransactionOutput}; diff --git a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs index 1533e3a927..d78780dc01 100644 --- a/base_layer/core/src/mempool/unconfirmed_pool/mod.rs +++ b/base_layer/core/src/mempool/unconfirmed_pool/mod.rs @@ -26,7 +26,7 @@ mod unconfirmed_pool; // Public re-exports pub use error::UnconfirmedPoolError; -use tari_crypto::{hash::blake2::Blake256, hash_domain, hashing::DomainSeparatedHasher}; +use tari_crypto::hash_domain; pub use unconfirmed_pool::{UnconfirmedPool, UnconfirmedPoolConfig}; hash_domain!( From 2004f581e213974da8ef0c60f26bb22f6d073e31 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 12:27:31 +0100 Subject: [PATCH 27/38] run cargo fmt --- base_layer/core/src/covenants/filters/fields_hashed_eq.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs index 194f999721..3ec33cf4fc 100644 --- a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs +++ b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs @@ -41,9 +41,8 @@ impl Filter for FieldsHashedEqFilter { #[cfg(test)] mod test { - use tari_crypto::hashing::DomainSeparation; - use tari_common_types::types::Challenge; + use tari_crypto::hashing::DomainSeparation; use super::*; use crate::{ From 102fc344689ea4fa4bfe1c7dd14fa602588485bd Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 12:34:28 +0100 Subject: [PATCH 28/38] remove unused dependencies --- .../core/src/transactions/transaction_components/test.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index b457750edd..0ce26ef580 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -537,15 +537,11 @@ mod output_features { mod validate_internal_consistency { - use tari_common_types::types::FixedHash; + use digest::Digest; use tari_comms::types::CommsChallenge; - use tari_crypto::hashing::DomainSeparation; use super::*; - use crate::{ - consensus::ToConsensusBytes, - covenants::{BaseLayerCovenantsDomain, COVENANTS_FIELD_HASHER_LABEL}, - }; + use crate::consensus::ToConsensusBytes; fn test_case( input_params: &UtxoTestParams, From c318dc1305279fc1002a9bba334f38fe6cfe64ea Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 13:19:16 +0100 Subject: [PATCH 29/38] resolve `it_validates_that_the_covenant_is_honoured` --- .../transaction_components/test.rs | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index 0ce26ef580..7d4ae0c82e 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -538,10 +538,14 @@ mod output_features { mod validate_internal_consistency { use digest::Digest; - use tari_comms::types::CommsChallenge; + 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, @@ -590,7 +594,17 @@ 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()))); From 3c738c52ddd7b0c0578fb96a5b669fa7f6c72f11 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 13:27:28 +0100 Subject: [PATCH 30/38] run cargo fmt --- .../core/src/transactions/transaction_components/test.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index 7d4ae0c82e..c3bcd93700 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -597,10 +597,7 @@ mod validate_internal_consistency { 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 hash = hasher.chain(features.to_consensus_bytes()).finalize().to_vec(); let mut slice = [0u8; FixedHash::byte_size()]; slice.copy_from_slice(hash.as_ref()); From 7c0e3cb65181b5e760b08a9f2490182f436ba7d5 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 16:23:32 +0100 Subject: [PATCH 31/38] refactor cucumber tests --- .../helpers/transactionOutputHashing.js | 29 +++---------------- 1 file changed, 4 insertions(+), 25 deletions(-) diff --git a/integration_tests/helpers/transactionOutputHashing.js b/integration_tests/helpers/transactionOutputHashing.js index 1b1bfd3b6b..d8aedf2443 100644 --- a/integration_tests/helpers/transactionOutputHashing.js +++ b/integration_tests/helpers/transactionOutputHashing.js @@ -15,39 +15,18 @@ const featuresToConsensusBytes = function (features) { // TODO: Keep this number in sync with 'get_current_version()' in 'output_features_version.rs' const OUTPUT_FEATURES_VERSION = 0x00; - // Add length byte to unique id - note this only works until 127 bytes (TODO: varint encoding) - let unique_id = features.unique_id - ? toLengthEncoded(features.unique_id) - : null; - return Buffer.concat([ // version Buffer.from([OUTPUT_FEATURES_VERSION]), - // maturity - Buffer.from([parseInt(features.maturity || 0)]), // output_type Buffer.from([features.output_type]), - // parent_public_key - encodeOption(features.parent_public_key, "hex"), - // unique_id - encodeOption(unique_id, false), - // sidechain_features - // TODO: SideChainFeatures - encodeOption(null), - // asset - // TODO: AssetOutputFeatures - encodeOption(null), - // mint_non_fungible - // TODO: MintNonFungibleFeatures - encodeOption(null), - // sidechain_checkpoint - // TODO: SideChainCheckpointFeatures - encodeOption(null), + // maturity + Buffer.from([parseInt(features.maturity || 0)]), // metadata // TODO: Vec (len is 0) Buffer.from([0x00]), - // committee_definition - // TODO: CommitteeDefinitionFeatures (len is 0) + // sidechain_features + // TODO: SideChainFeatures encodeOption(null), ]); }; From d3cb3ee67e9042a52fc01cf16b8ea6d84a46e950 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 17:31:12 +0100 Subject: [PATCH 32/38] remove files that were already eliminated --- .../contract_acceptance_challenge.rs | 50 -------- .../side_chain/signer_signature.rs | 115 ------------------ 2 files changed, 165 deletions(-) delete mode 100644 base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs delete mode 100644 base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs b/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs deleted file mode 100644 index 7dbece6097..0000000000 --- a/base_layer/core/src/transactions/transaction_components/side_chain/contract_acceptance_challenge.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// 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 tari_common_types::types::{Commitment, FixedHash}; -use tari_utilities::ByteArray; - -use super::ContractAcceptanceHasherBlake256; -#[derive(Debug, Clone, Copy)] -pub struct ContractAcceptanceChallenge(FixedHash); - -impl ContractAcceptanceChallenge { - pub fn new(constiution_commitment: &Commitment, contract_id: &FixedHash) -> Self { - let hash = ContractAcceptanceHasherBlake256::new() - .chain(constiution_commitment.as_bytes()) - .chain(contract_id.as_slice()) - .finalize(); - - let mut slice = [0u8; FixedHash::byte_size()]; - slice.copy_from_slice(hash.as_ref()); - - let hash = FixedHash::from(slice); - - Self(hash) - } -} - -impl AsRef<[u8]> for ContractAcceptanceChallenge { - fn as_ref(&self) -> &[u8] { - self.0.as_ref() - } -} diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs b/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs deleted file mode 100644 index 877261eac0..0000000000 --- a/base_layer/core/src/transactions/transaction_components/side_chain/signer_signature.rs +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// 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 std::io; - -use rand::rngs::OsRng; -use serde::{Deserialize, Serialize}; -use tari_common_types::types::{PrivateKey, PublicKey, Signature}; -use tari_crypto::{hash::blake2::Blake256, hashing::DomainSeparatedHash, keys::PublicKey as PublicKeyT}; -use tari_utilities::ByteArray; - -use super::SignerSignatureHasherBlake256; -use crate::consensus::{ConsensusDecoding, ConsensusEncoding, ConsensusEncodingSized}; - -#[derive(Debug, Clone, Hash, PartialEq, Deserialize, Serialize, Eq, Default)] -pub struct SignerSignature { - signer: PublicKey, - signature: Signature, -} - -impl SignerSignature { - pub fn new(signer: PublicKey, signature: Signature) -> Self { - Self { signer, signature } - } - - pub fn sign>(signer_secret: &PrivateKey, challenge: C) -> Self { - let signer = PublicKey::from_secret_key(signer_secret); - let (nonce, public_nonce) = PublicKey::random_keypair(&mut OsRng); - - let final_challenge = Self::build_final_challenge(&signer, challenge, &public_nonce); - let signature = Signature::sign(signer_secret.clone(), nonce, final_challenge.as_ref()) - .expect("challenge is the correct length"); - Self { signer, signature } - } - - pub fn verify>(signature: &Signature, signer: &PublicKey, challenge: C) -> bool { - let public_nonce = signature.get_public_nonce(); - let final_challenge = Self::build_final_challenge(signer, challenge, public_nonce); - signature.verify_challenge(signer, final_challenge.as_ref()) - } - - fn build_final_challenge>( - signer: &PublicKey, - challenge: C, - public_nonce: &PublicKey, - ) -> DomainSeparatedHash { - SignerSignatureHasherBlake256::new() - .chain(signer.as_bytes()) - .chain(public_nonce.as_bytes()) - .chain(challenge) - .finalize() - } - - pub fn signer(&self) -> &PublicKey { - &self.signer - } - - pub fn signature(&self) -> &Signature { - &self.signature - } -} - -impl ConsensusEncoding for SignerSignature { - fn consensus_encode(&self, writer: &mut W) -> Result<(), io::Error> { - self.signer.consensus_encode(writer)?; - self.signature.consensus_encode(writer)?; - Ok(()) - } -} - -impl ConsensusEncodingSized for SignerSignature { - fn consensus_encode_exact_size(&self) -> usize { - 32 + 64 - } -} - -impl ConsensusDecoding for SignerSignature { - fn consensus_decode(reader: &mut R) -> Result { - Ok(Self { - signer: PublicKey::consensus_decode(reader)?, - signature: Signature::consensus_decode(reader)?, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::consensus::check_consensus_encoding_correctness; - - #[test] - fn it_encodes_and_decodes_correctly() { - let subject = SignerSignature::default(); - check_consensus_encoding_correctness(subject).unwrap(); - } -} From ddb6b513f63a99b7cad6df9addcef37157473041 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 17:35:40 +0100 Subject: [PATCH 33/38] refactor transactionOutputHashing.js --- .../helpers/transactionOutputHashing.js | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/integration_tests/helpers/transactionOutputHashing.js b/integration_tests/helpers/transactionOutputHashing.js index d8aedf2443..e984ae584c 100644 --- a/integration_tests/helpers/transactionOutputHashing.js +++ b/integration_tests/helpers/transactionOutputHashing.js @@ -43,20 +43,8 @@ const getTransactionOutputHash = function (output) { assertBufferType(output.covenant); assertBufferType(output.encrypted_value, 24); const hash = hasher - // version - .chain(Buffer.from([OUTPUT_FEATURES_VERSION])) // features .chain(featuresToConsensusBytes(output.features)) - // commitment - .chain(output.commitment) - // script - .chain(toLengthEncoded(output.script)) - // covenant - .chain(toLengthEncoded(output.covenant)) - // encrypted_value - .chain(output.encrypted_value) - // minimum_value_promise - .chain(toLittleEndian(output.minimum_value_promise, 64)) .finalize(); const hashBuffer = Buffer.from(hash); From 00bd69ea3c902f71a7829c19724781cb636aeba7 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 18:03:27 +0100 Subject: [PATCH 34/38] add changes to transactionOuptutHashing.js --- .../transaction_components/test.rs | 2 +- .../helpers/transactionOutputHashing.js | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index c3bcd93700..1ee67ed725 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -603,7 +603,7 @@ mod validate_internal_consistency { 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 { diff --git a/integration_tests/helpers/transactionOutputHashing.js b/integration_tests/helpers/transactionOutputHashing.js index e984ae584c..c2196e48cd 100644 --- a/integration_tests/helpers/transactionOutputHashing.js +++ b/integration_tests/helpers/transactionOutputHashing.js @@ -3,9 +3,7 @@ const { Blake256 } = require("./hashing"); const { - toLittleEndian, encodeOption, - toLengthEncoded, assertBufferType, } = require("./util"); @@ -37,14 +35,21 @@ const getTransactionOutputHash = function (output) { // TODO: Keep this number in sync with 'get_current_version()' in 'transaction_output_version.rs' const OUTPUT_FEATURES_VERSION = 0x00; - let hasher = new Blake256(); - assertBufferType(output.commitment, 32); - assertBufferType(output.script); - assertBufferType(output.covenant); - assertBufferType(output.encrypted_value, 24); const hash = hasher + // version + .chain(Buffer.from([OUTPUT_FEATURES_VERSION])) // features .chain(featuresToConsensusBytes(output.features)) + // commitment + .chain(output.commitment) + // script + .chain(toLengthEncoded(output.script)) + // covenant + .chain(toLengthEncoded(output.covenant)) + // encrypted_value + .chain(output.encrypted_value) + // minimum_value_promise + .chain(toLittleEndian(output.minimum_value_promise, 64)) .finalize(); const hashBuffer = Buffer.from(hash); From 2e66f2453ee81e2deff723471c3f75bc5f84b47a Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Tue, 16 Aug 2022 19:02:15 +0100 Subject: [PATCH 35/38] refactor feature tests --- integration_tests/helpers/transactionOutputHashing.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/integration_tests/helpers/transactionOutputHashing.js b/integration_tests/helpers/transactionOutputHashing.js index c2196e48cd..d8aedf2443 100644 --- a/integration_tests/helpers/transactionOutputHashing.js +++ b/integration_tests/helpers/transactionOutputHashing.js @@ -3,7 +3,9 @@ const { Blake256 } = require("./hashing"); const { + toLittleEndian, encodeOption, + toLengthEncoded, assertBufferType, } = require("./util"); @@ -35,6 +37,11 @@ const getTransactionOutputHash = function (output) { // TODO: Keep this number in sync with 'get_current_version()' in 'transaction_output_version.rs' const OUTPUT_FEATURES_VERSION = 0x00; + let hasher = new Blake256(); + assertBufferType(output.commitment, 32); + assertBufferType(output.script); + assertBufferType(output.covenant); + assertBufferType(output.encrypted_value, 24); const hash = hasher // version .chain(Buffer.from([OUTPUT_FEATURES_VERSION])) From 49f20df82d3173052894de81978eb758ed00a32b Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Wed, 17 Aug 2022 10:22:03 +0100 Subject: [PATCH 36/38] remove unnecessary allocation --- base_layer/core/src/covenants/filters/fields_hashed_eq.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs index 3ec33cf4fc..57755b5289 100644 --- a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs +++ b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs @@ -32,8 +32,7 @@ impl Filter for FieldsHashedEqFilter { let hash = context.next_arg()?.require_hash()?; output_set.retain(|output| { let challenge = fields.construct_challenge_from(output).finalize(); - let challenge = challenge.to_vec(); - Ok(challenge[..] == *hash) + Ok(challenge.finalize()[..] == *hash) })?; Ok(()) } From 01269a9707600f4009a53092005ef3e7ba85caac Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Wed, 17 Aug 2022 10:31:27 +0100 Subject: [PATCH 37/38] refactor finalize --- base_layer/core/src/covenants/filters/fields_hashed_eq.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs index 57755b5289..1eaf6e9dc5 100644 --- a/base_layer/core/src/covenants/filters/fields_hashed_eq.rs +++ b/base_layer/core/src/covenants/filters/fields_hashed_eq.rs @@ -32,7 +32,7 @@ impl Filter for FieldsHashedEqFilter { let hash = context.next_arg()?.require_hash()?; output_set.retain(|output| { let challenge = fields.construct_challenge_from(output).finalize(); - Ok(challenge.finalize()[..] == *hash) + Ok(challenge[..] == *hash) })?; Ok(()) } From 6316cb778b9015aca06397e583fba4ed4d3eda11 Mon Sep 17 00:00:00 2001 From: jorgeantonio21 Date: Wed, 17 Aug 2022 10:55:39 +0100 Subject: [PATCH 38/38] remove cucumber tests with @dan --- integration_tests/features/WalletCli.feature | 66 -------------------- 1 file changed, 66 deletions(-) diff --git a/integration_tests/features/WalletCli.feature b/integration_tests/features/WalletCli.feature index a11ce1dfc6..b0784d007a 100644 --- a/integration_tests/features/WalletCli.feature +++ b/integration_tests/features/WalletCli.feature @@ -139,69 +139,3 @@ Feature: Wallet CLI Given I have a base node BASE And I have wallet WALLET connected to base node BASE Then I run whois BASE on wallet WALLET via command line - - @dan @critical - Scenario: As a user I want to publish a contract definition via command line - Given I have a base node BASE - And I have wallet WALLET connected to base node BASE - And I have mining node MINE connected to base node BASE and wallet WALLET - And mining node MINE mines 4 blocks - Then I wait for wallet WALLET to have at least 1000000 uT - And I publish a contract definition DEF1 from file "fixtures/contract_definition.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 1 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - Then WALLET is connected to BASE - - @dan @critical - Scenario: As a user I want to publish a contract constitution via command line - Given I have a base node BASE - And I have wallet WALLET connected to base node BASE - And I have mining node MINE connected to base node BASE and wallet WALLET - And mining node MINE mines 4 blocks - Then I wait for wallet WALLET to have at least 1000000 uT - And I publish a contract definition DEF1 from file "fixtures/contract_definition.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 1 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - And I publish a contract constitution from file "fixtures/contract_constitution.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 2 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - Then WALLET is connected to BASE - - @dan @critical - Scenario: As a user I want to publish a contract update proposal via command line - Given I have a base node BASE - And I have wallet WALLET connected to base node BASE - And I have mining node MINE connected to base node BASE and wallet WALLET - And mining node MINE mines 4 blocks - Then I wait for wallet WALLET to have at least 1000000 uT - And I publish a contract definition DEF1 from file "fixtures/contract_definition.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 1 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - When I publish a contract constitution from file "fixtures/contract_constitution.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 2 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - And I publish a contract update proposal from file "fixtures/contract_update_proposal.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 3 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - Then WALLET is connected to BASE - - @dan @critical - Scenario: As a user I want to publish a contract amendment via command line - Given I have a base node BASE - And I have wallet WALLET connected to base node BASE - And I have mining node MINE connected to base node BASE and wallet WALLET - And mining node MINE mines 4 blocks - Then I wait for wallet WALLET to have at least 1000000 uT - And I publish a contract definition DEF1 from file "fixtures/contract_definition.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 1 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - When I publish a contract constitution from file "fixtures/contract_constitution.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 2 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - And I publish a contract update proposal from file "fixtures/contract_update_proposal.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 3 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - And I publish a contract amendment from file "fixtures/contract_amendment.json" on wallet WALLET via command line - And mining node MINE mines 8 blocks - Then wallet WALLET has at least 4 transactions that are all TRANSACTION_STATUS_MINED_CONFIRMED and not cancelled - Then WALLET is connected to BASE