Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(block-sync): check coinbase maturity #4168

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion base_layer/core/src/transactions/aggregated_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,6 @@ impl AggregateBody {
/// This function does NOT check that inputs come from the UTXO set
/// The reward is the total amount of Tari rewarded for this block (block reward + total fees), this should be 0
/// for a transaction

pub fn validate_internal_consistency(
&self,
tx_offset: &BlindingFactor,
Expand Down
25 changes: 25 additions & 0 deletions base_layer/core/src/transactions/test_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,20 @@ pub fn create_random_signature_from_s_key(
(p, Signature::sign(s_key, r, &e).unwrap())
}

pub fn create_consensus_manager() -> ConsensusManager {
ConsensusManager::builder(Network::LocalNet).build()
}

pub fn create_unblinded_coinbase(test_params: &TestParams, height: u64) -> UnblindedOutput {
let rules = create_consensus_manager();
let constants = rules.consensus_constants(height);
test_params.create_unblinded_output(UtxoTestParams {
value: rules.get_block_reward_at(height),
features: OutputFeatures::create_coinbase(height + constants.coinbase_lock_height(), 0x00),
..Default::default()
})
}

pub fn create_unblinded_output(
script: TariScript,
output_features: OutputFeatures,
Expand Down Expand Up @@ -743,6 +757,17 @@ pub fn create_stx_protocol(schema: TransactionSchema) -> (SenderTransactionProto
(stx_protocol, outputs)
}

pub fn create_coinbase_kernel(excess: &PrivateKey) -> TransactionKernel {
let public_excess = PublicKey::from_secret_key(excess);
let s = create_signature(excess.clone(), 0.into(), 0);
KernelBuilder::new()
.with_features(KernelFeatures::COINBASE_KERNEL)
.with_excess(&Commitment::from_public_key(&public_excess))
.with_signature(&s)
.build()
.unwrap()
}

/// Create a transaction kernel with the given fee, using random keys to generate the signature
pub fn create_test_kernel(fee: MicroTari, lock_height: u64) -> TransactionKernel {
let (excess, s) = create_random_signature(fee, lock_height);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,11 @@ impl<B: BlockchainBackend + 'static> BlockValidator<B> {
let kernels_result = kernels_task.await??;

// Perform final checks using validation outputs
helpers::check_coinbase_maturity(&self.rules, valid_header.height, outputs_result.coinbase())?;
helpers::check_coinbase_reward(
&self.factories.commitment,
&self.rules,
&valid_header,
valid_header.height,
kernels_result.kernel_sum.fees,
kernels_result.coinbase(),
outputs_result.coinbase(),
Expand Down
112 changes: 108 additions & 4 deletions base_layer/core/src/validation/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,12 +683,22 @@ pub fn validate_covenants(block: &Block) -> Result<(), ValidationError> {
pub fn check_coinbase_reward(
factory: &CommitmentFactory,
rules: &ConsensusManager,
header: &BlockHeader,
height: u64,
total_fees: MicroTari,
coinbase_kernel: &TransactionKernel,
coinbase_output: &TransactionOutput,
) -> Result<(), ValidationError> {
let reward = rules.emission_schedule().block_reward(header.height) + total_fees;
let constants = rules.consensus_constants(height);
if coinbase_output.features.maturity < height + constants.coinbase_lock_height() {
warn!(
target: LOG_TARGET,
"Coinbase {} found with maturity set too low", coinbase_output
);
return Err(ValidationError::TransactionError(
TransactionError::InvalidCoinbaseMaturity,
));
}
let reward = rules.emission_schedule().block_reward(height) + total_fees;
let rhs = &coinbase_kernel.excess + &factory.commit_value(&Default::default(), reward.into());
if rhs != coinbase_output.commitment {
warn!(
Expand All @@ -700,6 +710,24 @@ pub fn check_coinbase_reward(
Ok(())
}

pub fn check_coinbase_maturity(
rules: &ConsensusManager,
height: u64,
coinbase_output: &TransactionOutput,
) -> Result<(), ValidationError> {
let constants = rules.consensus_constants(height);
if coinbase_output.features.maturity < height + constants.coinbase_lock_height() {
warn!(
target: LOG_TARGET,
"Coinbase {} found with maturity set too low", coinbase_output
);
return Err(ValidationError::TransactionError(
TransactionError::InvalidCoinbaseMaturity,
));
}
Ok(())
}

pub fn check_kernel_sum(
factory: &CommitmentFactory,
kernel_sum: &KernelSum,
Expand Down Expand Up @@ -774,7 +802,15 @@ pub fn check_blockchain_version(constants: &ConsensusConstants, version: u16) ->

#[cfg(test)]
mod test {

use tari_test_utils::unpack_enum;

use super::*;
use crate::transactions::{
test_helpers,
test_helpers::TestParams,
transaction_components::{OutputFeatures, TransactionInputVersion},
};

mod is_all_unique_and_sorted {
use super::*;
Expand Down Expand Up @@ -843,7 +879,6 @@ mod test {

mod check_lock_height {
use super::*;
use crate::transactions::test_helpers;

#[test]
fn it_checks_the_kernel_timelock() {
Expand All @@ -861,7 +896,6 @@ mod test {

mod check_maturity {
use super::*;
use crate::transactions::transaction_components::{OutputFeatures, TransactionInputVersion};

#[test]
fn it_checks_the_input_maturity() {
Expand Down Expand Up @@ -893,4 +927,74 @@ mod test {
check_maturity(6, &[input]).unwrap();
}
}

mod check_coinbase_maturity {

use super::*;

#[test]
fn it_succeeds_for_valid_coinbase() {
let test_params = TestParams::new();
let rules = test_helpers::create_consensus_manager();
let coinbase = test_helpers::create_unblinded_coinbase(&test_params, 1);
let coinbase_output = coinbase.as_transaction_output(&CryptoFactories::default()).unwrap();
check_coinbase_maturity(&rules, 1, &coinbase_output).unwrap();
}

#[test]
fn it_returns_error_for_invalid_coinbase_maturity() {
let test_params = TestParams::new();
let rules = test_helpers::create_consensus_manager();
let mut coinbase = test_helpers::create_unblinded_coinbase(&test_params, 1);
coinbase.features.maturity = 0;
let coinbase_output = coinbase.as_transaction_output(&CryptoFactories::default()).unwrap();
let err = check_coinbase_maturity(&rules, 1, &coinbase_output).unwrap_err();
unpack_enum!(ValidationError::TransactionError(err) = err);
unpack_enum!(TransactionError::InvalidCoinbaseMaturity = err);
}
}

mod check_coinbase_reward {

use super::*;

#[test]
fn it_succeeds_for_valid_coinbase() {
let test_params = TestParams::new();
let rules = test_helpers::create_consensus_manager();
let coinbase = test_helpers::create_unblinded_coinbase(&test_params, 1);
let coinbase_output = coinbase.as_transaction_output(&CryptoFactories::default()).unwrap();
let coinbase_kernel = test_helpers::create_coinbase_kernel(&coinbase.spending_key);
check_coinbase_reward(
&CommitmentFactory::default(),
&rules,
1,
0.into(),
&coinbase_kernel,
&coinbase_output,
)
.unwrap();
}

#[test]
fn it_returns_error_for_invalid_coinbase_reward() {
let test_params = TestParams::new();
let rules = test_helpers::create_consensus_manager();
let mut coinbase = test_helpers::create_unblinded_coinbase(&test_params, 1);
coinbase.value = 123.into();
let coinbase_output = coinbase.as_transaction_output(&CryptoFactories::default()).unwrap();
let coinbase_kernel = test_helpers::create_coinbase_kernel(&coinbase.spending_key);
let err = check_coinbase_reward(
&CommitmentFactory::default(),
&rules,
1,
0.into(),
&coinbase_kernel,
&coinbase_output,
)
.unwrap_err();
unpack_enum!(ValidationError::TransactionError(err) = err);
unpack_enum!(TransactionError::InvalidCoinbase = err);
}
}
}
2 changes: 1 addition & 1 deletion base_layer/core/tests/block_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@ async fn test_block_sync_body_validator() {
let (coinbase_utxo, coinbase_kernel, _) = create_coinbase(
&factories,
rules.get_block_reward_at(1) + tx01.body.get_total_fee() + tx02.body.get_total_fee(),
1,
1 + rules.consensus_constants(1).coinbase_lock_height(),
);
let template = chain_block_with_coinbase(
&genesis,
Expand Down
2 changes: 1 addition & 1 deletion base_layer/core/tests/helpers/block_builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ pub fn chain_block_with_new_coinbase(
let (coinbase_utxo, coinbase_kernel, coinbase_output) = create_coinbase(
factories,
coinbase_value,
height + consensus_manager.consensus_constants(0).coinbase_lock_height(),
height + consensus_manager.consensus_constants(height).coinbase_lock_height(),
);
let mut header = BlockHeader::from_previous(prev_block.header());
header.height = height;
Expand Down