Skip to content

Commit

Permalink
Starting with representing the mempool in a struct
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielgusn committed Apr 25, 2024
1 parent ca50bc8 commit 8c9d6c8
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 77 deletions.
10 changes: 5 additions & 5 deletions src/block/block.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![allow(dead_code, unused)]

use super::block_header::{self, BlockHeader};
use crate::transactions::{self, tx::Tx};
use super::block_header::BlockHeader;
use crate::transactions::tx::Tx;
use core::fmt;
#[derive(Debug)]
pub struct Block{
Expand All @@ -19,8 +19,8 @@ impl Block {
}
}

fn get_block_header_hash() -> String {
String::from("Hello World!")
fn get_block_header_hash(&self) -> String {
self.block_header.get_block_header_sha256sum()
}

pub fn get_block_size(&self) -> u64 {
Expand All @@ -35,7 +35,7 @@ impl Block {
pub fn proof_of_work(&mut self){
loop {
if self.block_header.get_block_header_sha256sum() < self.block_header.target_hash {
println!("\tFound the nonce for the target Hash! It is: {} and you can attach this block to the blockchain\n\t Block Hash is: {}", self.block_header.nonce, self.block_header.get_block_header_sha256sum());
println!("\tFound the nonce for the target Hash! It is: {} and you can attach this block to the blockchain\n\t Block Hash is: {}\n", self.block_header.nonce, self.block_header.get_block_header_sha256sum());
break
}
// println!("Not yet! ({})", self.block_header.get_block_header_sha256sum());
Expand Down
79 changes: 15 additions & 64 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,68 +26,39 @@ pub fn read_mempool(path: &str){
mempool.push(transaction);
}

let mut teste: String = String::from("teste");
teste.push('a');

println!("teste eh {}", teste);

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

mempool.sort_by_key(|tx| tx.calculate_tx_fee());
mempool.sort_by_key(|tx| tx.get_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());
println!("Fee:{}", mempool[0].get_tx_fee());
println!("Fee:{}", mempool[1].get_tx_fee());
println!("Fee:{}", mempool[2].get_tx_fee());
// is_coinbase(tx_in_json);
}

pub fn read_tx_from_file(file_path: &str) -> Tx {
let mut file_content: String = String::new();
let path = Path::new(&file_path);

let mut file = File::open(path).expect("Error while loading file");
file.read_to_string(&mut file_content).expect("File can not be read");
// let contents = fs::read_to_string(file_path)
// .expect("Error while reading file");

let error_in_file_message:String = String::from("Error while parsing json to Tx in file ") + file_path;

let tx_in_json: Tx = serde_json::from_str(&file_content).expect(&error_in_file_message);
// .expect("Error parsing file content to JSON");

return tx_in_json;
}

// 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];
// let tx_vout = &tx_json["vout"][0];

// let mut tx_input_vec: Vec<TxInput> = vec![];
// let mut tx_output_vec: Vec<TxOutput> = vec![];

// let tx_input: TxInput = TxInput::new(tx_vin["txid"].to_string(), tx_vin["prevout"]["value"].as_u64().expect("Error while casting tx_in value to u64"), tx_vin["scriptsig"].to_string(), tx_vin["is_coinbase"].as_bool().expect("Error while casting tx_in is_coinbase"));

// let tx_output: TxOutput = TxOutput::new(tx_vout["value"].as_u64().expect("Error while casting tx_out value to u64"), tx_vout["scriptpubkey"].to_string());

// tx_input_vec.push(tx_input);
// tx_output_vec.push(tx_output);

// Tx::new(tx_json["version"].as_u64().expect("Error while parsing tx version to u64") as u32, tx_input_vec, tx_output_vec)
// }

pub fn is_coinbase(tx: serde_json::Value) -> bool {
let tx_input = &tx["vin"];
if tx_input[0]["is_coinbase"].to_string() == "true"{
println!("{}", tx_input[0]["txid"]);
}
// println!("{}", type_name_of_val(&tx_input[0]["is_coinbase"]));
// println!("{}", tx_input);
// println!("{:?}", tx_input[0]["is_coinbase"]);
// println!("{}", type_name_of_val(&tx));
// tx.as_array().map(
// println!("{}", type_name_of_val(tx_input))
// );
return true
}

fn get_files_in_directory(path: &str) -> io::Result<Vec<String>> {
// Get a list of all entries in the folder
let entries = fs::read_dir(path)?;
Expand All @@ -105,24 +76,4 @@ fn get_files_in_directory(path: &str) -> io::Result<Vec<String>> {
.collect();

Ok(file_names)
}

// THIS FUNCTION IS NOT WORKING
// pub fn get_files_in_directory(dir_path: &str) -> io::Result<Vec<String>> {

// let entries = fs::read_dir(dir_path)
// .expect("Error while reading directory");

// let file_names: Vec<String> = entries
// .filter_map(|entry| {
// let path = entry.ok()?.path();
// if path.is_file() {
// path.file_name()?.to_str().map(|s| s.to_owned())
// } else {
// None
// }
// })
// .collect();

// Ok(file_names);
// }
}
52 changes: 52 additions & 0 deletions src/mempool/mempool.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@

#![allow(dead_code, unused)]

use crate::transactions::tx::Tx;
use mining_challenge::{get_files_in_directory};

pub struct Mempool {
mempool_txs: Vec<MempoolTx>,
}

impl Mempool{
pub fn new(mempool_txs: Vec<MempoolTx>) -> Self {
Self {
mempool_txs,
}
}

}

pub fn get_mempool_from_dir(dir_path: &str) -> Mempool {
let files: Vec<String> = get_files_in_directory(dir_path).expect("Error while reading mempool directory");

let mut mempool: Vec<MempoolTx> = vec![];

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

let transaction: Tx = read_tx_from_file(&file_path);

let mempool_tx: MempoolTx = MempoolTx::new(transaction);

mempool.push(mempool_tx);
}

return mempool;
}

struct MempoolTx {
default_tx: Tx,
tx_size: u64,
tx_fee: u64,
}

impl MempoolTx{
pub fn new(tx: Tx) -> Self {
Self {
default_tx,
tx_size: tx.get_tx_size_in_bits(),
tx_fee: tx.get_tx_fee(),
}
}
}
1 change: 1 addition & 0 deletions src/mempool/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod mempool;
20 changes: 12 additions & 8 deletions src/transactions/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl Tx{
}
}

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

Expand All @@ -46,7 +46,7 @@ impl Tx{
return inputs_total - outputs_total;
}

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

Expand Down Expand Up @@ -101,7 +101,7 @@ pub struct TxInput{
}

impl TxInput{

pub fn new(txid: String,vout: u32,prevout: TxPrevOut,scriptsig: String,scriptsig_asm: String,witness: Vec<String>,is_coinbase: bool,sequence: u64,) -> Self{
Self{
txid,
Expand All @@ -114,15 +114,15 @@ impl TxInput{
sequence,
}
}

pub fn get_tx_input_size_in_bits(&self) -> u64{
let mut tx_input_size: u64 = 32 + 64 + 1;

let txid_size: u64 = self.txid.len() as u64 * 32;
let prevout_size: u64 = self.prevout.get_prevout_size_in_bytes();
let scriptsig_size: u64 = self.scriptsig.len() as u64 * 32;
let scriptsig_asm_size: u64 = self.scriptsig_asm.len() as u64 * 32;

let mut witness_size: u64 = match self.witness.clone() {
Some(witness_vec) => {
let mut witness_vec_strings_size: u64 = 0;
Expand All @@ -133,11 +133,15 @@ impl TxInput{
},
None => 0
};

tx_input_size += txid_size + prevout_size + scriptsig_size + scriptsig_asm_size + witness_size;

return tx_input_size;
}

pub fn is_coinbase(&self) -> bool {
self.is_coinbase
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down

0 comments on commit 8c9d6c8

Please sign in to comment.