Skip to content

Instantly share code, notes, and snippets.

@SergioDemianLerner
Last active October 29, 2020 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergioDemianLerner/80d9ac7e60151360c4eed11be00e16c3 to your computer and use it in GitHub Desktop.
Save SergioDemianLerner/80d9ac7e60151360c4eed11be00e16c3 to your computer and use it in GitHub Desktop.
CryptoRandomBlockheader
pragma solidity >=0.4.0 <0.7.0;
abstract contract IBlockHeaderPrecompiledContract {
function getBitcoinHeader(int256 indexBlock) public virtual view returns (bytes memory coinbase);
}
contract CryptoRandomBlockheader {
IBlockHeaderPrecompiledContract blockHeader =
IBlockHeaderPrecompiledContract(0x0000000000000000000000000000000001000010);
bool public waitForRandom;
uint public deadline;
function debug_queryLastMergeMiningHeaderHash() public returns (bytes32) {
return bitcoiMergeMiningnHeaderHash(block.number - 1);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function isRandomSeedReady() public view returns (bool) {
if (!waitForRandom)
return false;
require(block.number<deadline+4000);
// Assure the deadline block has been mined, and it has 60
// confirmations (30 minutes)
return block.number>=deadline+6;
}
function getRandomSeed() public returns (bytes32) {
require(isRandomSeedReady());
waitForRandom = false;
return bitcoiMergeMiningnHeaderHash(deadline);
}
function startWaitForRandomValue() public {
// Wait approximately one hour
deadline = block.number+12;
waitForRandom = true;
}
function bitcoiMergeMiningnHeaderHash (uint index) public view returns (bytes32) {
bytes memory header = blockHeader.getBitcoinHeader(int256(block.number-1-index));
bytes32 x = sha256(header);
bytes32 y = sha256(abi.encodePacked(x));
return y;
}
function bytesToBytes32(bytes memory source) private pure returns (bytes32 result) {
if (source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment