Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(merkle-tree): Contract with tests #228

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Scarb.lock
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ version = "0.1.0"
name = "mappings"
version = "0.1.0"

[[package]]
name = "merkle_tree"
version = "0.1.0"

[[package]]
name = "nft_dutch_auction"
version = "0.1.0"
Expand Down
1 change: 1 addition & 0 deletions listings/applications/merkle_tree/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
target
12 changes: 12 additions & 0 deletions listings/applications/merkle_tree/Scarb.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "merkle_tree"
version.workspace = true
edition = '2023_11'

[dependencies]
starknet.workspace = true

[scripts]
test.workspace = true

[[target.starknet-contract]]
134 changes: 134 additions & 0 deletions listings/applications/merkle_tree/src/contract.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
use core::poseidon::PoseidonTrait;
use core::hash::{HashStateTrait};
use core::poseidon::poseidon_hash_span;

#[generate_trait]
pub impl ByteArrayHashTraitImpl of ByteArrayHashTrait {
fn hash(self: @ByteArray) -> felt252 {
let mut serialized_byte_arr: Array<felt252> = ArrayTrait::new();
self.serialize(ref serialized_byte_arr);

let mut hash = PoseidonTrait::new().update(poseidon_hash_span(serialized_byte_arr.span()));

hash.finalize()
}
}
hudem1 marked this conversation as resolved.
Show resolved Hide resolved

#[starknet::interface]
pub trait IMerkleTree<TContractState> {
fn build_tree(ref self: TContractState, data: Array<ByteArray>) -> Array<felt252>;
fn get_root(self: @TContractState) -> felt252;
// function to verify if leaf node exists in the merkle tree
fn verify(
self: @TContractState, proof: Array<felt252>, root: felt252, leaf: felt252, index: usize
) -> bool;
}

mod Errors {
hudem1 marked this conversation as resolved.
Show resolved Hide resolved
pub const NOT_POW_2: felt252 = 'Data length is not a power of 2';
pub const NOT_PRESENT: felt252 = 'No element in merkle tree';
}

#[starknet::contract]
pub mod MerkleTree {
use core::poseidon::PoseidonTrait;
use core::hash::{HashStateTrait, HashStateExTrait};
use super::ByteArrayHashTrait;

#[storage]
struct Storage {
// cannot store Array, therefore use a LegacyMap to simulate an array
hashes: LegacyMap::<usize, felt252>,
hashes_length: usize
}

#[derive(Drop, Serde, Copy)]
struct Vec2 {
x: u32,
y: u32
}

#[abi(embed_v0)]
impl IMerkleTreeImpl of super::IMerkleTree<ContractState> {
fn build_tree(ref self: ContractState, mut data: Array<ByteArray>) -> Array<felt252> {
let data_len = data.len();
assert(data_len > 0 && (data_len & (data_len - 1)) == 0, super::Errors::NOT_POW_2);

let mut _hashes: Array<felt252> = ArrayTrait::new();
hudem1 marked this conversation as resolved.
Show resolved Hide resolved

// first, hash every leaf
let mut i = 0;
while let Option::Some(value) = data
.pop_front() {
_hashes.append(value.hash());

i += 1;
};

// then, hash all levels above leaves
let mut current_nodes_lvl_len = data_len;
let mut hashes_offset = 0;

while current_nodes_lvl_len > 0 {
let mut i = 0;
while i < current_nodes_lvl_len
- 1 {
let left_elem = *_hashes.at(hashes_offset + i);
let right_elem = *_hashes.at(hashes_offset + i + 1);

let hash = PoseidonTrait::new()
.update_with((left_elem, right_elem))
.finalize();
_hashes.append(hash);

i += 2;
};

hashes_offset += current_nodes_lvl_len;
current_nodes_lvl_len /= 2;
};

// write to the contract state (useful for the get_root function)
let mut i = 0;
let hashes_span = _hashes.span();
while i < hashes_span.len() {
self.hashes.write(i, *hashes_span.at(i));
i += 1;
};
self.hashes_length.write(hashes_span.len());
hudem1 marked this conversation as resolved.
Show resolved Hide resolved

_hashes
}

fn get_root(self: @ContractState) -> felt252 {
let merkle_tree_length = self.hashes_length.read();
assert(merkle_tree_length > 0, super::Errors::NOT_PRESENT);

self.hashes.read(merkle_tree_length - 1)
}

fn verify(
self: @ContractState,
mut proof: Array<felt252>,
root: felt252,
leaf: felt252,
mut index: usize
) -> bool {
let mut current_hash = leaf;

while let Option::Some(value) = proof
.pop_front() {
current_hash =
if index % 2 == 0 {
PoseidonTrait::new().update_with((current_hash, value)).finalize()
} else {
PoseidonTrait::new().update_with((value, current_hash)).finalize()
};

index /= 2;
};

current_hash == root
}
}
}
4 changes: 4 additions & 0 deletions listings/applications/merkle_tree/src/lib.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
mod contract;

#[cfg(test)]
mod tests;
189 changes: 189 additions & 0 deletions listings/applications/merkle_tree/src/tests.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
use merkle_tree::contract::MerkleTree::__member_module_hashes::InternalContractMemberStateTrait as HashesInt;
use merkle_tree::contract::MerkleTree::__member_module_hashes_length::InternalContractMemberStateTrait as HashesLenInt;
use merkle_tree::contract::IMerkleTreeDispatcherTrait;
use merkle_tree::contract::{IMerkleTreeDispatcher, MerkleTree, ByteArrayHashTrait};
use starknet::syscalls::deploy_syscall;
use starknet::{ContractAddress, SyscallResultTrait};
use starknet::testing::set_contract_address;
use core::poseidon::PoseidonTrait;
use core::hash::{HashStateTrait, HashStateExTrait};

