Calculates the Merkle root given a leaf transaction ID (`txid`, which is a `mid_state_txid`) and the Merkle proof path (sibling nodes from the "mid-state" tree). The core of the SPV security enhancement is here: Each `merkle_proof` element (a sibling node from the mid-state tree) is first hashed with `calculate_sha256`. This transformed hash is then used in the standard Bitcoin Merkle combination
(&self, txid: [u8; 32])
| 237 | /// from the leaf transaction IDs, preventing cross-interpretation and related attacks. |
| 238 | /// The final hash should be the main Bitcoin block Merkle root. |
| 239 | pub fn get_root(&self, txid: [u8; 32]) -> [u8; 32] { |
| 240 | // txid is the leaf (e.g., mid_state_txid) |
| 241 | let mut preimage: [u8; 64] = [0; 64]; |
| 242 | let mut combined_hash: [u8; 32] = txid; // Start with the leaf txid |
| 243 | let mut index = self.idx; |
| 244 | let mut level: u32 = 0; |
| 245 | while level < self.merkle_proof.len() as u32 { |
| 246 | // Get the sibling node from the mid-state tree proof path |
| 247 | let mid_state_sibling_node = self.merkle_proof[level as usize]; |
| 248 | // Secure SPV step: transform the mid-state sibling node by SHA256-ing it |
| 249 | // before using it in the double-SHA256 combination. |
| 250 | let processed_sibling_hash = calculate_sha256(&mid_state_sibling_node); |
| 251 | |
| 252 | if index % 2 == 0 { |
| 253 | // `combined_hash` is the left child |
| 254 | preimage[..32].copy_from_slice(&combined_hash); |
| 255 | preimage[32..].copy_from_slice(&processed_sibling_hash); // Use the SHA256'd mid-state sibling |
| 256 | combined_hash = calculate_double_sha256(&preimage); |
| 257 | } else { |
| 258 | // `combined_hash` is the right child |
| 259 | preimage[..32].copy_from_slice(&processed_sibling_hash); // Use the SHA256'd mid-state sibling |
| 260 | preimage[32..].copy_from_slice(&combined_hash); |
| 261 | combined_hash = calculate_double_sha256(&preimage); |
| 262 | } |
| 263 | level += 1; |
| 264 | index /= 2; |
| 265 | } |
| 266 | combined_hash // This should be the Bitcoin block's Merkle root |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// Verifies a Merkle proof against a given root using the "mid-state" tree approach. |
no test coverage detected