olisystems / BEST-Energy

Integritee off-chain worker and sidechain validateer
Apache License 2.0
2 stars 0 forks source link

Create hash of market clearing operation #6

Closed clangenb closed 1 year ago

clangenb commented 1 year ago

We use this function of to create merkle roots of extrinsics upstream: https://github.com/integritee-network/worker/blob/aeb303826d286bb399f1dc2a5fcbfdb9964e5201/core/parentchain/indirect-calls-executor/src/indirect_calls_executor.rs#L142.

Looking at the function in merkle-tree.

/// Construct a root hash of a Binary Merkle Tree created from given leaves.
///
/// See crate-level docs for details about Merkle Tree construction.
///
/// In case an empty list of leaves is passed the function returns a 0-filled hash.
pub fn merkle_root<H, I>(leaves: I) -> H::Output
where
    H: HashT,
    H::Output: Default + AsRef<[u8]>,
    I: IntoIterator,
    I::Item: AsRef<[u8]>,
{
    let iter = leaves.into_iter().map(|l| <H as HashT>::hash(l.as_ref()));
    merkelize::<H, _, _>(iter, &mut ()).into()
}

The traitbounds look a bit scary, but what they essentially means is that you can supply any kind of vec/array/slice that contains u8s. Calling it the same way as in our code, where we use the Keccak256 hasher, this function will hash the leaves with sha3. So I expect to see something like this in your code:

// your set of orders
let orders: Vec<Orders> = myOrders;
let orders_encoded: Vec<Vec<u8>> = myOrders.into_iter().map(|o| o.encode()).collect();

let root: H256 = merkle_root::<Keccak256, _>(orders_encoded);

I would suggest that you might look at the tests here to see how to use the library to create merkle proofs and verify them: https://github.com/paritytech/substrate/blob/5d0867c7dcdc50572422611128853ccff63ebd4d/utils/binary-merkle-tree/src/lib.rs#L353

clangenb commented 1 year ago

Done