-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
SecureMerkleTrie.sol
50 lines (46 loc) · 2.17 KB
/
SecureMerkleTrie.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { MerkleTrie } from "src/libraries/trie/MerkleTrie.sol";
/// @title SecureMerkleTrie
/// @notice SecureMerkleTrie is a thin wrapper around the MerkleTrie library that hashes the input
/// keys. Ethereum's state trie hashes input keys before storing them.
library SecureMerkleTrie {
/// @notice Verifies a proof that a given key/value pair is present in the Merkle trie.
/// @param _key Key of the node to search for, as a hex string.
/// @param _value Value of the node to search for, as a hex string.
/// @param _proof Merkle trie inclusion proof for the desired node. Unlike traditional Merkle
/// trees, this proof is executed top-down and consists of a list of RLP-encoded
/// nodes that make a path down to the target node.
/// @param _root Known root of the Merkle trie. Used to verify that the included proof is
/// correctly constructed.
/// @return valid_ Whether or not the proof is valid.
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes[] memory _proof,
bytes32 _root
)
internal
pure
returns (bool valid_)
{
bytes memory key = _getSecureKey(_key);
valid_ = MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
/// @notice Retrieves the value associated with a given key.
/// @param _key Key to search for, as hex bytes.
/// @param _proof Merkle trie inclusion proof for the key.
/// @param _root Known root of the Merkle trie.
/// @return value_ Value of the key if it exists.
function get(bytes memory _key, bytes[] memory _proof, bytes32 _root) internal pure returns (bytes memory value_) {
bytes memory key = _getSecureKey(_key);
value_ = MerkleTrie.get(key, _proof, _root);
}
/// @notice Computes the hashed version of the input key.
/// @param _key Key to hash.
/// @return hash_ Hashed version of the key.
function _getSecureKey(bytes memory _key) private pure returns (bytes memory hash_) {
hash_ = abi.encodePacked(keccak256(_key));
}
}