Skip to content

Commit

Permalink
Add unit tests for Bitfield.sol
Browse files Browse the repository at this point in the history
  • Loading branch information
vgeddes committed May 26, 2024
1 parent 2ebd3d2 commit fe4f35c
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
34 changes: 34 additions & 0 deletions contracts/test/Bitfield.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.25;

import {Test} from "forge-std/Test.sol";
import {console} from "forge-std/console.sol";
import {BitfieldWrapper} from "./mocks/BitfieldWrapper.sol";
import {Bitfield} from "../src/utils/Bitfield.sol";

import {stdJson} from "forge-std/StdJson.sol";

contract BitfieldTest is Test {
using stdJson for string;

function testBitfieldSubsampling() public {
BitfieldWrapper bw = new BitfieldWrapper();

string memory json = vm.readFile(string.concat(vm.projectRoot(), "/test/data/beefy-validator-set.json"));
uint32 setSize = uint32(json.readUint(".validatorSetSize"));
bytes32 root = json.readBytes32(".validatorRoot");
uint256[] memory bitSetArray = json.readUintArray(".participants");

uint256[] memory initialBitField = bw.createBitfield(bitSetArray, setSize);
uint256[] memory finalBitfield = bw.subsample(67, initialBitField, 30, setSize);

uint256 counter = 0;
for (uint256 i = 0; i < bitSetArray.length; i++) {
if (Bitfield.isSet(finalBitfield, bitSetArray[i])) {
counter++;
}
}
assertEq(30, counter);
assertEq(Bitfield.countSetBits(finalBitfield), counter);
}
}
18 changes: 18 additions & 0 deletions contracts/test/mocks/BitfieldWrapper.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.25;

import {Bitfield} from "../../src/utils/Bitfield.sol";

contract BitfieldWrapper {
function createBitfield(uint256[] calldata bitsToSet, uint256 length)
pure
public
returns (uint256[] memory bitfield)
{
return Bitfield.createBitfield(bitsToSet, length);
}

function subsample(uint256 seed, uint256[] memory prior, uint256 n, uint256 length) public returns (uint256[] memory bitfield) {
return Bitfield.subsample(seed, prior, n, length);
}
}
1 change: 0 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
gopls
go-outline
gopkgs
gocode-gomod
godef
golint
mage
Expand Down

0 comments on commit fe4f35c

Please sign in to comment.