# [译]区块链上生成随机数

## 区块链上如何实现伪随机数.

pragma solidity ^0.5.8;

/**
* @title True random number generator
* @notice This is a contract to generate a true random number on blockchai.
* Though true random number generators doesn't require seed. But, to simplify
* the functions i used seed and other terms used in PRNGs,
* seed should be enough to generate a random number, but to randomize the pattern
* even more i added two more functions with salt and sugar.
*/
contract PRNG {
/**
* @notice Generates a random number between 0 - 100
* @param seed The seed to generate different number if block.timestamp is same
* for two or more numbers.
*/
function importSeedFromThird(uint256 seed) public view returns (uint8) {
uint8 randomNumber = uint8(
uint256(keccak256(abi.encodePacked(block.timestamp, seed))) % 100
);
return randomNumber;
}

/**
* @notice Generates a random number between 0 - 100
* @param seed The seed to generate different number if block.timestamp is same
* for two or more numbers.
* @param salt The salt to randomize the pattern
*/
function importSeedFromThirdSalt(uint256 seed, uint256 salt)
public
view
returns (uint8)
{
uint8 randomNumber = uint8(uint256(keccak256(abi.encodePacked(block.timestamp, seed, salt))) % 100);
return randomNumber;
}

/**
* @notice Generates a random number between 0 - 100
* @param seed The seed to generate different number if block.timestamp is same
* for two or more numbers.
* @param salt The salt to randomize the pattern
* @param sugar The sugar same as salt but for more randomization
*/
function importSeedFromThirdSaltSugar(
uint256 seed,
uint256 salt,
uint256 sugar
) public view returns (uint8) {
uint8 randomNumber = uint8(uint256(keccak256(abi.encodePacked(block.timestamp, seed, salt, sugar))) % 100);
return randomNumber;
}
}

• importSeedFromThird：只需要种子的Solidity随机数发生器

• importSeedFromThirdSalt：需要种子、盐的Solidity随机数发生器

• importSeedFromThirdSaltSugar：需要种子、盐、糖的Solidity随机数发生器

abi.encodePacked紧密打包数据的bytes而没有任何填充，因为如果没有填充，则无法从此函数中提取数据。函数返回 bytes 类型，可以转化为 uint256 类型。参考Solidity 中文文档 keccak256sha3 类似的 hash函数，只是采用不同的补齐模式，具体可以参考 这里 .