-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcryptographic-functions
56 lines (41 loc) · 2.07 KB
/
cryptographic-functions
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
pragma solidity ^0.8.2;
/*
Algos for reference:
- keccak256(bytes memory) returns (bytes32) − computes the Keccak-256 hash of the input.
- sha256(bytes memory) returns (bytes32) − computes the SHA-256 hash of the input.
- ripemd160(bytes memory) returns (bytes20) − compute RIPEMD-160 hash of the input.
Exercise: (Secure Random Functionality From Miner Manipulation):
1. Build a random number generator which takes an input range and uses cryptographic hashing
modulo (%) - so by computing against the remainder we will be able to produce a random number within a range
cryptographic hashing
2. Create a contract Oracle with an address datatype called admin and a public integer called rand.
3. Create a constructor and set the admin to the current caller.
4. Write a function which takes the input of an integer and sets the state variable rand to that integer.
5. Require that the current caller must equal the admin.
6. Set the oracle contract to a new variable called oracle in the GenerateRandomNumber contract (hint calling contracts)
7. Write a constructor in the GenerateRandomNumber contract which sets the oracle to a deployment address of the Oracle
8. Modify the hash return so that the miners greatly lesson control manipulation to the random generation.
9. Successfully deploy and test the results.
*/
// (already outdated, now that mainnet difficulty is 0)
contract MyFirstRandomNumberGenerator {
Oracle oracle;
constructor(address oracleAddress) {
oracle = Oracle(oracleAddress);
}
function randMod(uint range) external view returns(uint) {
return uint(keccak256(abi.encodePacked(oracle.rand(),block.timestamp, block.difficulty, msg.sender))) % range;
}
}
//note to self: this oracle contract probably isn't secure enough for IRL use. Ideally should use Chainlink's VRF instead, to make result less-gameable
contract Oracle {
address admin;
uint public rand;
constructor() {
admin = msg.sender;
}
function feedRand(uint _rand) external {
require (msg.sender == admin);
rand = _rand;
}
}