Random
2020-11-24 本文已影响0人
小吖么小一郎
pragma solidity 0.6.2;
/*
获取随机数
*/
contract Random{
function getSalt() private view returns(uint256){
return now + block.number + tx.origin.balance + uint160(tx.origin) + 113054462744175736859760933276506452880756369766118458860348233028355831172232;
}
function getRandom() public view returns(uint256) {
uint256 a = getSalt();
bytes memory s = uintToBytes(a);
bytes32 b = sha256(bytes(s));
string memory str = new string(b.length);
bytes memory c = bytes(str);
for(uint256 i=0;i<b.length;i++){
c[i] = b[i];
}
return bytesToUint(c) % 10;
}
function uintToBytes(uint256 x) private pure returns (bytes memory c) {
bytes32 b = bytes32(x);
c = new bytes(32);
for (uint i=0; i < 32; i++) {
c[i] = b[i];
}
}
function bytesToUint(bytes memory b) private pure returns (uint256){
uint256 number;
for(uint i= 0; i<b.length; i++){
number = number + uint8(b[i])*(2**(8*(b.length-(i+1))));
}
return number;
}
}