Skip to content

Instantly share code, notes, and snippets.

@resilience-me
Last active November 13, 2018 10:26
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save resilience-me/d439a629929cd45a141e8429cd962766 to your computer and use it in GitHub Desktop.
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