-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasedRandomness.sol
More file actions
389 lines (325 loc) · 16.3 KB
/
BasedRandomness.sol
File metadata and controls
389 lines (325 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "./interfaces/IBasedRandomness.sol";
// crafted with ❤️ by BasedToschi
/**
* @title BasedRandomness - On-Chain Randomness System
* @dev Secure random number generation using DEX entropy and future block hashes
*
* Two-Step Process:
* 1. Prepare: Lock parameters using current block data + DEX entropy
* 2. Generate: Use future block hashes (unpredictable at preparation time)
*
* Entropy Sources: 6 DEX pools + block data for maximum security
*/
/**
* @dev ERC20 interface for balance and supply queries
*/
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
contract BasedRandomness is IBasedRandomness {
// ═══════════════════════════════════════════════════════════════════
// CONSTANTS & IMMUTABLES
// ═══════════════════════════════════════════════════════════════════
/// @dev Maximum random number upper bound (2^120)
uint256 public constant MAX_NUMBER_LIMIT = 2**120;
// DEX addresses for entropy generation
address private immutable USDC_TOKEN;
address private immutable WETH_TOKEN;
address private immutable UNI_USDC_ETH_V2;
address private immutable UNI_USDC_ETH_03;
address private immutable UNI_04;
// ═══════════════════════════════════════════════════════════════════
// STORAGE
// ═══════════════════════════════════════════════════════════════════
/// @dev Maps request IDs to their request data
mapping(bytes32 => RandomRequest) public randomRequests;
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════════════
/**
* @dev Initialize with DEX addresses for entropy
*/
constructor(
address USDCAddress,
address WETHAddress,
address UNIV2PoolAddress,
address UNIV3PoolAddress,
address UNIV4Address
) {
USDC_TOKEN = USDCAddress;
WETH_TOKEN = WETHAddress;
UNI_USDC_ETH_V2 = UNIV2PoolAddress;
UNI_USDC_ETH_03 = UNIV3PoolAddress;
UNI_04 = UNIV4Address;
}
// ═══════════════════════════════════════════════════════════════════
// PREPARATION FUNCTIONS
// ═══════════════════════════════════════════════════════════════════
/**
* @inheritdoc IBasedRandomness
*/
function prepareRandomNumbers(
uint256 maxNumber,
uint256 count,
bytes32 initialCumulativeHash,
bool includeZero,
address idOwner,
uint256 extraSecurity,
bytes32 baseEntropyHash
) public returns (bytes32) {
// Parameter validation
require(maxNumber > 0 && maxNumber <= MAX_NUMBER_LIMIT, "Invalid maxNumber");
require(count > 0, "Count must be greater than 0");
require(count <= 500, "Count cannot exceed 500 for gas safety");
require(extraSecurity <= 50, "Extra security must be less than 50");
// Range exhaustion validation
uint256 totalPossible = includeZero ? maxNumber + 1 : maxNumber;
require(count <= totalPossible, "Cannot generate more unique numbers than range allows");
// Owner resolution - use msg.sender if idOwner is zero
address actualOwner = idOwner == address(0) ? msg.sender : idOwner;
// Entropy collection - use provided or generate from DEX
bytes32 realBaseEntropyHash = baseEntropyHash;
if(baseEntropyHash == bytes32(0)) {
realBaseEntropyHash = getEntropy(); // Generates from 6 DEX calls
}
// Get previous block hash for temporal entropy
bytes32 previousBlockHash = blockhash(block.number - 1);
// Generate unique request ID
bytes32 requestId = keccak256(abi.encodePacked(
maxNumber,
initialCumulativeHash,
actualOwner,
previousBlockHash,
realBaseEntropyHash,
includeZero,
block.number,
block.prevrandao
));
// Check for collisions
if(randomRequests[requestId].requester != address(0)) {
revert("Request already exists");
}
// Store request
randomRequests[requestId] = RandomRequest({
requestBlock: block.number,
requester: actualOwner,
maxNumber: maxNumber,
includeZero: includeZero,
count: count,
extraSecurity: extraSecurity
});
emit RandomNumberRequested(requestId, actualOwner, maxNumber, includeZero, extraSecurity, count);
return requestId;
}
/**
* @inheritdoc IBasedRandomness
*/
function batchPrepareRandomNumbers(
uint256[] calldata maxNumbers,
uint256[] calldata counts,
bytes32 initialCumulativeHash,
bool includeZero,
address idOwner,
uint256[] calldata extraSecurity,
bytes32 baseEntropyHash
) external returns (bytes32[] memory) {
// Validate arrays
require(maxNumbers.length > 0, "Empty maxNumbers array");
require(counts.length == 1 || counts.length == maxNumbers.length, "Invalid counts array length");
require(extraSecurity.length == 1 || extraSecurity.length == maxNumbers.length, "Invalid security array length");
bytes32[] memory requestIds = new bytes32[](maxNumbers.length);
bytes32 rollingHash = initialCumulativeHash;
// Process each request
for (uint256 i = 0; i < maxNumbers.length; i++) {
uint256 currentCount = counts.length == 1 ? counts[0] : counts[i];
uint256 currentSecurity = extraSecurity.length == 1 ? extraSecurity[0] : extraSecurity[i];
// Update rolling hash for uniqueness
rollingHash = keccak256(abi.encodePacked(rollingHash, maxNumbers[i], i));
// Handle entropy
bytes32 realBaseEntropyHash = baseEntropyHash;
if(baseEntropyHash == bytes32(0)) {
realBaseEntropyHash = getEntropy();
}
// Create request
requestIds[i] = prepareRandomNumbers(
maxNumbers[i],
currentCount,
rollingHash,
includeZero,
idOwner,
currentSecurity,
realBaseEntropyHash
);
}
return requestIds;
}
// ═══════════════════════════════════════════════════════════════════
// VIEW FUNCTIONS
// ═══════════════════════════════════════════════════════════════════
/**
* @inheritdoc IBasedRandomness
*/
function isRequestReady(bytes32 requestId) external view returns (bool) {
RandomRequest memory request = randomRequests[requestId];
if (request.requester == address(0)) {
return false; // Request doesn't exist
}
return block.number >= request.requestBlock + 4 + request.extraSecurity;
}
// ═══════════════════════════════════════════════════════════════════
// GENERATION FUNCTIONS
// ═══════════════════════════════════════════════════════════════════
/**
* @inheritdoc IBasedRandomness
*/
function generateRandomNumbers(bytes32 requestId) public returns (uint256[] memory) {
// Validate request and authorization
RandomRequest memory request = randomRequests[requestId];
require(request.requester != address(0), "Invalid request ID");
require(request.requester == msg.sender, "Only the original requester can generate the number");
require(block.number >= request.requestBlock + 4 + request.extraSecurity, "Must wait required blocks before generating");
uint256[] memory randomNumbers = new uint256[](request.count);
// Create slots for transient storage
bytes32 duplicateSlot = keccak256(abi.encodePacked(requestId, "UniqueNumberCheck"));
bytes32 checkCountSlot = keccak256(abi.encodePacked(requestId, "CheckCount"));
// Collect future block hashes for randomness
bytes32 blockHashesCumulative = bytes32(0);
for (uint j = 1; j <= 3 + request.extraSecurity; j++) {
bytes32 futureBlockHash = blockhash(request.requestBlock + j);
blockHashesCumulative = keccak256(abi.encodePacked(blockHashesCumulative, futureBlockHash));
}
// Generate random numbers
for (uint256 i = 0; i < request.count; i++) {
// Additional entropy for multi-number requests
bytes32 additionalEntropy = i > 0 ? blockhash(block.number - i - 1) : bytes32(0);
// Combine entropy sources
uint256 randomSource = uint256(keccak256(abi.encodePacked(
requestId,
blockHashesCumulative,
i,
additionalEntropy
)));
// Map to range
uint256 candidate;
if (request.includeZero) {
candidate = randomSource % (request.maxNumber + 1);
} else {
candidate = (randomSource % request.maxNumber) + 1;
}
// Check for duplicates and adjust using improved logic with transient storage
bytes32 candidateSlot = keccak256(abi.encodePacked(duplicateSlot, candidate));
bool isUsed;
assembly {
isUsed := tload(candidateSlot)
}
if (isUsed) {
// Store original candidate for expanding circle search
uint256 originalCandidate = candidate;
// Define range bounds
uint256 minValue = request.includeZero ? 0 : 1;
uint256 maxValue = request.maxNumber;
// Use transient storage for search increment counter
uint256 searchIncrement = 1;
assembly {
tstore(checkCountSlot, 1)
}
// Expanding circle search: ±1, ±2, ±3, etc.
while (isUsed && searchIncrement <= maxValue) {
bool upwardValid = (originalCandidate + searchIncrement) <= maxValue;
bool downwardValid = originalCandidate >= (minValue + searchIncrement);
// Try upward direction: original + i
if (upwardValid) {
candidate = originalCandidate + searchIncrement;
candidateSlot = keccak256(abi.encodePacked(duplicateSlot, candidate));
assembly {
isUsed := tload(candidateSlot)
}
// If found unique number, break immediately!
if (!isUsed) break;
}
// Try downward direction: original - i
if (downwardValid) {
candidate = originalCandidate - searchIncrement;
candidateSlot = keccak256(abi.encodePacked(duplicateSlot, candidate));
assembly {
isUsed := tload(candidateSlot)
}
// If found unique number, break immediately!
if (!isUsed) break;
}
// If both directions are out of bounds, we've searched the entire range
if (!upwardValid && !downwardValid) {
break;
}
// Increment search radius and update transient storage
searchIncrement++;
assembly {
tstore(checkCountSlot, searchIncrement)
}
}
// Final check: If we still haven't found a unique number, range is exhausted
if (isUsed) {
revert("Cannot generate unique numbers - range exhausted");
}
// Clean up transient storage
assembly {
tstore(checkCountSlot, 0)
}
}
// Mark as used in transient storage
assembly {
tstore(candidateSlot, 1)
}
randomNumbers[i] = candidate;
emit RandomNumberGenerated(requestId, msg.sender, randomNumbers[i]);
}
// Clean up ALL transient storage - reset all used number flags
for (uint256 i = 0; i < request.count; i++) {
bytes32 numberSlot = keccak256(abi.encodePacked(duplicateSlot, randomNumbers[i]));
assembly {
tstore(numberSlot, 0)
}
}
// Clean up search increment counter (in case it wasn't cleaned during collision resolution)
assembly {
tstore(checkCountSlot, 0)
}
// Clean up storage
delete randomRequests[requestId];
return randomNumbers;
}
/**
* @inheritdoc IBasedRandomness
*/
function batchGenerateRandomNumbers(bytes32[] calldata requestIds) external returns (uint256[][] memory) {
uint256[][] memory randomNumbers = new uint256[][](requestIds.length);
for (uint256 i = 0; i < requestIds.length; i++) {
randomNumbers[i] = generateRandomNumbers(requestIds[i]);
}
return randomNumbers;
}
// ═══════════════════════════════════════════════════════════════════
// ENTROPY GENERATION
// ═══════════════════════════════════════════════════════════════════
/**
* @dev Generate entropy from DEX pool balances and token supplies
* @return entropy Combined hash of all entropy sources
*/
function getEntropy() private view returns (bytes32) {
return keccak256(abi.encodePacked(
// Pool balances
IERC20(USDC_TOKEN).balanceOf(UNI_USDC_ETH_V2),
IERC20(WETH_TOKEN).balanceOf(UNI_USDC_ETH_V2),
IERC20(USDC_TOKEN).balanceOf(UNI_USDC_ETH_03),
IERC20(WETH_TOKEN).balanceOf(UNI_USDC_ETH_03),
IERC20(USDC_TOKEN).balanceOf(UNI_04),
IERC20(WETH_TOKEN).balanceOf(UNI_04),
// Token supplies
IERC20(USDC_TOKEN).totalSupply(),
IERC20(WETH_TOKEN).totalSupply()
));
}
}