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

fix: add merkle proof length check #2

Open
wants to merge 1 commit into
base: feat/v0.2.0
Choose a base branch
from
Open
Changes from all 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
18 changes: 10 additions & 8 deletions packages/evm/contracts/adapters/Spectre/lib/Merkle.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ library Merkle {
function restoreMerkleRoot(
bytes32[] memory branch,
bytes32 leaf,
uint256 index
uint256 index,
uint256 depth
) internal pure returns (bytes32 root) {
require(index < 2 ** branch.length, "invalid leaf index");

bytes32 combineHash = leaf;
uint256 curIndex = index;
for (uint256 i = 0; i < branch.length; ) {
for (uint256 i = 0; i < depth; ) {
if (curIndex % 2 == 0) combineHash = sha256(bytes.concat(combineHash, branch[i]));
else combineHash = sha256(bytes.concat(branch[i], combineHash));

Expand All @@ -40,9 +41,9 @@ library Merkle {
uint64 txSlot,
bytes32 headerRoot
) internal pure returns (bool) {
uint256 index;
uint256 gindex;
if (txSlot == lcSlot) {
index = RECEIPT_ROOT_GINDEX;
gindex = RECEIPT_ROOT_GINDEX;
} else if (lcSlot - txSlot <= SLOTS_PER_HISTORICAL_ROOT) {
uint256[] memory blockRootsGindex = new uint256[](2);
blockRootsGindex[0] = BLOCK_ROOTS_GINDEX;
Expand All @@ -53,14 +54,15 @@ library Merkle {
receiptGindexes[2] = RECEIPT_ROOT_GINDEX;

// BeaconBlock -> BeaconState -> HistoricalRoots -> BeaconBlock -> BeaconBody -> ExecutionPayload -> ReceiptsRoot
index = concatGindices(receiptGindexes);
gindex = concatGindices(receiptGindexes);
} else if (lcSlot - txSlot > SLOTS_PER_HISTORICAL_ROOT) {
revert("txSlot lags by >8192 blocks. Not supported.");
} else {
revert("txSlot can't be greater than lightclient slot");
}

bytes32 computedRoot = restoreMerkleRoot(receiptsRootBranch, receiptsRoot, calculateIndex(index));
(uint256 index, uint256 depth) = calculateIndex(gindex);
bytes32 computedRoot = restoreMerkleRoot(receiptsRootBranch, receiptsRoot, index, depth);
return computedRoot == headerRoot;
}

Expand Down Expand Up @@ -99,8 +101,8 @@ library Merkle {
return gindex;
}

function calculateIndex(uint256 gindex) internal pure returns (uint256 index) {
uint256 depth = floorLog2(gindex);
function calculateIndex(uint256 gindex) internal pure returns (uint256 index, uint256 depth) {
depth = floorLog2(gindex);
index = gindex % (2 ** depth);
}

Expand Down