Random numbers are numbers that occur in a sequence with the following two mandatory conditions:
- The values are uniformly distributed over a set interval.
- One cannot predict future values based on past outputs.
Example: In the below example, we have created a contract with a function that will generate a random number. Below is the step by step description of the entire process to be followed.
Step 1: Take the instance of now, the msg.sender, and an incrementing nonce.
Step 2: “pack” the inputs and use keccak256() to convert into 256-bit hash.
Step 3: Convert that hash to an uint, and then use % 100 to take only the last 2 digits. This will give us a totally random number between 0 and 99.
Possible attacks with this approach:
In Ethereum, all nodes are trying to solve the problem and verify the transaction. Once a node verifies it, it broadcasts it to the network.
Suppose we create a DApp where we flip a coin where the head is the winning side. We use the above function to predict heads or tails. If I were running a node, I could publish a transaction only to my own node and not share it. I will run the randMod function or the coin flip function until I will and will only share the transaction after I have won.
One way to solve this would be to use an oracle to access a random number function from outside the Ethereum blockchain. There are other cryptographic algorithms and third party functions that can be utilized, but they are not safe or should be audited.
- Steps to Execute Solidity Smart Contract using Remix IDE
- Creating a Smart Contract that Returns Address and Balance of Owner using Solidity
- Solidity - Types
- Solidity - Functions
- What are Events in Solidity?
- Solidity - Inheritance
- Solidity - Polymorphism
- Solidity - View and Pure Functions
- Solidity - Encapsulation
- Solidity - Abstract Contract
- How to Install Solidity in Windows?
- Solidity - While, Do-While, and For Loop
- Solidity - Break and Continue Statements
- Solidity - Variables
- Solidity - Error Handling
- Solidity - Arrays
- Solidity - Enums and Structs
- Solidity - Libraries
- Introduction to Solidity
- Solidity - Constructors
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.