Skip to content
Open
Show file tree
Hide file tree
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
160 changes: 131 additions & 29 deletions evm/test/Timba.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {Timba} from "../src/Timba.sol";
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract Token is ERC20 {
constructor() ERC20("Test", "TST") {}
Expand All @@ -31,25 +33,29 @@ contract TaxToken is Token {
}
}

contract CallbackToken is Token {
Timba public target;
bytes32 public game;
bool public blocked;
/// Calls `target` with `data` from inside its next transfer, and passes on that call's revert,
/// so a test sees why the nested call failed.
contract ReentrantToken is Token {
address public target;
bytes public data;

function arm(Timba t, bytes32 id) external {
target = t;
game = id;
function arm(address next, bytes memory call) external {
target = next;
data = call;
}

function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
if (address(target) != address(0)) {
try target.joinGame(game, 0, "") {
revert("reentered");
} catch {
blocked = true;
function _update(address from, address to, uint256 amount) internal override {
address next = target;
if (next != address(0) && from != address(0)) {
target = address(0);
(bool ok, bytes memory reason) = next.call(data);
if (!ok) {
assembly {
revert(add(reason, 32), mload(reason))
}
}
}
return super.transferFrom(from, to, amount);
super._update(from, to, amount);
}
}

Expand All @@ -76,14 +82,15 @@ contract TimbaV2 is Timba {
}

// A test-only entropy source exercises exhaustion deterministically. The deployed
// Timba implementation continues to use keccak256 for every rehash.
// Timba implementation continues to use keccak256 for every rehash. Only the last rehash
// (round 31) gives usable entropy, and the budget of 32 samples never reads it.
contract ExhaustedEntropyTimba is Timba {
function sample(bytes32 entropy, uint256 entries) external pure returns (uint256) {
return _sampleWinner(entropy, entries);
}

function _rehashWinnerEntropy(bytes32, uint256) internal pure override returns (bytes32) {
return bytes32(0);
function _rehashWinnerEntropy(bytes32, uint256 round) internal pure override returns (bytes32) {
return round == 31 ? bytes32(type(uint256).max) : bytes32(0);
}
}

Expand Down Expand Up @@ -498,12 +505,17 @@ contract TimbaTest is Test {
Timba.CreateRequest memory r = request(Timba.GameType.Coinflip);
r.isPrivate = true;
bytes32 game = create(r, true);
bytes memory signature = sign(timba.joinDigest(game, bob, block.timestamp + 10));
uint256 deadline = block.timestamp + 10;
bytes memory signature = sign(timba.joinDigest(game, bob, deadline));
vm.prank(bob);
vm.expectRevert(Timba.InvalidAuthorization.selector);
timba.joinGame(game, block.timestamp + 11, signature);
timba.joinGame(game, deadline + 1, signature);
// The signature is still good at its deadline.
vm.warp(deadline);
vm.expectEmit(true, true, false, true, address(timba));
emit Timba.PlayerJoined(game, bob, 1, block.number);
vm.prank(bob);
timba.joinGame(game, block.timestamp + 10, signature);
timba.joinGame(game, deadline, signature);
vm.prank(operator);
timba.transferOwnership(bob);
vm.prank(bob);
Expand Down Expand Up @@ -612,15 +624,79 @@ contract TimbaTest is Test {
assertEq(tax.balanceOf(address(timba)), 100 ether);
}

function testReentrancyBlockedDuringDeposit() public {
CallbackToken callback = new CallbackToken();
fund(alice, callback);
Timba.CreateRequest memory r = request(Timba.GameType.Coinflip);
r.token = address(callback);
callback.arm(timba, timba.gameIdFor(alice, r.nonce));
bytes32 game = create(r, true);
assertTrue(callback.blocked());
assertEq(timba.getGame(game).participants.length, 1);
/// Each entry point that moves tokens, and the upgrade, holds the guard while it runs: a
/// token that calls back into Timba from its transfer cannot join a game. The last lines
/// show the nested join is otherwise valid, so only the guard stops it.
function testReentryFromTransfersAndUpgradesIsBlocked() public {
ReentrantToken hook = new ReentrantToken();
fund(alice, hook);
fund(bob, hook);
// An open, public giveaway: any address joins it without a transfer.
Timba.CreateRequest memory open = request(Timba.GameType.Giveaway);
open.timeout = 1 days;
bytes32 target = create(open, false);
bytes memory reenter = abi.encodeCall(Timba.joinGame, (target, 0, ""));
bytes4 blocked = ReentrancyGuardTransient.ReentrancyGuardReentrantCall.selector;

// createGame: the giveaway's deposit.
Timba.CreateRequest memory r = request(Timba.GameType.Giveaway);
r.token = address(hook);
bytes memory signature = sign(timba.creationDigest(r));
hook.arm(address(timba), reenter);
vm.prank(alice);
vm.expectRevert(blocked);
timba.createGame(r, signature, false);
hook.arm(address(0), "");
bytes32 giveaway = create(r, false);

// closeGame: the creator's refund.
hook.arm(address(timba), reenter);
vm.prank(alice);
vm.expectRevert(blocked);
timba.closeGame(giveaway);

// joinGame: the ticket deposit.
r = request(Timba.GameType.Coinflip);
r.token = address(hook);
hook.arm(address(0), "");
bytes32 coinflip = create(r, false);
hook.arm(address(timba), reenter);
vm.prank(bob);
vm.expectRevert(blocked);
timba.joinGame(coinflip, 0, "");

// completeGame: the prize.
hook.arm(address(0), "");
join(coinflip, alice);
join(coinflip, bob);
hook.arm(address(timba), reenter);
vm.prank(operator);
vm.expectRevert(blocked);
timba.completeGame(coinflip, SECRET);

// refundPlayer: an underfilled coinflip that expired.
r = request(Timba.GameType.Coinflip);
r.token = address(hook);
r.timeout = 1;
hook.arm(address(0), "");
bytes32 expired = create(r, true);
vm.warp(block.timestamp + 1);
hook.arm(address(timba), reenter);
vm.prank(alice);
vm.expectRevert(blocked);
timba.refundPlayer(expired, alice);

// upgradeToAndCall: its call runs in the proxy while the guard is held.
address next = address(new Timba());
vm.prank(address(0xad));
vm.expectRevert(blocked);
timba.upgradeToAndCall(next, reenter);

vm.prank(address(hook));
timba.joinGame(target, 0, "");
vm.prank(address(0xad));
timba.joinGame(target, 0, "");
assertEq(timba.getGame(target).participants.length, 2);
}

function testFuzzAccounting(uint96 rawAmount, uint8 rawFee) public {
Expand Down Expand Up @@ -651,6 +727,16 @@ contract TimbaTest is Test {
vm.prank(operator);
vm.expectRevert(Timba.InvalidAuthorization.selector);
timba.transferOwnership(address(timba));
// A stranger is stopped by the owner check before the operator rules.
vm.prank(alice);
vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, alice));
timba.renounceOwnership();
vm.prank(alice);
vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, alice));
timba.transferOwnership(address(timba));
c.minTimeout = c.maxTimeout;
vm.prank(operator);
timba.configure(c);
for (uint256 i; i < 5; i++) {
c = defaults();
if (i == 0) c.feePercentage = 11;
Expand Down Expand Up @@ -690,6 +776,22 @@ contract TimbaTest is Test {
assertEq(uint256(timba.getGame(timba.gameIdFor(alice, 0)).status), uint256(Timba.Status.Missing));
}

/// Each creation limit is inclusive: a request at the limit itself is accepted.
function testCreationAcceptsEachLimitItself() public {
for (uint256 i; i < 4; i++) {
Timba.CreateRequest memory r = request(Timba.GameType.Coinflip);
if (i == 0) r.deadline = block.timestamp;
if (i == 1) r.timeout = defaults().minTimeout;
if (i == 2) r.timeout = defaults().maxTimeout;
if (i == 3) r.amount = type(uint256).max / r.maxPlayers;
create(r, false);
}
// The latest start whose expiry and buffer still fit in uint48.
vm.warp(type(uint48).max - 1 hours - timba.MAX_BUFFER());
create(request(Timba.GameType.Coinflip), false);
assertEq(timba.creationNonces(alice), 5);
}

function testReadyGiveawayCannotCloseEarlyAndRecoversAtLiveBoundary() public {
bytes32 game = create(request(Timba.GameType.Giveaway), true);
join(game, bob);
Expand Down
136 changes: 136 additions & 0 deletions scripts/check-coverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,139 @@ test("enforces the threshold and validates merged LCOV reports", async () => {
await rm(root, { recursive: true, force: true });
}
});

/** A git repository with these tracked files, each one line long. */
async function trackedRepository(files: string[]): Promise<string> {
const root = await mkdtemp(join(tmpdir(), "timba-coverage-scope-"));
for (const file of files) {
await mkdir(join(root, file, ".."), { recursive: true });
await writeFile(join(root, file), "synthetic\n");
}
await git(root, "init", "-q");
await git(root, "add", ".");
return root;
}

/** Full coverage for each file: one hit line. */
const covering = (...files: string[]) =>
files.map((file) => `SF:${file}\nDA:1,1\nend_of_record\n`).join("");

async function gate(
root: string,
config: Parameters<typeof checkCoverage>[0],
lcov: string,
): Promise<Awaited<ReturnType<typeof checkCoverage>>> {
await writeFile(join(root, "report.info"), lcov);
return checkCoverage(config, ["report.info"], root);
}

test("the scope takes every root, file roots, nested roots and globs", async () => {
const files = [
"src/a.ts",
"srcx/b.ts",
"lib/c.js",
"pkg/src/d.ts",
"one.ts",
"src/gen-1.ts",
"src/q1.ts",
"src/qq1.ts",
];
const root = await trackedRepository(files);
try {
// Missing from the report, so each scoped file is listed.
const scope = async (config: Parameters<typeof checkCoverage>[0]) =>
(await gate(root, config, covering("src/a.ts"))).missing.sort();

expect(await scope({ roots: ["src"], extensions: [".ts"] })).toEqual([
"src/gen-1.ts",
"src/q1.ts",
"src/qq1.ts",
]);
// Any of several roots, and a root may name a file.
expect(await scope({ roots: ["src", "one.ts"], extensions: [".ts"] })).toEqual([
"one.ts",
"src/gen-1.ts",
"src/q1.ts",
"src/qq1.ts",
]);
// Trailing slashes of a nested root do not matter.
expect(await scope({ roots: ["src", "pkg/src//"], extensions: [".ts"] })).toEqual([
"pkg/src/d.ts",
"src/gen-1.ts",
"src/q1.ts",
"src/qq1.ts",
]);
// "." is the whole repository, and any of several extensions counts.
expect(await scope({ roots: ["."], extensions: [".js", ".ts"] })).toEqual(
files.filter((file) => file !== "src/a.ts").sort(),
);
// "*" matches any text and "?" one character.
expect(
await scope({ roots: ["src"], extensions: [".ts"], exclude: ["src/gen-*.ts", "src/q?.ts"] }),
).toEqual(["src/qq1.ts"]);
await expect(gate(root, { roots: ["none"], extensions: [".ts"] }, "")).rejects.toThrow(
"No source files matched the coverage scope",
);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("report paths resolve from the report base, and paths outside the root are ignored", async () => {
const root = await trackedRepository(["solana/src/a.rs"]);
try {
const config = { roots: ["solana"], extensions: [".rs"], reportBase: "solana" };
expect((await gate(root, config, covering("src/a.rs"))).passed).toBe(true);
const unbased = { roots: ["solana"], extensions: [".rs"] };
expect((await gate(root, unbased, covering("solana/src/a.rs"))).passed).toBe(true);
expect((await gate(root, config, covering(join(root, "solana/src/a.rs")))).passed).toBe(true);
await expect(gate(root, config, covering("../src/a.rs", "/elsewhere/a.rs"))).rejects.toThrow(
"No scoped line data",
);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("line data is a positive line number, a hit count and maybe a checksum", async () => {
const root = await trackedRepository(["src/a.ts"]);
try {
const config = { roots: ["src"], extensions: [".ts"] };
const result = await gate(root, config, "SF:src/a.ts\nDA:12,0\nDA:3,10,abc\nend_of_record\n");
expect([result.covered, result.total]).toEqual([1, 2]);
for (const data of ["x,1", "1,x", "a1,1", "1a,1", "1,1a", "1,a1", "1", "0,1", "-1,1", "1,-1"]) {
await expect(gate(root, config, `SF:src/a.ts\nDA:${data}\nend_of_record\n`)).rejects.toThrow(
"Invalid LCOV line data",
);
}
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("only a record's own lines count for its file", async () => {
const root = await trackedRepository(["src/a.ts"]);
try {
const config = { roots: ["src"], extensions: [".ts"] };
// Other entries in a record do not end it, end_of_record does.
const result = await gate(
root,
config,
"SF:src/a.ts\nFN:1,main\nLF:1\nDA:1,1\nend_of_record\nDA:2,0\n",
);
expect([result.covered, result.total]).toEqual([1, 1]);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("a directory that is not a git repository has no tracked files", async () => {
const root = await mkdtemp(join(tmpdir(), "timba-coverage-nogit-"));
try {
await expect(checkCoverage({ roots: ["."], extensions: [".ts"] }, [], root)).rejects.toThrow(
"Unable to list tracked source files",
);
} finally {
await rm(root, { recursive: true, force: true });
}
});
Loading