Skip to content

Commit

Permalink
Implementation for calculating the transaction fee
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielgusn committed Apr 24, 2024
1 parent f22304e commit aeacd00
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 12 deletions.
37 changes: 25 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,27 @@ pub fn read_mempool(path: &str){

let tx = read_tx_from_file("/home/gabriel/projects/bitcoin-mining-challenge/mempool/0.json");

// for file in files{
// let file_path = path.to_string() + &file;
// // let file: File = File::create(&file_path).unwrap();
// // let file_size = fs::metadata(&file_path).expect("Falha ao ler o arquivo");
// // file.sync_all();
// // println!("Size: {} File: {}", file);
// let transaction_json: Tx = read_tx_from_file(file_path);

// // let tx: Tx = convert_json_tx_to_struct(transaction_json);
// println!("{:?}", transaction_json.get_tx_size());

// }
let mut mempool: Vec<Tx> = vec![];

for file in files{
let file_path = path.to_string() + &file;

let transaction: Tx = read_tx_from_file(&file_path);

mempool.push(transaction);
}

println!("Before sorting");
println!("Fee:{}", mempool[0].calculate_tx_fee());
println!("Fee:{}", mempool[1].calculate_tx_fee());
println!("Fee:{}", mempool[2].calculate_tx_fee());

mempool.sort_by_key(|tx| tx.calculate_tx_fee());
mempool.reverse();
println!("After sorting");
println!("Fee:{}", mempool[0].calculate_tx_fee());
println!("Fee:{}", mempool[1].calculate_tx_fee());
println!("Fee:{}", mempool[2].calculate_tx_fee());
// is_coinbase(tx_in_json);
}

Expand All @@ -46,6 +55,10 @@ pub fn read_tx_from_file(file_path: &str) -> Tx {
return tx_in_json;
}

pub fn sort_txs_by_fee(mut txs: Vec<Tx>){
txs.sort_by_key(|tx| tx.calculate_tx_fee());
}

// TODO: this function is with a problem that all the strings are coming with "\".......\""
// pub fn convert_json_tx_to_struct(tx_json: serde_json::Value) -> Tx {
// let tx_vin = &tx_json["vin"][0];
Expand Down
14 changes: 14 additions & 0 deletions src/transactions/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ impl Tx{
}
}

pub fn calculate_tx_fee(&self) -> u64 {
let mut inputs_total: u64 = 0;
let mut outputs_total: u64 = 0;

for inputs in &self.tx_input{
inputs_total += inputs.prevout.value;
}
for outputs in &self.tx_output{
outputs_total += outputs.value;
}

return inputs_total - outputs_total;
}

pub fn get_tx_hash(&self) -> String{
let serialized_tx = format!("{:?}", self);
let mut hasher = Sha256::new();
Expand Down

0 comments on commit aeacd00

Please sign in to comment.