Last active
November 13, 2018 10:26
-
-
Save resilience-me/d439a629929cd45a141e8429cd962766 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
contract MazeHashFunction { | |
function generateRandomNumber(uint _treasureMap) view public returns (uint) { | |
bytes memory randomNumber = new bytes(32); | |
bytes memory treasureMapInBytes = toBytes(_treasureMap); | |
uint8 nextByteInTreasureMap = uint8(treasureMapInBytes[31]); | |
uint8 pointerToNextPosition = nextByteInTreasureMap; | |
for(uint i = 31; i >0; i--) { | |
uint nextHashInLabyrinth = uint(blockhash(block.number - 1 - pointerToNextPosition)); | |
bytes memory blockHashToBytes = toBytes(nextHashInLabyrinth); | |
uint8 byteFromBlockhash = uint8(blockHashToBytes[i]); | |
nextByteInTreasureMap = uint8(treasureMapInBytes[i]); | |
uint8 nextRandomNumber = nextByteInTreasureMap ^ byteFromBlockhash; | |
randomNumber[i] = bytes1(nextRandomNumber); | |
pointerToNextPosition = nextRandomNumber; | |
} | |
return toUint(randomNumber); | |
} | |
function toBytes(uint256 x) pure internal returns (bytes b) { | |
b = new bytes(32); | |
assembly { mstore(add(b, 32), x) } | |
} | |
function toUint(bytes x) pure internal returns (uint b) { | |
assembly { | |
b := mload(add(x, 0x20)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment