Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: allow zero fees for pre-mine #6595

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
50 changes: 34 additions & 16 deletions applications/minotari_console_wallet/src/automation/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1252,7 +1252,11 @@ pub async fn command_runner(

match encumber_aggregate_utxo(
transaction_service.clone(),
session_info.fee_per_gram,
if session_info.use_pre_mine_input_file {
MicroMinotari::zero()
} else {
session_info.fee_per_gram
},
embedded_output.commitment.clone(),
input_shares,
script_signature_public_nonces,
Expand Down Expand Up @@ -1576,6 +1580,7 @@ pub async fn command_runner(
}

// Create finalized spend transactions
let mut inputs = Vec::new();
let mut outputs = Vec::new();
let mut kernels = Vec::new();
for (indexed_info, leader_self) in party_info_per_index.iter().zip(leader_info.outputs_for_self.iter())
Expand Down Expand Up @@ -1605,22 +1610,17 @@ pub async fn command_runner(
break;
}

if args.print_to_console || args.save_to_file {
if session_info.use_pre_mine_input_file {
match transaction_service.get_any_transaction(leader_self.tx_id).await {
Ok(Some(WalletTransaction::Completed(tx))) => {
if args.save_to_file {
for output in tx.transaction.body.outputs() {
outputs.push(output.clone());
}
for kernel in tx.transaction.body.kernels() {
kernels.push(kernel.clone());
}
for input in tx.transaction.body.inputs() {
inputs.push(input.clone());
}
for output in tx.transaction.body.outputs() {
outputs.push(output.clone());
}
if args.print_to_console {
let tx_console = serde_json::to_string(&tx.transaction).unwrap_or_else(|_| {
format!("Transaction to json conversion error! ('{}')", leader_self.tx_id)
});
println!("Tx_Id: {}, Tx: {}", leader_self.tx_id, tx_console);
for kernel in tx.transaction.body.kernels() {
kernels.push(kernel.clone());
}
},
Ok(_) => {
Expand All @@ -1638,7 +1638,7 @@ pub async fn command_runner(
}
}

if args.save_to_file {
if session_info.use_pre_mine_input_file {
let file_name = get_pre_mine_addition_file_name();
let out_dir_path = out_dir(&args.session_id)?;
let out_file = out_dir_path.join(&file_name);
Expand All @@ -1651,6 +1651,24 @@ pub async fn command_runner(
};

let mut error = false;
for input in inputs {
let input_s = match serde_json::to_string(&input) {
Ok(val) => val,
Err(e) => {
eprintln!("\nError: Could not serialize UTXO ({})\n", e);
error = true;
break;
},
};
if let Err(e) = file_stream.write_all(format!("{}\n", input_s).as_bytes()) {
eprintln!("\nError: Could not write UTXO to file ({})\n", e);
error = true;
break;
}
}
if error {
break;
}
for output in outputs {
let utxo_s = match serde_json::to_string(&output) {
Ok(val) => val,
Expand Down Expand Up @@ -2405,7 +2423,7 @@ fn read_genesis_file_outputs(
}
file
} else {
return Err("Missing pre-mine file!".to_string());
return Err("Missing pre-mine file! Need '--pre-mine-file-path <path_to_file>.'".to_string());
};

let file = File::open(file_path.clone())
Expand Down
6 changes: 2 additions & 4 deletions applications/minotari_console_wallet/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,10 +281,6 @@ pub struct PreMineSpendAggregateTransactionArgs {
pub session_id: String,
#[clap(long)]
pub input_file_names: Vec<String>,
#[clap(long)]
pub save_to_file: bool,
#[clap(long)]
pub print_to_console: bool,
}

#[derive(Debug, Args, Clone)]
Expand All @@ -295,6 +291,8 @@ pub struct PreMineSpendBackupUtxoArgs {
pub output_index: usize,
#[clap(long)]
pub recipient_address: TariAddress,
#[clap(long)]
pub pre_mine_file_path: Option<PathBuf>,
}

#[derive(Debug, Args, Clone)]
Expand Down
15 changes: 13 additions & 2 deletions base_layer/core/src/blocks/genesis_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use crate::{
proof_of_work::{AccumulatedDifficulty, Difficulty, PowAlgorithm, PowData, ProofOfWork},
transactions::{
aggregated_body::AggregateBody,
transaction_components::{TransactionKernel, TransactionOutput},
transaction_components::{TransactionInput, TransactionKernel, TransactionOutput},
},
OutputSmt,
};
Expand All @@ -54,9 +54,12 @@ pub fn get_genesis_block(network: Network) -> ChainBlock {

fn add_pre_mine_utxos_to_genesis_block(file: &str, block: &mut Block) {
let mut utxos = Vec::new();
let mut inputs = Vec::new();
for line in file.lines() {
if let Ok(utxo) = serde_json::from_str::<TransactionOutput>(line) {
utxos.push(utxo);
} else if let Ok(input) = serde_json::from_str::<TransactionInput>(line) {
inputs.push(input);
} else if let Ok(kernel) = serde_json::from_str::<TransactionKernel>(line) {
block.body.add_kernel(kernel);
block.header.kernel_mmr_size += 1;
Expand All @@ -66,6 +69,7 @@ fn add_pre_mine_utxos_to_genesis_block(file: &str, block: &mut Block) {
}
block.header.output_smt_size += utxos.len() as u64;
block.body.add_outputs(utxos);
block.body.add_inputs(inputs);
block.body.sort();
}

Expand Down Expand Up @@ -647,7 +651,14 @@ mod test {
// Check that the pre_mine UTXOs balance (the pre_mine_value consensus constant is set correctly and pre_mine
// kernel is correct)

let utxo_sum = block.block().body.outputs().iter().map(|o| &o.commitment).sum();
let input_sum = block
.block()
.body
.inputs()
.iter()
.map(|o| &o.commitment().unwrap())
.sum();
let utxo_sum = block.block().body.outputs().iter().map(|o| &o.commitment).sum() - input_sum;
let kernel_sum = block.block().body.kernels().iter().map(|k| &k.excess).sum();

let db = create_new_blockchain_with_network(network);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ pub struct SenderTransactionInitializer<KM> {
fee: Fee,
key_manager: KM,
sender_address: TariAddress,
allow_zero_fees: bool,
}

pub struct BuildError<KM> {
Expand Down Expand Up @@ -137,6 +138,7 @@ where KM: TransactionKeyManagerInterface
tx_id: None,
sender_address: TariAddress::default(),
key_manager,
allow_zero_fees: false,
}
}

Expand All @@ -147,6 +149,13 @@ where KM: TransactionKeyManagerInterface
self
}

/// Set the fee per weight for the transaction. See (Fee::calculate)[Struct.Fee.html#calculate] for how the
/// absolute fee is calculated from the fee-per-gram value.
pub fn with_allow_zero_fees(&mut self, allow_zero_fees: bool) -> &mut Self {
self.allow_zero_fees = allow_zero_fees;
self
}

/// Set the sender's address
pub fn with_sender_address(&mut self, sender_address: TariAddress) -> &mut Self {
self.sender_address = sender_address;
Expand Down Expand Up @@ -521,7 +530,7 @@ where KM: TransactionKeyManagerInterface
"Build transaction with Fee: {}. Change: {}. Output: {:?}", total_fee, change, change_output,
);
// Some checks on the fee
if total_fee < Fee::MINIMUM_TRANSACTION_FEE {
if total_fee < Fee::MINIMUM_TRANSACTION_FEE && !self.allow_zero_fees {
return self.build_err("Fee is less than the minimum");
}
hansieodendaal marked this conversation as resolved.
Show resolved Hide resolved

Expand Down
8 changes: 6 additions & 2 deletions base_layer/wallet/src/output_manager_service/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1279,7 +1279,7 @@ where
output_hash, tx_id
))
})?,
UseOutput::AsProvided(val) => val,
UseOutput::AsProvided(ref val) => val.clone(),
};
if output.commitment != expected_commitment {
return Err(OutputManagerError::ServiceError(format!(
Expand Down Expand Up @@ -1386,7 +1386,7 @@ where
let fee = self.get_fee_calc();
let fee = fee.calculate(fee_per_gram, 1, 1, 1, metadata_byte_size);
let amount = input.value - fee;
trace!(target: LOG_TARGET, "encumber_aggregate_utxo: created script");
trace!(target: LOG_TARGET, "encumber_aggregate_utxo: created script, with fee {}", fee);

// Create sender transaction protocol builder with recipient data and no change
let mut builder = SenderTransactionProtocol::builder(
Expand All @@ -1396,6 +1396,10 @@ where
builder
.with_lock_height(0)
.with_fee_per_gram(fee_per_gram)
.with_allow_zero_fees(match use_output {
UseOutput::FromBlockchain(_) => false,
UseOutput::AsProvided(_) => true,
})
.with_kernel_features(KernelFeatures::empty())
.with_prevent_fee_gt_amount(self.resources.config.prevent_fee_gt_amount)
.with_input(input.clone())
Expand Down
Loading