Skip to content

Commit df55e1a

Browse files
author
Ivo Georgiev
authored
Merge pull request #169 from samparsky/issue-168-fix-merkle-tree-bug
Issue 168 fix merkle tree bug
2 parents 8f2cdcc + d51970e commit df55e1a

File tree

2 files changed

+44
-10
lines changed

2 files changed

+44
-10
lines changed

primitives/src/merkle_tree.rs

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,19 @@ impl Algorithm<MerkleItem> for KeccakAlgorithm {
5353
}
5454

5555
fn node(&mut self, left: MerkleItem, right: MerkleItem, _height: usize) -> MerkleItem {
56-
let left_vec: Vec<u8> = left.to_vec();
57-
let right_vec: Vec<u8> = right.to_vec();
58-
59-
let mut node_vec = vec![left_vec, right_vec];
60-
node_vec.sort();
61-
62-
let flatten_node_vec: Vec<u8> = node_vec.into_iter().flatten().collect();
56+
// This is a check for odd number of leaves items
57+
// left == right since the right is a duplicate of left
58+
// return the item unencoded as the JS impl
59+
if left == right {
60+
left
61+
} else {
62+
let mut node_vec = vec![left.to_vec(), right.to_vec()];
63+
node_vec.sort();
6364

64-
self.write(&flatten_node_vec);
65-
self.hash()
65+
let flatten_node_vec: Vec<u8> = node_vec.into_iter().flatten().collect();
66+
self.write(&flatten_node_vec);
67+
self.hash()
68+
}
6669
}
6770
}
6871

@@ -183,4 +186,36 @@ mod test {
183186

184187
assert_eq!(verify, true, "should verify proof successfully");
185188
}
189+
190+
#[test]
191+
fn it_generates_correct_merkle_tree_with_odd_leaves() {
192+
let h1 = <[u8; 32]>::from_hex(
193+
"13c21db99584c9bb3e9ad98061f6ca39364049b328b74822be6303a4da18014d",
194+
)
195+
.unwrap();
196+
let h2 = <[u8; 32]>::from_hex(
197+
"b1bea7b8b58cd47d475bfe07dbe6df33f50f7a76957c51cebe8254257542fd7d",
198+
)
199+
.unwrap();
200+
201+
let h3 = <[u8; 32]>::from_hex(
202+
"c455ef23d4db0091e1e25ef5d652a2832a1fc4fa82b8e66c290a692836e0cbe6",
203+
)
204+
.unwrap();
205+
206+
// odd leaves
207+
let top = MerkleTree::new(&[h1, h2, h3]);
208+
209+
let root = hex::encode(&top.root());
210+
211+
assert_eq!(
212+
root, "e68ea33571084e5dea276b089a10fa7be9d59accf3d7838c0d9b050bf72634a1",
213+
"should generate the correct root"
214+
);
215+
216+
let proof = top.proof(0);
217+
let verify = top.verify(proof);
218+
219+
assert_eq!(verify, true, "should verify proof successfully");
220+
}
186221
}

validator_worker/src/follower.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ async fn on_new_state<'a, A: Adapter + 'static>(
6060
) -> Result<NewStateResult, Box<dyn Error>> {
6161
let proposed_balances = new_state.balances.clone();
6262
let proposed_state_root = new_state.state_root.clone();
63-
6463
if proposed_state_root != hex::encode(get_state_root_hash(&iface, &proposed_balances)?) {
6564
return Ok(on_error(&iface, &new_state, InvalidNewState::RootHash).await);
6665
}

0 commit comments

Comments
 (0)