Skip to content

Commit

Permalink
merkle root calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
stojanov-igor committed Oct 21, 2024
1 parent 8cd1f36 commit 3584ccf
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions jam/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,31 @@ impl Block {
block
}

// Merkle root calculation for the block's transactions
fn calculate_state_root(transactions: &[Transaction]) -> String {
// Placeholder implementation, should calculate the state root based on the transactions
let state_data: String = transactions.iter().map(|tx| tx.tx_hash.clone()).collect();
sha256(&state_data)
if transactions.is_empty() {
return sha256("");
}
let tx_hashes: Vec<String> = transactions.iter().map(|tx| tx.tx_hash.clone()).collect();
Self::compute_merkle_root(tx_hashes)
}

fn compute_merkle_root(mut leaves: Vec<String>) -> String {
if leaves.len() == 1 {
return leaves[0].clone();
}

if leaves.len() % 2 != 0 {
leaves.push(leaves.last().unwrap().clone()); // Duplicate the last hash if odd number of leaves
}

let mut new_level = Vec::new();
for i in (0..leaves.len()).step_by(2) {
let combined = format!("{}{}", leaves[i], leaves[i + 1]);
new_level.push(sha256(&combined));
}

Self::compute_merkle_root(new_level)
}

pub fn calculate_hash(&self) -> String {
Expand Down Expand Up @@ -93,8 +114,9 @@ impl Block {
Ok(())
}

// Verify that the recomputed Merkle root matches the stored state_root
fn verify_merkle_root(&self) -> bool {
// Placeholder for actual Merkle root verification logic
true
let recomputed_root = Self::calculate_state_root(&self.transactions);
recomputed_root == self.state_root
}
}

0 comments on commit 3584ccf

Please sign in to comment.