forked from bitcoin-dev-project/rust-for-bitcoiners
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute_transaction_fee.rs
47 lines (40 loc) · 2.09 KB
/
compute_transaction_fee.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use bitcoin::{Block, OutPoint, Transaction, TxOut};
use bitcoincore_rpc::{json::{GetRawTransactionResult, GetRawTransactionResultVout}, Client, RpcApi};
struct TxId(String);
fn high_fee_transaction(block: Block, client: &Client) -> Option<TxId> {
let txs = block.txdata;
if txs.len() == 1 {
return None; // Only coinbase transaction
}
let mut max_fee = 0;
let mut max_fee_txid = "".to_owned();
for tx in txs {
// Find the total value of outputs
// let total = tx.output.iter().map(|txout| txout.value.to_sat()).sum();
let total_output_value: u64 = tx.output.iter().fold(0, |acc, txout| acc + txout.value.to_sat());
// Find the total value of inputs
let mut total_input_value: u64 = 0;
tx.input.iter().for_each(|txin| {
let previous_outpoint: OutPoint = txin.previous_output;
let previous_transaction: Transaction = client
.get_raw_transaction(&previous_outpoint.txid, None)
.expect("The bitcoin node does not support transaction indexing or the given block has invalid data");
let previous_output: &TxOut = &previous_transaction.output[previous_outpoint.vout as usize];
total_input_value += previous_output.value.to_sat();
});
// let total_input_value: u64 = tx.input.iter().map(|txin| {
// let previous_outpoint = txin.previous_output;
// let previous_transaction: GetRawTransactionResult = client
// .get_raw_transaction_info(&previous_outpoint.txid, None)
// .expect("The bitcoin node does not support transaction indexing or the given block has invalid data");
// let previous_output: &GetRawTransactionResultVout = &previous_transaction.vout[previous_outpoint.vout as usize];
// previous_output.value.to_sat() // input value of this txin
// }).sum();
let fee = total_input_value - total_output_value;
if fee > max_fee {
max_fee = fee;
max_fee_txid = tx.txid().to_string();
}
}
Some(TxId(max_fee_txid))
}