Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
6b079ee
Add a (complete) MerkleTree structure
Amxx Aug 14, 2022
42c695b
optimize array access & remove depth/length constrains
Amxx Aug 14, 2022
ca83cde
gas optimization
Amxx Aug 14, 2022
f4f46ca
limit tree depth to 255 to avoid issues (255 is enough for any realis…
Amxx Aug 14, 2022
af7cb9c
fix lint
Amxx Aug 14, 2022
45eae37
reason
Amxx Aug 14, 2022
ac648c6
coverage
Amxx Aug 14, 2022
1b184c9
comments
Amxx Aug 14, 2022
4863418
documentation & changelog entry
Amxx Aug 16, 2022
3c19dcf
Merge branch 'master' into structure/merkletree
Amxx Dec 13, 2023
9fc7f31
update
Amxx Dec 13, 2023
652c8a1
add changeset
Amxx Dec 13, 2023
c74ab55
fix lint
Amxx Dec 14, 2023
a9932c9
fix lint
Amxx Dec 14, 2023
d8bdfd0
fix codespell
Amxx Dec 14, 2023
4d0ed52
Merge branch 'master' into structure/merkletree
Amxx Jan 4, 2024
b131354
update @openzeppelin/merkle-tree dependency
Amxx Jan 28, 2024
6422af6
fix lint
Amxx Jan 28, 2024
3ab0d21
Merge branch 'master' into structure/merkletree
Amxx Feb 5, 2024
5639d7c
up
Amxx Feb 5, 2024
24c829a
minimize changes
Amxx Feb 5, 2024
f954a98
Panic with RESOURCE_ERROR when inserting in a full tree
Amxx Feb 5, 2024
acdc6a9
Merge branch 'master' into structure/merkletree
Amxx Feb 6, 2024
cebdc2a
improve coverage
Amxx Feb 6, 2024
d4ced94
test looparound property of memory arrays
Amxx Feb 6, 2024
a3a813c
rename initialize → setUp
Amxx Feb 7, 2024
ec05d19
Update contracts/utils/structs/MerkleTree.sol
Amxx Feb 7, 2024
8ecc790
Merge branch 'master' into structure/merkletree
Amxx Feb 12, 2024
ec3d96b
fix lint
Amxx Feb 12, 2024
bcc0667
cleanup
Amxx Feb 12, 2024
b50ebee
Merge branch 'master' into structure/merkletree
Amxx Feb 16, 2024
5b15205
remove root history from the MerkleTree structure
Amxx Feb 19, 2024
b390790
Add Hashes.sol
Amxx Feb 19, 2024
e331674
fix-lint
Amxx Feb 19, 2024
91f7057
rename to reflect removal of history
Amxx Feb 19, 2024
088fa8c
rename setUp → setup
Amxx Feb 19, 2024
2d869b7
doc
Amxx Feb 20, 2024
567cd3e
Update contracts/utils/structs/MerkleTree.sol
Amxx Feb 20, 2024
a13237a
Update MerkleTree.sol
Amxx Feb 20, 2024
03bea3e
Update changesets and fix some comments
ernestognw Feb 21, 2024
c475bad
Simplify
ernestognw Feb 21, 2024
6a9e873
Add Merkle Tree to the docs
ernestognw Feb 21, 2024
1e59539
Remove merkletree.test.js
ernestognw Feb 21, 2024
051107b
Recover MerkleTree.test.js
ernestognw Feb 21, 2024
a1dd158
prefix variables with underscore to mark them as private (similar do …
Amxx Feb 21, 2024
7a21c4e
test reseting the tree using setup
Amxx Feb 21, 2024
01c2879
rename hashing functions
Amxx Feb 21, 2024
2494680
return index and root when inserting a leaf
Amxx Feb 21, 2024
0a2bfce
rename structure and functions
Amxx Feb 21, 2024
08c9a3c
Apply PR suggestions
ernestognw Mar 5, 2024
31712fb
Update contracts/utils/cryptography/Hashes.sol
Amxx Mar 5, 2024
55853be
rename the standard node hash
Amxx Mar 6, 2024
eca27fc
fix lint
Amxx Mar 6, 2024
eca9085
Fix NatSpec weird error
ernestognw Mar 7, 2024
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
Prev Previous commit
Next Next commit
remove root history from the MerkleTree structure
  • Loading branch information
Amxx committed Feb 19, 2024
commit 5b152051142e6c64c30f91263e9bdde114248c6a
24 changes: 4 additions & 20 deletions contracts/mocks/MerkleTreeMock.sol
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ contract MerkleTreeMock {

MerkleTree.TreeWithHistory private _tree;

constructor(uint256 _depth, uint256 _length, bytes32 _zero) {
_tree.setUp(_depth, _length, _zero);
constructor(uint256 _depth, bytes32 _zero) {
_tree.setUp(_depth, _zero);
}

function insert(bytes32 leaf) public returns (uint256) {
Expand All @@ -21,23 +21,11 @@ contract MerkleTreeMock {
return _tree.getDepth();
}

function getLength() public view returns (uint256) {
return _tree.getLength();
}

function getLastRoot() public view returns (bytes32) {
return _tree.getLastRoot();
}

function isKnownRoot(bytes32 root) public view returns (bool) {
return _tree.isKnownRoot(root);
function getRoot() public view returns (bytes32) {
return _tree.getRoot();
}

// internal state
function currentRootIndex() public view returns (uint256) {
return _tree.currentRootIndex;
}

function nextLeafIndex() public view returns (uint256) {
return _tree.nextLeafIndex;
}
Expand All @@ -49,8 +37,4 @@ contract MerkleTreeMock {
function zeros(uint256 i) public view returns (bytes32) {
return _tree.zeros[i];
}

function roots(uint256 i) public view returns (bytes32) {
return _tree.roots[i];
}
}
64 changes: 16 additions & 48 deletions contracts/utils/structs/MerkleTree.sol
Original file line number Diff line number Diff line change
Expand Up @@ -41,38 +41,36 @@ library MerkleTree {
* @dev The `sides` and `zero` arrays are set, at initialization, to have a length equal to the depth of the tree.
* No push/pop operations should be performed of these array, and their lengths should not be updated.
*
* The `roots` array stores the history of roots. Its length is set at initialization, and should not be updated.
*
* The hashing function used during initialization to compute the `zeros` values (value of a node at a given depth
* for which the subtree is full of zero leaves). This function is kept in the structure for handling insertions.
*
* Developper using this structure may want to use a secondary structure to store a (partial) list of historical
* roots.
*/
struct TreeWithHistory {
uint256 currentRootIndex;
bytes32 root;
uint256 nextLeafIndex;
bytes32[] sides;
bytes32[] zeros;
bytes32[] roots;
function(bytes32, bytes32) view returns (bytes32) fnHash;
}

/**
* @dev Initialize using the default hash
*/
function setUp(TreeWithHistory storage self, uint256 depth, uint256 length, bytes32 zero) internal {
return setUp(self, depth, length, zero, MerkleProof.hashPair);
function setUp(TreeWithHistory storage self, uint256 depth, bytes32 zero) internal {
return setUp(self, depth, zero, MerkleProof.hashPair);
}

/**
* @dev Initialize a new complete MerkleTree defined by:
* - Depth `depth`
* - All leaves are initialize to `zero`
* - Hashing function for a pair of leaves is fnHash
* and keep a root history of length `length` when leaves are inserted.
* - Hashing function for a pair of leaves is fnHash.
*/
function setUp(
TreeWithHistory storage self,
uint256 depth,
uint256 length,
bytes32 zero,
function(bytes32, bytes32) view returns (bytes32) fnHash
) internal {
Expand All @@ -83,7 +81,6 @@ library MerkleTree {
// Store depth & length in the dynamic array
Arrays.unsafeSetLength(self.sides, depth);
Arrays.unsafeSetLength(self.zeros, depth);
Arrays.unsafeSetLength(self.roots, length);
self.fnHash = fnHash;

// Build the different hashes in a zero-filled complete tree
Expand All @@ -92,13 +89,12 @@ library MerkleTree {
Arrays.unsafeAccess(self.zeros, i).value = currentZero;
currentZero = fnHash(currentZero, currentZero);
}

// Insert the first root
Arrays.unsafeAccess(self.roots, 0).value = currentZero;
// Set the first root
self.root = currentZero;
}

/**
* @dev Insert a new leaf in the tree, compute the new root, and store that new root in the history.
* @dev Insert a new leaf in the tree, and compute the new root.
*/
function insert(TreeWithHistory storage self, bytes32 leaf) internal returns (uint256) {
// Cache read
Expand All @@ -109,7 +105,9 @@ library MerkleTree {
uint256 leafIndex = self.nextLeafIndex++;

// Check if tree is full.
if (leafIndex >= 1 << depth) Panic.panic(Panic.RESOURCE_ERROR);
if (leafIndex >= 1 << depth) {
Panic.panic(Panic.RESOURCE_ERROR);
}

// Rebuild branch from leaf to root
uint256 currentIndex = leafIndex;
Expand All @@ -136,8 +134,7 @@ library MerkleTree {
}

// Record new root
self.currentRootIndex = (self.currentRootIndex + 1) % self.roots.length;
Arrays.unsafeAccess(self.roots, self.currentRootIndex).value = currentLevelHash;
self.root = currentLevelHash;

return leafIndex;
}
Expand All @@ -149,39 +146,10 @@ library MerkleTree {
return self.zeros.length;
}

/**
* @dev History length (set at initialization)
*/
function getLength(TreeWithHistory storage self) internal view returns (uint256) {
return self.roots.length;
}

/**
* @dev Return the current root of the tree.
*/
function getLastRoot(TreeWithHistory storage self) internal view returns (bytes32) {
return Arrays.unsafeAccess(self.roots, self.currentRootIndex).value;
}

/**
* @dev Look in root history,
*/
function isKnownRoot(TreeWithHistory storage self, bytes32 root) internal view returns (bool) {
if (root == 0) {
return false;
}

// Cache read
uint256 currentRootIndex = self.currentRootIndex;
uint256 length = self.roots.length;

// Search (most recents first)
for (uint256 i = length; i > 0; --i) {
if (root == Arrays.unsafeAccess(self.roots, (currentRootIndex + i) % length).value) {
return true;
}
}

return false;
function getRoot(TreeWithHistory storage self) internal view returns (bytes32) {
return self.root;
}
}
29 changes: 4 additions & 25 deletions test/utils/structs/Merkletree.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@ const makeTree = (leafs = [ethers.ZeroHash]) =>

const MAX_DEPTH = 255n;
const DEPTH = 4n; // 16 slots
const LENGTH = 8n;
const ZERO = makeTree().leafHash([ethers.ZeroHash]);

async function fixture() {
return { mock: await ethers.deployContract('MerkleTreeMock', [DEPTH, LENGTH, ZERO]) };
return { mock: await ethers.deployContract('MerkleTreeMock', [DEPTH, ZERO]) };
}

describe('Merklee tree', function () {
Expand All @@ -27,7 +26,7 @@ describe('Merklee tree', function () {

it('depth is limited', async function () {
const invalidDepth = MAX_DEPTH + 1n;
await expect(ethers.deployContract('MerkleTreeMock', [invalidDepth, LENGTH, ZERO]))
await expect(ethers.deployContract('MerkleTreeMock', [invalidDepth, ZERO]))
.to.be.revertedWithCustomError({ interface: this.mock.interface }, 'MerkleTreeInvalidDepth')
.withArgs(invalidDepth, MAX_DEPTH);
});
Expand All @@ -36,23 +35,13 @@ describe('Merklee tree', function () {
const merkleTree = makeTree(Array.from({ length: 2 ** Number(DEPTH) }, () => ethers.ZeroHash));

expect(await this.mock.getDepth()).to.equal(DEPTH);
expect(await this.mock.getLength()).to.equal(LENGTH);
expect(await this.mock.currentRootIndex()).to.equal(0n);
expect(await this.mock.nextLeafIndex()).to.equal(0n);
expect(await this.mock.getLastRoot()).to.equal(merkleTree.root);

for (let i = 0; i < LENGTH; ++i) {
expect(await this.mock.roots(i)).to.equal(i === 0 ? merkleTree.root : ethers.ZeroHash);
}

expect(await this.mock.isKnownRoot(merkleTree.root)).to.be.true;
expect(await this.mock.isKnownRoot(ethers.ZeroHash)).to.be.false;
expect(await this.mock.getRoot()).to.equal(merkleTree.root);
});

describe('insert', function () {
it('tree is correctly updated', async function () {
const leafs = Array.from({ length: 2 ** Number(DEPTH) }, () => ethers.ZeroHash);
const roots = [];

// for each leaf slot
for (const i in leafs) {
Expand All @@ -66,18 +55,8 @@ describe('Merklee tree', function () {
await this.mock.insert(merkleTree.leafHash([leafs[i]]));

// check tree
expect(await this.mock.currentRootIndex()).to.equal((BigInt(i) + 1n) % LENGTH);
expect(await this.mock.getRoot()).to.equal(merkleTree.root);
expect(await this.mock.nextLeafIndex()).to.equal(BigInt(i) + 1n);
expect(await this.mock.getLastRoot()).to.equal(merkleTree.root);

// check root history
roots.push(merkleTree.root);
for (const root of roots.slice(0, -Number(LENGTH))) {
expect(await this.mock.isKnownRoot(root)).to.be.false;
}
for (const root of roots.slice(-Number(LENGTH))) {
expect(await this.mock.isKnownRoot(root)).to.be.true;
}
}
});

Expand Down