fn deploy_util(class_hash: felt252, calldata: Array<felt252>) -> ContractAddress {
let (address, _) = deploy_syscall(class_hash.try_into().unwrap(), 0, calldata.span(), false)
.unwrap_syscall();

address
}

fn setup() -> IMerkleTreeDispatcher {
let contract_address = deploy_util(MerkleTree::TEST_CLASS_HASH, array![]);

IMerkleTreeDispatcher { contract_address }
}

#[test]
#[available_gas(20000000)]
fn should_deploy() {
let deploy = setup();

let state = MerkleTree::contract_state_for_testing();
// "link" a new MerkleTree struct to the deployed MerkleTree contract
// in order to access its internal state fields for assertions
set_contract_address(deploy.contract_address);

assert_eq!(state.hashes_length.read(), 0);
}

#[test]
#[available_gas(20000000)]
fn build_tree_succeeds() {
/// Set up
let deploy = setup();

let data_1 = "alice -> bob: 2";
let data_2 = "bob -> john: 5";
let data_3 = "alice -> john: 1";
let data_4 = "john -> alex: 8";
let arguments = array![data_1.clone(), data_2.clone(), data_3.clone(), data_4.clone()];

/// When
let actual_hashes = deploy.build_tree(arguments);

/// Then
let mut expected_hashes: Array<felt252> = array![];

// leaves' hashes
expected_hashes.append(data_1.hash());
expected_hashes.append(data_2.hash());
expected_hashes.append(data_3.hash());
expected_hashes.append(data_4.hash());

// hashes for level above leaves
let hash_0 = PoseidonTrait::new()
.update_with((*expected_hashes.at(0), *expected_hashes.at(1)))
.finalize();
let hash_1 = PoseidonTrait::new()
.update_with((*expected_hashes.at(2), *expected_hashes.at(3)))
.finalize();
expected_hashes.append(hash_0);
expected_hashes.append(hash_1);

// root hash
let root_hash = PoseidonTrait::new().update_with((hash_0, hash_1)).finalize();
expected_hashes.append(root_hash);

// verify returned result
assert_eq!(actual_hashes, expected_hashes);

// verify get_root
assert_eq!(deploy.get_root(), root_hash);

// verify contract storage state

let state = MerkleTree::contract_state_for_testing();
// "link" a new MerkleTree struct to the deployed MerkleTree contract
// in order to access its internal state fields for assertions
set_contract_address(deploy.contract_address);

assert_eq!(state.hashes_length.read(), expected_hashes.len());

let mut i = 0;
while i < expected_hashes
.len() {
assert_eq!(state.hashes.read(i), *expected_hashes.at(i));
i += 1;
};
}

#[test]
#[available_gas(20000000)]
#[should_panic(expected: ('Data length is not a power of 2', 'ENTRYPOINT_FAILED'))]
fn build_tree_fails() {
/// Set up
let deploy = setup();

let data_1 = "alice -> bob: 2";
let data_2 = "bob -> john: 5";
let data_3 = "alice -> john: 1";
// number of arguments not a power of 2
let arguments = array![data_1, data_2, data_3];

/// When
deploy.build_tree(arguments);
}

#[test]
#[available_gas(20000000)]
fn verify_leaf_succeeds() {
/// Set up
let deploy = setup();

let data_1 = "bob -> alice: 1";
let data_2 = "alex -> john: 3";
let data_3 = "alice -> alex: 8";
let data_4 = "alex -> bob: 8";
let arguments = array![data_1.clone(), data_2.clone(), data_3.clone(), data_4.clone()];

let hashes = deploy.build_tree(arguments);

// ----> hashes tree :
//
// hashes[6]
// / \
// hashes[4] hashes[5]
// / \ / \
// hashes[0] hashes[1] hashes[2] hashes[3]

let res = deploy
.verify(
array![*hashes.at(3), *hashes.at(4)], // proof
*hashes.at(6), // root
data_3.hash(), // leaf
2 // leaf index
);

assert(res, 'Leaf should be in merkle tree');
}

#[test]
#[available_gas(20000000)]
fn verify_leaf_fails() {
/// Set up
let deploy = setup();

let data_1 = "bob -> alice: 1";
let data_2 = "alex -> john: 3";
let data_3 = "alice -> alex: 8";
let data_4 = "alex -> bob: 8";
let arguments = array![data_1.clone(), data_2.clone(), data_3.clone(), data_4.clone()];

let hashes = deploy.build_tree(arguments);

// ----- hashes tree -----
// hashes[6]
// / \
// hashes[4] hashes[5]
// / \ / \
// hashes[0] hashes[1] hashes[2] hashes[3]

let wrong_leaf: ByteArray = "alice -> alex: 9";
let res = deploy
.verify(
array![*hashes.at(3), *hashes.at(4)], // proof
*hashes.at(6), // root
wrong_leaf.hash(), // leaf
2 // leaf index
);
assert(!res, '1- Leaf should NOT be in tree');

let wrong_proof = array![*hashes.at(4), *hashes.at(3)];
let res = deploy
.verify(
wrong_proof, // proof
*hashes.at(6), // root
data_3.hash(), // leaf
2 // leaf index
);
assert(!res, '2- Leaf should NOT be in tree');
}

1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Summary
- [Constant Product AMM](./applications/constant-product-amm.md)
- [TimeLock](./applications/timelock.md)
- [Staking](./applications/staking.md)
- [Merkle Tree](./applications/merkle_tree.md)
- [Simple Storage with Starknet-js](./applications/simple_storage_starknetjs.md)

<!-- advanced-concepts -->
Expand Down
Loading