Skip to content

Commit

Permalink
linted generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Amxx committed Jun 27, 2024
1 parent 2d87005 commit b85551a
Show file tree
Hide file tree
Showing 2 changed files with 230 additions and 128 deletions.
353 changes: 229 additions & 124 deletions scripts/generate/templates/MerkleProof.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,152 +24,257 @@ import {Hashes} from "./Hashes.sol";
`;

const errors = `\
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
`;

/* eslint-disable max-len */
const templateProof = ({ suffix, location, visibility, hashType, hashName = 'Hashes.commutativeKeccak256' }) => `\
/**
* @dev Returns true if a \`leaf\` can be proved to be a part of a Merkle tree
* defined by \`root\`. For this, a \`proof\` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in ${location} with ${hashType ? 'a custom' : 'the default'} hashing function.
*/
function verify${suffix}(${[
`bytes32[] ${location} proof`,
'bytes32 root',
'bytes32 leaf',
hashType && [hashType, hashName].join(' '),
]
.filter(Boolean)
.join(', ')}) internal ${visibility} returns (bool) {
return processProof(${['proof', 'leaf', hashType && hashName].filter(Boolean).join(', ')}) == root;
const templateProofDefault = ({ suffix, location, visibility }) => `\
/**
* @dev Returns true if a \`leaf\` can be proved to be a part of a Merkle tree
* defined by \`root\`. For this, a \`proof\` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in ${location} with the default hashing function.
*/
function verify${suffix}(bytes32[] ${location} proof, bytes32 root, bytes32 leaf) internal ${visibility} returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from \`leaf\` using \`proof\`. A \`proof\` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* This version handles proofs in ${location} with the default hashing function.
*/
function processProof${suffix}(bytes32[] ${location} proof, bytes32 leaf) internal ${visibility} returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
`;

/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from \`leaf\` using \`proof\`. A \`proof\` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* This version handles proofs in ${location} with ${hashType ? 'a custom' : 'the default'} hashing function.
*/
function processProof${suffix}(${[
`bytes32[] ${location} proof`,
'bytes32 leaf',
hashType && [hashType, hashName].join(' '),
]
.filter(Boolean)
.join(', ')}) internal ${visibility} returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = ${hashName}(computedHash, proof[i]);
}
return computedHash;
const templateProofCustom = ({ suffix, location, visibility, hash }) => `\
/**
* @dev Returns true if a \`leaf\` can be proved to be a part of a Merkle tree
* defined by \`root\`. For this, a \`proof\` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in ${location} with a custom hashing function.
*/
function verify${suffix}(
bytes32[] ${location} proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) ${hash}
) internal ${visibility} returns (bool) {
return processProof(proof, leaf, ${hash}) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from \`leaf\` using \`proof\`. A \`proof\` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* This version handles proofs in ${location} with a custom hashing function.
*/
function processProof${suffix}(
bytes32[] ${location} proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) ${hash}
) internal ${visibility} returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = ${hash}(computedHash, proof[i]);
}
return computedHash;
}
`;

const templateMultiProof = ({ suffix, location, visibility, hashType, hashName = 'Hashes.commutativeKeccak256' }) => `\
/**
* @dev Returns true if the \`leaves\` can be simultaneously proven to be a part of a Merkle tree defined by
* \`root\`, according to \`proof\` and \`proofFlags\` as described in {processMultiProof}.
*
* This version handles multiproofs in ${location} with ${hashType ? 'a custom' : 'the default'} hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerify${suffix}(${[
`bytes32[] ${location} proof`,
`bool[] ${location} proofFlags`,
'bytes32 root',
`bytes32[] ${location} leaves`,
hashType && [hashType, hashName].join(' '),
]
.filter(Boolean)
.join(', ')}) internal ${visibility} returns (bool) {
return processMultiProof(${['proof', 'proofFlags', 'leaves', hashType && hashName]
.filter(Boolean)
.join(', ')}) == root;
const templateMultiProofDefault = ({ suffix, location, visibility }) => `\
/**
* @dev Returns true if the \`leaves\` can be simultaneously proven to be a part of a Merkle tree defined by
* \`root\`, according to \`proof\` and \`proofFlags\` as described in {processMultiProof}.
*
* This version handles multiproofs in ${location} with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerify${suffix}(
bytes32[] ${location} proof,
bool[] ${location} proofFlags,
bytes32 root,
bytes32[] ${location} leaves
) internal ${visibility} returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from \`leaves\` and sibling nodes in \`proof\`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each \`proofFlags\` item is true or false
* respectively.
*
* This version handles multiproofs in ${location} with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/
function processMultiProof${suffix}(
bytes32[] ${location} proof,
bool[] ${location} proofFlags,
bytes32[] ${location} leaves
) internal ${visibility} returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the \`leaves\` array, then goes onto the
// \`hashes\` array. At the end of the process, the last hash in the \`hashes\` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
/**
* @dev Returns the root of a tree reconstructed from \`leaves\` and sibling nodes in \`proof\`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each \`proofFlags\` item is true or false
* respectively.
*
* This version handles multiproofs in ${location} with ${hashType ? 'a custom' : 'the default'} hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/
function processMultiProof${suffix}(${[
`bytes32[] ${location} proof`,
`bool[] ${location} proofFlags`,
`bytes32[] ${location} leaves`,
hashType && [hashType, hashName].join(' '),
]
.filter(Boolean)
.join(', ')}) internal ${visibility} returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the \`leaves\` array, then goes onto the
// \`hashes\` array. At the end of the process, the last hash in the \`hashes\` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != totalHashes + 1) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// \`xxx[xxxPos++]\`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// \`proof\` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (totalHashes > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// \`xxx[xxxPos++]\`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// \`proof\` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = ${hashName}(a, b);
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
`;

const templateMultiProofCustom = ({ suffix, location, visibility, hash }) => `\
/**
* @dev Returns true if the \`leaves\` can be simultaneously proven to be a part of a Merkle tree defined by
* \`root\`, according to \`proof\` and \`proofFlags\` as described in {processMultiProof}.
*
* This version handles multiproofs in ${location} with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerify${suffix}(
bytes32[] ${location} proof,
bool[] ${location} proofFlags,
bytes32 root,
bytes32[] ${location} leaves,
function(bytes32, bytes32) view returns (bytes32) ${hash}
) internal ${visibility} returns (bool) {
return processMultiProof(proof, proofFlags, leaves, ${hash}) == root;
}
/**
* @dev Returns the root of a tree reconstructed from \`leaves\` and sibling nodes in \`proof\`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each \`proofFlags\` item is true or false
* respectively.
*
* This version handles multiproofs in ${location} with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/
function processMultiProof${suffix}(
bytes32[] ${location} proof,
bool[] ${location} proofFlags,
bytes32[] ${location} leaves,
function(bytes32, bytes32) view returns (bytes32) ${hash}
) internal ${visibility} returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the \`leaves\` array, then goes onto the
// \`hashes\` array. At the end of the process, the last hash in the \`hashes\` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
if (totalHashes > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
// Check proof validity.
if (leavesLen + proof.length != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// \`xxx[xxxPos++]\`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// \`proof\` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = ${hash}(a, b);
}
if (totalHashes > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
`;
/* eslint-enable max-len */

// GENERATE
module.exports = format(
header.trimEnd(),
'library MerkleProof {',
errors,
...OPTS.flatMap(opts => templateProof(opts)),
...OPTS.flatMap(opts => templateMultiProof(opts)),
format(
[].concat(
errors,
OPTS.flatMap(opts => (opts.hash ? templateProofCustom(opts) : templateProofDefault(opts))),
OPTS.flatMap(opts => (opts.hash ? templateMultiProofCustom(opts) : templateMultiProofDefault(opts))),
),
).trimEnd(),
'}',
);
5 changes: 1 addition & 4 deletions scripts/generate/templates/MerkleProof.opts.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ const OPTS = product(
{ suffix: '', location: 'memory' },
{ suffix: 'Calldata', location: 'calldata' },
],
[
{ visibility: 'pure' },
{ visibility: 'view', hashName: 'hasher', hashType: 'function(bytes32, bytes32) view returns (bytes32)' },
],
[{ visibility: 'pure' }, { visibility: 'view', hash: 'hasher' }],
).map(objs => Object.assign({}, ...objs));

module.exports = { OPTS };

0 comments on commit b85551a

Please sign in to comment.