For ethfuzz

Signed-off-by: Tuan-Dat Tran <tuan-dat.tran@tudattr.dev>
This commit is contained in:
Tuan-Dat Tran
2024-04-05 10:31:37 +02:00
parent 618cc4b670
commit dcd76c08e6
25 changed files with 0 additions and 4576 deletions

View File

@@ -1,76 +0,0 @@
The research paper "Empirical Review of Automated Analysis Tools
on 47,587 Ethereum Smart Contracts" used a version of SB Curated
with the 69 contracts listed below.
(Link to paper: https://arxiv.org/abs/1910.10601)
./dataset/short_addresses/short_address_example.sol
./dataset/unchecked_low_level_calls/king_of_the_ether_throne.sol
./dataset/unchecked_low_level_calls/etherpot_lotto.sol
./dataset/unchecked_low_level_calls/FibonacciBalance.sol [MOVED TO: ./access_control/FibonacciBalance.sol]
./dataset/unchecked_low_level_calls/unchecked_return_value.sol
./dataset/unchecked_low_level_calls/lotto.sol
./dataset/time_manipulation/timed_crowdsale.sol
./dataset/time_manipulation/ether_lotto.sol
./dataset/time_manipulation/roulette.sol
./dataset/time_manipulation/governmental_survey.sol
./dataset/bad_randomness/random_number_generator.sol
./dataset/bad_randomness/blackjack.sol
./dataset/bad_randomness/lucky_doubler.sol
./dataset/bad_randomness/etheraffle.sol
./dataset/bad_randomness/lottery.sol
./dataset/bad_randomness/old_blockhash.sol
./dataset/bad_randomness/smart_billions.sol
./dataset/bad_randomness/guess_the_random_number.sol
./dataset/reentrancy/etherstore.sol
./dataset/reentrancy/reentrancy_dao.sol
./dataset/reentrancy/modifier_reentrancy.sol
./dataset/reentrancy/reentrance.sol
./dataset/reentrancy/reentrancy_simple.sol
./dataset/reentrancy/simple_dao.sol
./dataset/reentrancy/spank_chain_payment.sol
./dataset/other/crypto_roulette.sol
./dataset/other/name_registrar.sol
./dataset/other/open_address_lottery.sol
./dataset/arithmetic/overflow_single_tx.sol
./dataset/arithmetic/tokensalechallenge.sol
./dataset/arithmetic/integer_overflow_minimal.sol
./dataset/arithmetic/integer_overflow_multitx_multifunc_feasible.sol
./dataset/arithmetic/overflow_simple_add.sol
./dataset/arithmetic/BECToken.sol
./dataset/arithmetic/integer_overflow_multitx_onefunc_feasible.sol
./dataset/arithmetic/integer_overflow_mul.sol
./dataset/arithmetic/integer_overflow_benign_1.sol
./dataset/arithmetic/integer_overflow_add.sol
./dataset/arithmetic/integer_overflow_1.sol
./dataset/arithmetic/integer_overflow_mapping_sym_1.sol
./dataset/arithmetic/token.sol
./dataset/arithmetic/timelock.sol
./dataset/denial_of_service/send_loop.sol
./dataset/denial_of_service/dos_number.sol
./dataset/denial_of_service/auction.sol
./dataset/denial_of_service/list_dos.sol
./dataset/denial_of_service/dos_simple.sol
./dataset/denial_of_service/dos_address.sol
./dataset/access_control/multiowned_vulnerable.sol
./dataset/access_control/rubixi.sol
./dataset/access_control/incorrect_constructor_name3.sol
./dataset/access_control/incorrect_constructor_name2.sol
./dataset/access_control/mycontract.sol
./dataset/access_control/wallet_04_confused_sign.sol
./dataset/access_control/phishable.sol
./dataset/access_control/arbitrary_location_write_simple.sol
./dataset/access_control/proxy.sol
./dataset/access_control/simple_suicide.sol
./dataset/access_control/parity_wallet_bug_1.sol
./dataset/access_control/parity_wallet_bug_2.sol
./dataset/access_control/wallet_02_refund_nosub.sol
./dataset/access_control/mapping_write.sol
./dataset/access_control/wallet_03_wrong_constructor.sol
./dataset/access_control/unprotected0.sol
./dataset/access_control/incorrect_constructor_name1.sol
./dataset/front_running/FindThisHash.sol
./dataset/front_running/eth_tx_order_dependence_minimal.sol
./dataset/front_running/ERC20.sol
./dataset/front_running/odds_and_evens.sol

View File

@@ -1,38 +0,0 @@
# Bad Randomness
Also known as nothing is secret.
Randomness is hard to get right in Ethereum. While Solidity offers functions and variables that can access apparently hard-to-predict values, they are generally either more public than they seem or subject to miners' influence. Because these sources of randomness are to an extent predictable, malicious users can generally replicate it and attack the function relying on its unpredictablility.
Loss: more than 400 ETH
## Attack Scenario
A smart contract uses the block number as a source of randomness for a game.
An attacker creates a malicious contract that checks if the current block number is a winner. If so, it calls the first smart contract in order to win; since the call will be part of the same transaction, the block number will remain the same on both contracts.
The attacker only has to call her malicious contract until it wins.
## Examples
In this first example, a private seed is used in combination with an iteration number and the keccak256 hash function to determine if the caller wins. Even though the seed is private, it must have been set via a transaction at some point in time and thus is visible on the blockchain.
```
uint256 private seed;
function play() public payable {
require(msg.value >= 1 ether);
iteration++;
uint randomNumber = uint(keccak256(seed + iteration));
if (randomNumber % 2 == 0) {
msg.sender.transfer(this.balance);
}
}
```
In this second example, block.blockhash is being used to generate a random number. This hash is unknown if the blockNumber is set to the current block.number (for obvious reasons), and is thus set to 0. In the case where the blockNumber is set to more than 256 blocks in the past, it will always be zero. Finally, if it is set to a previous block number that is not too old, another smart contract can access the same number and call the game contract as part of the same transaction.
```
function play() public payable {
require(msg.value >= 1 ether);
if (block.blockhash(blockNumber) % 2 == 0) {
msg.sender.transfer(this.balance);
}
}
```
## References
Taken from [DASP TOP10](https://dasp.co/)

View File

@@ -1,308 +0,0 @@
/*
* @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
* @source: https://etherscan.io/address/0xa65d59708838581520511d98fb8b5d1f76a96cad#code
* @vulnerable_at_lines: 17,19,21
* @author: -
*/
pragma solidity ^0.4.2;
library Deck {
// returns random number from 0 to 51
// let's say 'value' % 4 means suit (0 - Hearts, 1 - Spades, 2 - Diamonds, 3 - Clubs)
// 'value' / 4 means: 0 - King, 1 - Ace, 2 - 10 - pip values, 11 - Jacket, 12 - Queen
function deal(address player, uint8 cardNumber) internal returns (uint8) {
// <yes> <report> BAD_RANDOMNESS
uint b = block.number;
// <yes> <report> BAD_RANDOMNESS
uint timestamp = block.timestamp;
// <yes> <report> BAD_RANDOMNESS
return uint8(uint256(keccak256(block.blockhash(b), player, cardNumber, timestamp)) % 52);
}
function valueOf(uint8 card, bool isBigAce) internal constant returns (uint8) {
uint8 value = card / 4;
if (value == 0 || value == 11 || value == 12) { // Face cards
return 10;
}
if (value == 1 && isBigAce) { // Ace is worth 11
return 11;
}
return value;
}
function isAce(uint8 card) internal constant returns (bool) {
return card / 4 == 1;
}
function isTen(uint8 card) internal constant returns (bool) {
return card / 4 == 10;
}
}
contract BlackJack {
using Deck for *;
uint public minBet = 50 finney; // 0.05 eth
uint public maxBet = 5 ether;
uint8 BLACKJACK = 21;
enum GameState { Ongoing, Player, Tie, House }
struct Game {
address player; // address игрока
uint bet; // стывка
uint8[] houseCards; // карты диллера
uint8[] playerCards; // карты игрока
GameState state; // состояние
uint8 cardsDealt;
}
mapping (address => Game) public games;
modifier gameIsGoingOn() {
if (games[msg.sender].player == 0 || games[msg.sender].state != GameState.Ongoing) {
throw; // game doesn't exist or already finished
}
_;
}
event Deal(
bool isUser,
uint8 _card
);
event GameStatus(
uint8 houseScore,
uint8 houseScoreBig,
uint8 playerScore,
uint8 playerScoreBig
);
event Log(
uint8 value
);
function BlackJack() {
}
function () payable {
}
// starts a new game
function deal() public payable {
if (games[msg.sender].player != 0 && games[msg.sender].state == GameState.Ongoing) {
throw; // game is already going on
}
if (msg.value < minBet || msg.value > maxBet) {
throw; // incorrect bet
}
uint8[] memory houseCards = new uint8[](1);
uint8[] memory playerCards = new uint8[](2);
// deal the cards
playerCards[0] = Deck.deal(msg.sender, 0);
Deal(true, playerCards[0]);
houseCards[0] = Deck.deal(msg.sender, 1);
Deal(false, houseCards[0]);
playerCards[1] = Deck.deal(msg.sender, 2);
Deal(true, playerCards[1]);
games[msg.sender] = Game({
player: msg.sender,
bet: msg.value,
houseCards: houseCards,
playerCards: playerCards,
state: GameState.Ongoing,
cardsDealt: 3
});
checkGameResult(games[msg.sender], false);
}
// deals one more card to the player
function hit() public gameIsGoingOn {
uint8 nextCard = games[msg.sender].cardsDealt;
games[msg.sender].playerCards.push(Deck.deal(msg.sender, nextCard));
games[msg.sender].cardsDealt = nextCard + 1;
Deal(true, games[msg.sender].playerCards[games[msg.sender].playerCards.length - 1]);
checkGameResult(games[msg.sender], false);
}
// finishes the game
function stand() public gameIsGoingOn {
var (houseScore, houseScoreBig) = calculateScore(games[msg.sender].houseCards);
while (houseScoreBig < 17) {
uint8 nextCard = games[msg.sender].cardsDealt;
uint8 newCard = Deck.deal(msg.sender, nextCard);
games[msg.sender].houseCards.push(newCard);
games[msg.sender].cardsDealt = nextCard + 1;
houseScoreBig += Deck.valueOf(newCard, true);
Deal(false, newCard);
}
checkGameResult(games[msg.sender], true);
}
// @param finishGame - whether to finish the game or not (in case of Blackjack the game finishes anyway)
function checkGameResult(Game game, bool finishGame) private {
// calculate house score
var (houseScore, houseScoreBig) = calculateScore(game.houseCards);
// calculate player score
var (playerScore, playerScoreBig) = calculateScore(game.playerCards);
GameStatus(houseScore, houseScoreBig, playerScore, playerScoreBig);
if (houseScoreBig == BLACKJACK || houseScore == BLACKJACK) {
if (playerScore == BLACKJACK || playerScoreBig == BLACKJACK) {
// TIE
if (!msg.sender.send(game.bet)) throw; // return bet to the player
games[msg.sender].state = GameState.Tie; // finish the game
return;
} else {
// HOUSE WON
games[msg.sender].state = GameState.House; // simply finish the game
return;
}
} else {
if (playerScore == BLACKJACK || playerScoreBig == BLACKJACK) {
// PLAYER WON
if (game.playerCards.length == 2 && (Deck.isTen(game.playerCards[0]) || Deck.isTen(game.playerCards[1]))) {
// Natural blackjack => return x2.5
if (!msg.sender.send((game.bet * 5) / 2)) throw; // send prize to the player
} else {
// Usual blackjack => return x2
if (!msg.sender.send(game.bet * 2)) throw; // send prize to the player
}
games[msg.sender].state = GameState.Player; // finish the game
return;
} else {
if (playerScore > BLACKJACK) {
// BUST, HOUSE WON
Log(1);
games[msg.sender].state = GameState.House; // finish the game
return;
}
if (!finishGame) {
return; // continue the game
}
// недобор
uint8 playerShortage = 0;
uint8 houseShortage = 0;
// player decided to finish the game
if (playerScoreBig > BLACKJACK) {
if (playerScore > BLACKJACK) {
// HOUSE WON
games[msg.sender].state = GameState.House; // simply finish the game
return;
} else {
playerShortage = BLACKJACK - playerScore;
}
} else {
playerShortage = BLACKJACK - playerScoreBig;
}
if (houseScoreBig > BLACKJACK) {
if (houseScore > BLACKJACK) {
// PLAYER WON
if (!msg.sender.send(game.bet * 2)) throw; // send prize to the player
games[msg.sender].state = GameState.Player;
return;
} else {
houseShortage = BLACKJACK - houseScore;
}
} else {
houseShortage = BLACKJACK - houseScoreBig;
}
// ?????????????????????? почему игра заканчивается?
if (houseShortage == playerShortage) {
// TIE
if (!msg.sender.send(game.bet)) throw; // return bet to the player
games[msg.sender].state = GameState.Tie;
} else if (houseShortage > playerShortage) {
// PLAYER WON
if (!msg.sender.send(game.bet * 2)) throw; // send prize to the player
games[msg.sender].state = GameState.Player;
} else {
games[msg.sender].state = GameState.House;
}
}
}
}
function calculateScore(uint8[] cards) private constant returns (uint8, uint8) {
uint8 score = 0;
uint8 scoreBig = 0; // in case of Ace there could be 2 different scores
bool bigAceUsed = false;
for (uint i = 0; i < cards.length; ++i) {
uint8 card = cards[i];
if (Deck.isAce(card) && !bigAceUsed) { // doesn't make sense to use the second Ace as 11, because it leads to the losing
scoreBig += Deck.valueOf(card, true);
bigAceUsed = true;
} else {
scoreBig += Deck.valueOf(card, false);
}
score += Deck.valueOf(card, false);
}
return (score, scoreBig);
}
function getPlayerCard(uint8 id) public gameIsGoingOn constant returns(uint8) {
if (id < 0 || id > games[msg.sender].playerCards.length) {
throw;
}
return games[msg.sender].playerCards[id];
}
function getHouseCard(uint8 id) public gameIsGoingOn constant returns(uint8) {
if (id < 0 || id > games[msg.sender].houseCards.length) {
throw;
}
return games[msg.sender].houseCards[id];
}
function getPlayerCardsNumber() public gameIsGoingOn constant returns(uint) {
return games[msg.sender].playerCards.length;
}
function getHouseCardsNumber() public gameIsGoingOn constant returns(uint) {
return games[msg.sender].houseCards.length;
}
function getGameState() public constant returns (uint8) {
if (games[msg.sender].player == 0) {
throw; // game doesn't exist
}
Game game = games[msg.sender];
if (game.state == GameState.Player) {
return 1;
}
if (game.state == GameState.House) {
return 2;
}
if (game.state == GameState.Tie) {
return 3;
}
return 0; // the game is still going on
}
}

View File

@@ -1,174 +0,0 @@
/*
* @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
* @source: https://etherscan.io/address/0xcC88937F325d1C6B97da0AFDbb4cA542EFA70870#code
* @vulnerable_at_lines: 49,99,101,103,114,158
* @author: -
*/
pragma solidity ^0.4.16;
contract Ethraffle_v4b {
struct Contestant {
address addr;
uint raffleId;
}
event RaffleResult(
uint raffleId,
uint winningNumber,
address winningAddress,
address seed1,
address seed2,
uint seed3,
bytes32 randHash
);
event TicketPurchase(
uint raffleId,
address contestant,
uint number
);
event TicketRefund(
uint raffleId,
address contestant,
uint number
);
// Constants
uint public constant prize = 2.5 ether;
uint public constant fee = 0.03 ether;
uint public constant totalTickets = 50;
uint public constant pricePerTicket = (prize + fee) / totalTickets; // Make sure this divides evenly
address feeAddress;
// Other internal variables
bool public paused = false;
uint public raffleId = 1;
// <yes> <report> BAD_RANDOMNESS
uint public blockNumber = block.number;
uint nextTicket = 0;
mapping (uint => Contestant) contestants;
uint[] gaps;
// Initialization
function Ethraffle_v4b() public {
feeAddress = msg.sender;
}
// Call buyTickets() when receiving Ether outside a function
function () payable public {
buyTickets();
}
function buyTickets() payable public {
if (paused) {
msg.sender.transfer(msg.value);
return;
}
uint moneySent = msg.value;
while (moneySent >= pricePerTicket && nextTicket < totalTickets) {
uint currTicket = 0;
if (gaps.length > 0) {
currTicket = gaps[gaps.length-1];
gaps.length--;
} else {
currTicket = nextTicket++;
}
contestants[currTicket] = Contestant(msg.sender, raffleId);
TicketPurchase(raffleId, msg.sender, currTicket);
moneySent -= pricePerTicket;
}
// Choose winner if we sold all the tickets
if (nextTicket == totalTickets) {
chooseWinner();
}
// Send back leftover money
if (moneySent > 0) {
msg.sender.transfer(moneySent);
}
}
function chooseWinner() private {
// <yes> <report> BAD_RANDOMNESS
address seed1 = contestants[uint(block.coinbase) % totalTickets].addr;
// <yes> <report> BAD_RANDOMNESS
address seed2 = contestants[uint(msg.sender) % totalTickets].addr;
// <yes> <report> BAD_RANDOMNESS
uint seed3 = block.difficulty;
bytes32 randHash = keccak256(seed1, seed2, seed3);
uint winningNumber = uint(randHash) % totalTickets;
address winningAddress = contestants[winningNumber].addr;
RaffleResult(raffleId, winningNumber, winningAddress, seed1, seed2, seed3, randHash);
// Start next raffle
raffleId++;
nextTicket = 0;
// <yes> <report> BAD_RANDOMNESS
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);
}
// Get your money back before the raffle occurs
function getRefund() public {
uint refund = 0;
for (uint i = 0; i < totalTickets; i++) {
if (msg.sender == contestants[i].addr && raffleId == contestants[i].raffleId) {
refund += pricePerTicket;
contestants[i] = Contestant(address(0), 0);
gaps.push(i);
TicketRefund(raffleId, msg.sender, i);
}
}
if (refund > 0) {
msg.sender.transfer(refund);
}
}
// Refund everyone's money, start a new raffle, then pause it
function endRaffle() public {
if (msg.sender == feeAddress) {
paused = true;
for (uint i = 0; i < totalTickets; i++) {
if (raffleId == contestants[i].raffleId) {
TicketRefund(raffleId, contestants[i].addr, i);
contestants[i].addr.transfer(pricePerTicket);
}
}
RaffleResult(raffleId, totalTickets, address(0), address(0), address(0), 0, 0);
raffleId++;
nextTicket = 0;
// <yes> <report> BAD_RANDOMNESS
blockNumber = block.number;
gaps.length = 0;
}
}
function togglePause() public {
if (msg.sender == feeAddress) {
paused = !paused;
}
}
function kill() public {
if (msg.sender == feeAddress) {
selfdestruct(feeAddress);
}
}
}

View File

@@ -1,29 +0,0 @@
/*
* @source: https://capturetheether.com/challenges/lotteries/guess-the-random-number/
* @author: Steve Marx
* @vulnerable_at_lines: 15
*/
pragma solidity ^0.4.21;
contract GuessTheRandomNumberChallenge {
uint8 answer;
function GuessTheRandomNumberChallenge() public payable {
require(msg.value == 1 ether);
// <yes> <report> BAD_RANDOMNESS
answer = uint8(keccak256(block.blockhash(block.number - 1), now));
}
function isComplete() public view returns (bool) {
return address(this).balance == 0;
}
function guess(uint8 n) public payable {
require(msg.value == 1 ether);
if (n == answer) {
msg.sender.transfer(2 ether);
}
}
}

View File

@@ -1,68 +0,0 @@
/*
* @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
* @source: https://etherscan.io/address/0x80ddae5251047d6ceb29765f38fed1c0013004b7#code
* @vulnerable_at_lines: 38,42
* @author: -
*/
//added pragma version
pragma solidity ^0.4.0;
contract Lottery {
event GetBet(uint betAmount, uint blockNumber, bool won);
struct Bet {
uint betAmount;
uint blockNumber;
bool won;
}
address private organizer;
Bet[] private bets;
// Create a new lottery with numOfBets supported bets.
function Lottery() {
organizer = msg.sender;
}
// Fallback function returns ether
function() {
throw;
}
// Make a bet
function makeBet() {
// Won if block number is even
// (note: this is a terrible source of randomness, please don't use this with real money)
// <yes> <report> BAD_RANDOMNESS
bool won = (block.number % 2) == 0;
// Record the bet with an event
// <yes> <report> BAD_RANDOMNESS
bets.push(Bet(msg.value, block.number, won));
// Payout if the user won, otherwise take their money
if(won) {
if(!msg.sender.send(msg.value)) {
// Return ether to sender
throw;
}
}
}
// Get all bets that have been made
function getBets() {
if(msg.sender != organizer) { throw; }
for (uint i = 0; i < bets.length; i++) {
GetBet(bets[i].betAmount, bets[i].blockNumber, bets[i].won);
}
}
// Suicide :(
function destroy() {
if(msg.sender != organizer) { throw; }
suicide(organizer);
}
}

View File

@@ -1,191 +0,0 @@
/*
* @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
* @source: https://etherscan.io/address/0xF767fCA8e65d03fE16D4e38810f5E5376c3372A8#code
* @vulnerable_at_lines: 127,128,129,130,132
* @author: -
*/
//added pragma version
pragma solidity ^0.4.0;
contract LuckyDoubler {
//##########################################################
//#### LuckyDoubler: A doubler with random payout order ####
//#### Deposit 1 ETHER to participate ####
//##########################################################
//COPYRIGHT 2016 KATATSUKI ALL RIGHTS RESERVED
//No part of this source code may be reproduced, distributed,
//modified or transmitted in any form or by any means without
//the prior written permission of the creator.
address private owner;
//Stored variables
uint private balance = 0;
uint private fee = 5;
uint private multiplier = 125;
mapping (address => User) private users;
Entry[] private entries;
uint[] private unpaidEntries;
//Set owner on contract creation
function LuckyDoubler() {
owner = msg.sender;
}
modifier onlyowner { if (msg.sender == owner) _; }
struct User {
address id;
uint deposits;
uint payoutsReceived;
}
struct Entry {
address entryAddress;
uint deposit;
uint payout;
bool paid;
}
//Fallback function
function() {
init();
}
function init() private{
if (msg.value < 1 ether) {
msg.sender.send(msg.value);
return;
}
join();
}
function join() private {
//Limit deposits to 1ETH
uint dValue = 1 ether;
if (msg.value > 1 ether) {
msg.sender.send(msg.value - 1 ether);
dValue = 1 ether;
}
//Add new users to the users array
if (users[msg.sender].id == address(0))
{
users[msg.sender].id = msg.sender;
users[msg.sender].deposits = 0;
users[msg.sender].payoutsReceived = 0;
}
//Add new entry to the entries array
entries.push(Entry(msg.sender, dValue, (dValue * (multiplier) / 100), false));
users[msg.sender].deposits++;
unpaidEntries.push(entries.length -1);
//Collect fees and update contract balance
balance += (dValue * (100 - fee)) / 100;
uint index = unpaidEntries.length > 1 ? rand(unpaidEntries.length) : 0;
Entry theEntry = entries[unpaidEntries[index]];
//Pay pending entries if the new balance allows for it
if (balance > theEntry.payout) {
uint payout = theEntry.payout;
theEntry.entryAddress.send(payout);
theEntry.paid = true;
users[theEntry.entryAddress].payoutsReceived++;
balance -= payout;
if (index < unpaidEntries.length - 1)
unpaidEntries[index] = unpaidEntries[unpaidEntries.length - 1];
unpaidEntries.length--;
}
//Collect money from fees and possible leftovers from errors (actual balance untouched)
uint fees = this.balance - balance;
if (fees > 0)
{
owner.send(fees);
}
}
//Generate random number between 0 & max
uint256 constant private FACTOR = 1157920892373161954235709850086879078532699846656405640394575840079131296399;
// <yes> <report> BAD_RANDOMNESS
function rand(uint max) constant private returns (uint256 result){
uint256 factor = FACTOR * 100 / max;
uint256 lastBlockNumber = block.number - 1;
uint256 hashVal = uint256(block.blockhash(lastBlockNumber));
return uint256((uint256(hashVal) / factor)) % max;
}
//Contract management
function changeOwner(address newOwner) onlyowner {
owner = newOwner;
}
function changeMultiplier(uint multi) onlyowner {
if (multi < 110 || multi > 150) throw;
multiplier = multi;
}
function changeFee(uint newFee) onlyowner {
if (fee > 5)
throw;
fee = newFee;
}
//JSON functions
function multiplierFactor() constant returns (uint factor, string info) {
factor = multiplier;
info = 'The current multiplier applied to all deposits. Min 110%, max 150%.';
}
function currentFee() constant returns (uint feePercentage, string info) {
feePercentage = fee;
info = 'The fee percentage applied to all deposits. It can change to speed payouts (max 5%).';
}
function totalEntries() constant returns (uint count, string info) {
count = entries.length;
info = 'The number of deposits.';
}
function userStats(address user) constant returns (uint deposits, uint payouts, string info)
{
if (users[user].id != address(0x0))
{
deposits = users[user].deposits;
payouts = users[user].payoutsReceived;
info = 'Users stats: total deposits, payouts received.';
}
}
function entryDetails(uint index) constant returns (address user, uint payout, bool paid, string info)
{
if (index < entries.length) {
user = entries[index].entryAddress;
payout = entries[index].payout / 1 finney;
paid = entries[index].paid;
info = 'Entry info: user address, expected payout in Finneys, payout status.';
}
}
}

View File

@@ -1,42 +0,0 @@
/*
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/weak_randomness/old_blockhash.sol
* @author: -
* @vulnerable_at_lines: 35
*/
pragma solidity ^0.4.24;
//Based on the the Capture the Ether challange at https://capturetheether.com/challenges/lotteries/predict-the-block-hash/
//Note that while it seems to have a 1/2^256 chance you guess the right hash, actually blockhash returns zero for blocks numbers that are more than 256 blocks ago so you can guess zero and wait.
contract PredictTheBlockHashChallenge {
struct guess{
uint block;
bytes32 guess;
}
mapping(address => guess) guesses;
constructor() public payable {
require(msg.value == 1 ether);
}
function lockInGuess(bytes32 hash) public payable {
require(guesses[msg.sender].block == 0);
require(msg.value == 1 ether);
guesses[msg.sender].guess = hash;
guesses[msg.sender].block = block.number + 1;
}
function settle() public {
require(block.number > guesses[msg.sender].block);
// <yes> <report> BAD_RANDOMNESS
bytes32 answer = blockhash(guesses[msg.sender].block);
guesses[msg.sender].block = 0;
if (guesses[msg.sender].guess == answer) {
msg.sender.transfer(2 ether);
}
}
}

View File

@@ -1,26 +0,0 @@
/*
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/weak_randomness/random_number_generator.sol
* @author: -
* @vulnerable_at_lines: 12,18,20,22
*/
pragma solidity ^0.4.25;
// Based on TheRun contract deployed at 0xcac337492149bDB66b088bf5914beDfBf78cCC18.
contract RandomNumberGenerator {
// <yes> <report> BAD_RANDOMNESS
uint256 private salt = block.timestamp;
function random(uint max) view private returns (uint256 result) {
// Get the best seed for randomness
uint256 x = salt * 100 / max;
// <yes> <report> BAD_RANDOMNESS
uint256 y = salt * block.number / (salt % 5);
// <yes> <report> BAD_RANDOMNESS
uint256 seed = block.number / 3 + (salt % 300) + y;
// <yes> <report> BAD_RANDOMNESS
uint256 h = uint256(blockhash(seed));
// Random number between 1 and max
return uint256((h / x)) % max + 1;
}
}

View File

@@ -1,771 +0,0 @@
/*
* @source: https://etherscan.io/address/0x5ace17f87c7391e5792a7683069a8025b83bbd85#code
* @author: -
* @vulnerable_at_lines: 523,560,700,702,704,706,708,710,712,714,716,718
*/
pragma solidity ^0.4.13;
library SafeMath {
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint public totalSupply;
address public owner; //owner
address public animator; //animator
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function commitDividend(address who) internal; // pays remaining dividend
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
commitDividend(msg.sender);
balances[msg.sender] = balances[msg.sender].sub(_value);
if(_to == address(this)) {
commitDividend(owner);
balances[owner] = balances[owner].add(_value);
Transfer(msg.sender, owner, _value);
}
else {
commitDividend(_to);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
commitDividend(_from);
commitDividend(_to);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title SmartBillions contract
*/
contract SmartBillions is StandardToken {
// metadata
string public constant name = "SmartBillions Token";
string public constant symbol = "PLAY";
uint public constant decimals = 0;
// contract state
struct Wallet {
uint208 balance; // current balance of user
uint16 lastDividendPeriod; // last processed dividend period of user's tokens
uint32 nextWithdrawBlock; // next withdrawal possible after this block number
}
mapping (address => Wallet) wallets;
struct Bet {
uint192 value; // bet size
uint32 betHash; // selected numbers
uint32 blockNum; // blocknumber when lottery runs
}
mapping (address => Bet) bets;
uint public walletBalance = 0; // sum of funds in wallets
// investment parameters
uint public investStart = 1; // investment start block, 0: closed, 1: preparation
uint public investBalance = 0; // funding from investors
uint public investBalanceMax = 200000 ether; // maximum funding
uint public dividendPeriod = 1;
uint[] public dividends; // dividens collected per period, growing array
// betting parameters
uint public maxWin = 0; // maximum prize won
uint public hashFirst = 0; // start time of building hashes database
uint public hashLast = 0; // last saved block of hashes
uint public hashNext = 0; // next available bet block.number
uint public hashBetSum = 0; // used bet volume of next block
uint public hashBetMax = 5 ether; // maximum bet size per block
uint[] public hashes; // space for storing lottery results
// constants
//uint public constant hashesSize = 1024 ; // DEBUG ONLY !!!
uint public constant hashesSize = 16384 ; // 30 days of blocks
uint public coldStoreLast = 0 ; // block of last cold store transfer
// events
event LogBet(address indexed player, uint bethash, uint blocknumber, uint betsize);
event LogLoss(address indexed player, uint bethash, uint hash);
event LogWin(address indexed player, uint bethash, uint hash, uint prize);
event LogInvestment(address indexed investor, address indexed partner, uint amount);
event LogRecordWin(address indexed player, uint amount);
event LogLate(address indexed player,uint playerBlockNumber,uint currentBlockNumber);
event LogDividend(address indexed investor, uint amount, uint period);
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
modifier onlyAnimator() {
assert(msg.sender == animator);
_;
}
// constructor
function SmartBillions() {
owner = msg.sender;
animator = msg.sender;
wallets[owner].lastDividendPeriod = uint16(dividendPeriod);
dividends.push(0); // not used
dividends.push(0); // current dividend
}
/* getters */
/**
* @dev Show length of allocated swap space
*/
function hashesLength() constant external returns (uint) {
return uint(hashes.length);
}
/**
* @dev Show balance of wallet
* @param _owner The address of the account.
*/
function walletBalanceOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].balance);
}
/**
* @dev Show last dividend period processed
* @param _owner The address of the account.
*/
function walletPeriodOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].lastDividendPeriod);
}
/**
* @dev Show block number when withdraw can continue
* @param _owner The address of the account.
*/
function walletBlockOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].nextWithdrawBlock);
}
/**
* @dev Show bet size.
* @param _owner The address of the player.
*/
function betValueOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].value);
}
/**
* @dev Show block number of lottery run for the bet.
* @param _owner The address of the player.
*/
function betHashOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].betHash);
}
/**
* @dev Show block number of lottery run for the bet.
* @param _owner The address of the player.
*/
function betBlockNumberOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].blockNum);
}
/**
* @dev Print number of block till next expected dividend payment
*/
function dividendsBlocks() constant external returns (uint) {
if(investStart > 0) {
return(0);
}
uint period = (block.number - hashFirst) / (10 * hashesSize);
if(period > dividendPeriod) {
return(0);
}
return((10 * hashesSize) - ((block.number - hashFirst) % (10 * hashesSize)));
}
/* administrative functions */
/**
* @dev Change owner.
* @param _who The address of new owner.
*/
function changeOwner(address _who) external onlyOwner {
assert(_who != address(0));
commitDividend(msg.sender);
commitDividend(_who);
owner = _who;
}
/**
* @dev Change animator.
* @param _who The address of new animator.
*/
function changeAnimator(address _who) external onlyAnimator {
assert(_who != address(0));
commitDividend(msg.sender);
commitDividend(_who);
animator = _who;
}
/**
* @dev Set ICO Start block.
* @param _when The block number of the ICO.
*/
function setInvestStart(uint _when) external onlyOwner {
require(investStart == 1 && hashFirst > 0 && block.number < _when);
investStart = _when;
}
/**
* @dev Set maximum bet size per block
* @param _maxsum The maximum bet size in wei.
*/
function setBetMax(uint _maxsum) external onlyOwner {
hashBetMax = _maxsum;
}
/**
* @dev Reset bet size accounting, to increase bet volume above safe limits
*/
function resetBet() external onlyOwner {
hashNext = block.number + 3;
hashBetSum = 0;
}
/**
* @dev Move funds to cold storage
* @dev investBalance and walletBalance is protected from withdraw by owner
* @dev if funding is > 50% admin can withdraw only 0.25% of balance weakly
* @param _amount The amount of wei to move to cold storage
*/
function coldStore(uint _amount) external onlyOwner {
houseKeeping();
require(_amount > 0 && this.balance >= (investBalance * 9 / 10) + walletBalance + _amount);
if(investBalance >= investBalanceMax / 2){ // additional jackpot protection
require((_amount <= this.balance / 400) && coldStoreLast + 4 * 60 * 24 * 7 <= block.number);
}
msg.sender.transfer(_amount);
coldStoreLast = block.number;
}
/**
* @dev Move funds to contract jackpot
*/
function hotStore() payable external {
houseKeeping();
}
/* housekeeping functions */
/**
* @dev Update accounting
*/
function houseKeeping() public {
if(investStart > 1 && block.number >= investStart + (hashesSize * 5)){ // ca. 14 days
investStart = 0; // start dividend payments
}
else {
if(hashFirst > 0){
uint period = (block.number - hashFirst) / (10 * hashesSize );
if(period > dividends.length - 2) {
dividends.push(0);
}
if(period > dividendPeriod && investStart == 0 && dividendPeriod < dividends.length - 1) {
dividendPeriod++;
}
}
}
}
/* payments */
/**
* @dev Pay balance from wallet
*/
function payWallet() public {
if(wallets[msg.sender].balance > 0 && wallets[msg.sender].nextWithdrawBlock <= block.number){
uint balance = wallets[msg.sender].balance;
wallets[msg.sender].balance = 0;
walletBalance -= balance;
pay(balance);
}
}
function pay(uint _amount) private {
uint maxpay = this.balance / 2;
if(maxpay >= _amount) {
msg.sender.transfer(_amount);
if(_amount > 1 finney) {
houseKeeping();
}
}
else {
uint keepbalance = _amount - maxpay;
walletBalance += keepbalance;
wallets[msg.sender].balance += uint208(keepbalance);
wallets[msg.sender].nextWithdrawBlock = uint32(block.number + 4 * 60 * 24 * 30); // wait 1 month for more funds
msg.sender.transfer(maxpay);
}
}
/* investment functions */
/**
* @dev Buy tokens
*/
function investDirect() payable external {
invest(owner);
}
/**
* @dev Buy tokens with affiliate partner
* @param _partner Affiliate partner
*/
function invest(address _partner) payable public {
//require(fromUSA()==false); // fromUSA() not yet implemented :-(
require(investStart > 1 && block.number < investStart + (hashesSize * 5) && investBalance < investBalanceMax);
uint investing = msg.value;
if(investing > investBalanceMax - investBalance) {
investing = investBalanceMax - investBalance;
investBalance = investBalanceMax;
investStart = 0; // close investment round
msg.sender.transfer(msg.value.sub(investing)); // send back funds immediately
}
else{
investBalance += investing;
}
if(_partner == address(0) || _partner == owner){
walletBalance += investing / 10;
wallets[owner].balance += uint208(investing / 10);} // 10% for marketing if no affiliates
else{
walletBalance += (investing * 5 / 100) * 2;
wallets[owner].balance += uint208(investing * 5 / 100); // 5% initial marketing funds
wallets[_partner].balance += uint208(investing * 5 / 100);} // 5% for affiliates
wallets[msg.sender].lastDividendPeriod = uint16(dividendPeriod); // assert(dividendPeriod == 1);
uint senderBalance = investing / 10**15;
uint ownerBalance = investing * 16 / 10**17 ;
uint animatorBalance = investing * 10 / 10**17 ;
balances[msg.sender] += senderBalance;
balances[owner] += ownerBalance ; // 13% of shares go to developers
balances[animator] += animatorBalance ; // 8% of shares go to animator
totalSupply += senderBalance + ownerBalance + animatorBalance;
Transfer(address(0),msg.sender,senderBalance); // for etherscan
Transfer(address(0),owner,ownerBalance); // for etherscan
Transfer(address(0),animator,animatorBalance); // for etherscan
LogInvestment(msg.sender,_partner,investing);
}
/**
* @dev Delete all tokens owned by sender and return unpaid dividends and 90% of initial investment
*/
function disinvest() external {
require(investStart == 0);
commitDividend(msg.sender);
uint initialInvestment = balances[msg.sender] * 10**15;
Transfer(msg.sender,address(0),balances[msg.sender]); // for etherscan
delete balances[msg.sender]; // totalSupply stays the same, investBalance is reduced
investBalance -= initialInvestment;
wallets[msg.sender].balance += uint208(initialInvestment * 9 / 10);
payWallet();
}
/**
* @dev Pay unpaid dividends
*/
function payDividends() external {
require(investStart == 0);
commitDividend(msg.sender);
payWallet();
}
/**
* @dev Commit remaining dividends before transfer of tokens
*/
function commitDividend(address _who) internal {
uint last = wallets[_who].lastDividendPeriod;
if((balances[_who]==0) || (last==0)){
wallets[_who].lastDividendPeriod=uint16(dividendPeriod);
return;
}
if(last==dividendPeriod) {
return;
}
uint share = balances[_who] * 0xffffffff / totalSupply;
uint balance = 0;
for(;last<dividendPeriod;last++) {
balance += share * dividends[last];
}
balance = (balance / 0xffffffff);
walletBalance += balance;
wallets[_who].balance += uint208(balance);
wallets[_who].lastDividendPeriod = uint16(last);
LogDividend(_who,balance,last);
}
/* lottery functions */
function betPrize(Bet _player, uint24 _hash) constant private returns (uint) { // house fee 13.85%
uint24 bethash = uint24(_player.betHash);
uint24 hit = bethash ^ _hash;
uint24 matches =
((hit & 0xF) == 0 ? 1 : 0 ) +
((hit & 0xF0) == 0 ? 1 : 0 ) +
((hit & 0xF00) == 0 ? 1 : 0 ) +
((hit & 0xF000) == 0 ? 1 : 0 ) +
((hit & 0xF0000) == 0 ? 1 : 0 ) +
((hit & 0xF00000) == 0 ? 1 : 0 );
if(matches == 6){
return(uint(_player.value) * 7000000);
}
if(matches == 5){
return(uint(_player.value) * 20000);
}
if(matches == 4){
return(uint(_player.value) * 500);
}
if(matches == 3){
return(uint(_player.value) * 25);
}
if(matches == 2){
return(uint(_player.value) * 3);
}
return(0);
}
/**
* @dev Check if won in lottery
*/
function betOf(address _who) constant external returns (uint) {
Bet memory player = bets[_who];
if( (player.value==0) ||
(player.blockNum<=1) ||
(block.number<player.blockNum) ||
(block.number>=player.blockNum + (10 * hashesSize))){
return(0);
}
if(block.number<player.blockNum+256){
// <yes> <report> BAD_RANDOMNESS
return(betPrize(player,uint24(block.blockhash(player.blockNum))));
}
if(hashFirst>0){
uint32 hash = getHash(player.blockNum);
if(hash == 0x1000000) { // load hash failed :-(, return funds
return(uint(player.value));
}
else{
return(betPrize(player,uint24(hash)));
}
}
return(0);
}
/**
* @dev Check if won in lottery
*/
function won() public {
Bet memory player = bets[msg.sender];
if(player.blockNum==0){ // create a new player
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
return;
}
if((player.value==0) || (player.blockNum==1)){
payWallet();
return;
}
require(block.number>player.blockNum); // if there is an active bet, throw()
if(player.blockNum + (10 * hashesSize) <= block.number){ // last bet too long ago, lost !
LogLate(msg.sender,player.blockNum,block.number);
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
return;
}
uint prize = 0;
uint32 hash = 0;
if(block.number<player.blockNum+256){
// <yes> <report> BAD_RANDOMNESS
hash = uint24(block.blockhash(player.blockNum));
prize = betPrize(player,uint24(hash));
}
else {
if(hashFirst>0){ // lottery is open even before swap space (hashes) is ready, but player must collect results within 256 blocks after run
hash = getHash(player.blockNum);
if(hash == 0x1000000) { // load hash failed :-(, return funds
prize = uint(player.value);
}
else{
prize = betPrize(player,uint24(hash));
}
}
else{
LogLate(msg.sender,player.blockNum,block.number);
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
return();
}
}
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
if(prize>0) {
LogWin(msg.sender,uint(player.betHash),uint(hash),prize);
if(prize > maxWin){
maxWin = prize;
LogRecordWin(msg.sender,prize);
}
pay(prize);
}
else{
LogLoss(msg.sender,uint(player.betHash),uint(hash));
}
}
/**
* @dev Send ether to buy tokens during ICO
* @dev or send less than 1 ether to contract to play
* @dev or send 0 to collect prize
*/
function () payable external {
if(msg.value > 0){
if(investStart>1){ // during ICO payment to the contract is treated as investment
invest(owner);
}
else{ // if not ICO running payment to contract is treated as play
play();
}
return;
}
//check for dividends and other assets
if(investStart == 0 && balances[msg.sender]>0){
commitDividend(msg.sender);}
won(); // will run payWallet() if nothing else available
}
/**
* @dev Play in lottery
*/
function play() payable public returns (uint) {
return playSystem(uint(sha3(msg.sender,block.number)), address(0));
}
/**
* @dev Play in lottery with random numbers
* @param _partner Affiliate partner
*/
function playRandom(address _partner) payable public returns (uint) {
return playSystem(uint(sha3(msg.sender,block.number)), _partner);
}
/**
* @dev Play in lottery with own numbers
* @param _partner Affiliate partner
*/
function playSystem(uint _hash, address _partner) payable public returns (uint) {
won(); // check if player did not win
uint24 bethash = uint24(_hash);
require(msg.value <= 1 ether && msg.value < hashBetMax);
if(msg.value > 0){
if(investStart==0) { // dividends only after investment finished
dividends[dividendPeriod] += msg.value / 20; // 5% dividend
}
if(_partner != address(0)) {
uint fee = msg.value / 100;
walletBalance += fee;
wallets[_partner].balance += uint208(fee); // 1% for affiliates
}
if(hashNext < block.number + 3) {
hashNext = block.number + 3;
hashBetSum = msg.value;
}
else{
if(hashBetSum > hashBetMax) {
hashNext++;
hashBetSum = msg.value;
}
else{
hashBetSum += msg.value;
}
}
bets[msg.sender] = Bet({value: uint192(msg.value), betHash: uint32(bethash), blockNum: uint32(hashNext)});
LogBet(msg.sender,uint(bethash),hashNext,msg.value);
}
putHash(); // players help collecing data
return(hashNext);
}
/* database functions */
/**
* @dev Create hash data swap space
* @param _sadd Number of hashes to add (<=256)
*/
function addHashes(uint _sadd) public returns (uint) {
require(hashFirst == 0 && _sadd > 0 && _sadd <= hashesSize);
uint n = hashes.length;
if(n + _sadd > hashesSize){
hashes.length = hashesSize;
}
else{
hashes.length += _sadd;
}
for(;n<hashes.length;n++){ // make sure to burn gas
hashes[n] = 1;
}
if(hashes.length>=hashesSize) { // assume block.number > 10
hashFirst = block.number - ( block.number % 10);
hashLast = hashFirst;
}
return(hashes.length);
}
/**
* @dev Create hash data swap space, add 128 hashes
*/
function addHashes128() external returns (uint) {
return(addHashes(128));
}
function calcHashes(uint32 _lastb, uint32 _delta) constant private returns (uint) {
// <yes> <report> BAD_RANDOMNESS
return( ( uint(block.blockhash(_lastb )) & 0xFFFFFF )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+1)) & 0xFFFFFF ) << 24 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+2)) & 0xFFFFFF ) << 48 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+3)) & 0xFFFFFF ) << 72 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+4)) & 0xFFFFFF ) << 96 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+5)) & 0xFFFFFF ) << 120 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+6)) & 0xFFFFFF ) << 144 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+7)) & 0xFFFFFF ) << 168 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+8)) & 0xFFFFFF ) << 192 )
// <yes> <report> BAD_RANDOMNESS
| ( ( uint(block.blockhash(_lastb+9)) & 0xFFFFFF ) << 216 )
| ( ( uint(_delta) / hashesSize) << 240));
}
function getHash(uint _block) constant private returns (uint32) {
uint delta = (_block - hashFirst) / 10;
uint hash = hashes[delta % hashesSize];
if(delta / hashesSize != hash >> 240) {
return(0x1000000); // load failed, incorrect data in hashes
}
uint slotp = (_block - hashFirst) % 10;
return(uint32((hash >> (24 * slotp)) & 0xFFFFFF));
}
/**
* @dev Fill hash data
*/
function putHash() public returns (bool) {
uint lastb = hashLast;
if(lastb == 0 || block.number <= lastb + 10) {
return(false);
}
uint blockn256;
if(block.number<256) { // useless test for testnet :-(
blockn256 = 0;
}
else{
blockn256 = block.number - 256;
}
if(lastb < blockn256) {
uint num = blockn256;
num += num % 10;
lastb = num;
}
uint delta = (lastb - hashFirst) / 10;
hashes[delta % hashesSize] = calcHashes(uint32(lastb),uint32(delta));
hashLast = lastb + 10;
return(true);
}
/**
* @dev Fill hash data many times
* @param _num Number of iterations
*/
function putHashes(uint _num) external {
uint n=0;
for(;n<_num;n++){
if(!putHash()){
return;
}
}
}
}

View File

@@ -1,129 +0,0 @@
/*
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/transaction_order_dependence/ERC20.sol
* @author: -
* @vulnerable_at_lines: 110,113
*/
pragma solidity ^0.4.24;
/** Taken from the OpenZeppelin github
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 {
event Transfer( address indexed from, address indexed to, uint256 value );
event Approval( address indexed owner, address indexed spender, uint256 value);
using SafeMath for *;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
constructor(uint totalSupply){
_balances[msg.sender] = totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256)
{
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
// <yes> <report> FRONT_RUNNING
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
// <yes> <report> FRONT_RUNNING
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
}

View File

@@ -1,20 +0,0 @@
/*
* @source: https://github.com/sigp/solidity-security-blog
* @author: -
* @vulnerable_at_lines: 17
*/
pragma solidity ^0.4.22;
contract FindThisHash {
bytes32 constant public hash = 0xb5b5b97fafd9855eec9b41f74dfb6c38f5951141f9a3ecd7f44d5479b630ee0a;
constructor() public payable {} // load with ether
function solve(string solution) public {
// If you can find the pre image of the hash, receive 1000 ether
// <yes> <report> FRONT_RUNNING
require(hash == sha3(solution));
msg.sender.transfer(1000 ether);
}
}

View File

@@ -1,14 +0,0 @@
# Front Running
Also known as time-of-check vs time-of-use (TOCTOU), race condition, transaction ordering dependence (TOD).
Since miners always get rewarded via gas fees for running code on behalf of externally owned addresses (EOA), users can specify higher fees to have their transactions mined more quickly. Since the Ethereum blockchain is public, everyone can see the contents of others' pending transactions. This means if a given user is revealing the solution to a puzzle or other valuable secret, a malicious user can steal the solution and copy their transaction with higher fees to preempt the original solution. If developers of smart contracts are not careful, this situation can lead to practical and devastating front-running attacks.
## Attack Scenario
A smart contract publishes an RSA number (N = prime1 x prime2).
A call to its submitSolution() public function with the right prime1 and prime2 rewards the caller.
Alice successfuly factors the RSA number and submits a solution.
Someone on the network sees Alice's transaction (containing the solution) waiting to be mined and submits it with a higher gas price.
The second transaction gets picked up first by miners due to the higher paid fee. The attacker wins the prize.
## References
Taken from [DASP TOP10](https://dasp.co/)

View File

@@ -1,34 +0,0 @@
/*
* @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite
* @author: Suhabe Bugrara
* @vulnerable_at_lines: 23,31
*/
pragma solidity ^0.4.16;
contract EthTxOrderDependenceMinimal {
address public owner;
bool public claimed;
uint public reward;
function EthTxOrderDependenceMinimal() public {
owner = msg.sender;
}
function setReward() public payable {
require (!claimed);
require(msg.sender == owner);
// <yes> <report> FRONT_RUNNING
owner.transfer(reward);
reward = msg.value;
}
function claimReward(uint256 submission) {
require (!claimed);
require(submission < 10);
// <yes> <report> FRONT_RUNNING
msg.sender.transfer(reward);
claimed = true;
}
}

View File

@@ -1,53 +0,0 @@
/*
* @source: http://blockchain.unica.it/projects/ethereum-survey/attacks.html#oddsandevens
* @author: -
* @vulnerable_at_lines: 25,28
*/
pragma solidity ^0.4.2;
contract OddsAndEvens{
struct Player {
address addr;
uint number;
}
Player[2] public players; //public only for debug purpose
uint8 tot;
address owner;
function OddsAndEvens() {
owner = msg.sender;
}
// <yes> <report> FRONT_RUNNING
function play(uint number) payable{
if (msg.value != 1 ether) throw;
// <yes> <report> FRONT_RUNNING
players[tot] = Player(msg.sender, number);
tot++;
if (tot==2) andTheWinnerIs();
}
function andTheWinnerIs() private {
bool res ;
uint n = players[0].number+players[1].number;
if (n%2==0) {
res = players[0].addr.send(1800 finney);
}
else {
res = players[1].addr.send(1800 finney);
}
delete players;
tot=0;
}
function getProfit() {
if(msg.sender!=owner) throw;
bool res = msg.sender.send(this.balance);
}
}

View File

@@ -1,15 +0,0 @@
# Short Addresses
Also known as or related to off-chain issues, client vulnerabilities.
Short address attacks are a side-effect of the EVM itself accepting incorrectly padded arguments. Attackers can exploit this by using specially-crafted addresses to make poorly coded clients encode arguments incorrectly before including them in transactions. Is this an EVM issue or a client issue? Should it be fixed in smart contracts instead? While everyone has a different opinion, the fact is that a great deal of ether could be directly impacted by this issue. While this vulnerability has yet to be exploited in the wild, it is a good demonstration of problems arising from the interaction between clients and the Ethereum blockchain. Other off-chain issues exist: an important one is the Ethereum ecosystem's deep trust in specific Javascript front ends, browser plugins and public nodes. An infamous off-chain exploit was used in the hack of the Coindash ICO that modified the company's Ethereum address on their webpage to trick participants into sending ethers to the attacker's address.
## Attack Scenario
An exchange API has a trading function that takes a recipient address and an amount.
The API then interacts with the smart contract transfer(address _to, uint256 _amount) function with padded arguments: it prepends the address (of an expected 20-byte length) with 12 zero bytes to make it 32-byte long
Bob (0x3bdde1e9fbaef2579dd63e2abbf0be445ab93f00) asks Alice to transfer him 20 tokens. He maliciously gives her his address truncated to remove the trailing zeroes.
Alice uses the exchange API with the shorter 19-byte address of Bob (0x3bdde1e9fbaef2579dd63e2abbf0be445ab93f).
The API pads the address with 12 zero bytes, making it 31 bytes instead of the 32 bytes. Effectively stealing one byte from the following _amount argument.
Eventually, the EVM executing the smart contract's code will remark that the data is not properly padded and will add the missing byte at the end of the _amount argument. Effectively transfering 256 times more tokens than thought.
## References
Taken from [DASP TOP10](https://dasp.co/)

View File

@@ -1,29 +0,0 @@
/*
* @source: https://ericrafaloff.com/analyzing-the-erc20-short-address-attack/
* @author: -
* @vulnerable_at_lines: 18
*/
pragma solidity ^0.4.11;
contract MyToken {
mapping (address => uint) balances;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function MyToken() {
balances[tx.origin] = 10000;
}
// <yes> <report> SHORT_ADDRESSES
function sendCoin(address to, uint amount) returns(bool sufficient) {
if (balances[msg.sender] < amount) return false;
balances[msg.sender] -= amount;
balances[to] += amount;
Transfer(msg.sender, to, amount);
return true;
}
function getBalance(address addr) constant returns(uint) {
return balances[addr];
}
}

View File

@@ -1,22 +0,0 @@
# Time Manipulation
Also known as timestamp dependence.
From locking a token sale to unlocking funds at a specific time for a game, contracts sometimes need to rely on the current time. This is usually done via block.timestamp or its alias now in Solidity. But where does that value come from? From the miners! Because a transaction's miner has leeway in reporting the time at which the mining occurred, good smart contracts will avoid relying strongly on the time advertised. Note that block.timestamp is also sometimes (mis)used in the generation of random numbers as is discussed in #6. Bad Randomness.
## Attack Scenario
A game pays out the very first player at midnight today.
A malicious miner includes his or her attempt to win the game and sets the timestamp to midnight.
A bit before midnight the miner ends up mining the block. The real current time is "close enough" to midnight (the currently set timestamp for the block), other nodes on the network decide to accept the block.
## Examples
The following function only accepts calls that come after a specific date. Since miners can influence their block's timestamp (to a certain extent), they can attempt to mine a block containing their transaction with a block timestamp set in the future. If it is close enough, it will be accepted on the network and the transaction will give the miner ether before any other player could have attempted to win the game:
```
function play() public {
require(now > 1521763200 && neverPlayed == true);
neverPlayed = false;
msg.sender.transfer(1500 ether);
}
```
## References
Taken from [DASP TOP10](https://dasp.co/)

View File

@@ -1,59 +0,0 @@
/*
* @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
* @source: https://etherscan.io/address/0xa11e4ed59dc94e69612f3111942626ed513cb172#code
* @vulnerable_at_lines: 43
* @author: -
*/
pragma solidity ^0.4.15;
/// @title Ethereum Lottery Game.
contract EtherLotto {
// Amount of ether needed for participating in the lottery.
uint constant TICKET_AMOUNT = 10;
// Fixed amount fee for each lottery game.
uint constant FEE_AMOUNT = 1;
// Address where fee is sent.
address public bank;
// Public jackpot that each participant can win (minus fee).
uint public pot;
// Lottery constructor sets bank account from the smart-contract owner.
function EtherLotto() {
bank = msg.sender;
}
// Public function for playing lottery. Each time this function
// is invoked, the sender has an oportunity for winning pot.
function play() payable {
// Participants must spend some fixed ether before playing lottery.
assert(msg.value == TICKET_AMOUNT);
// Increase pot for each participant.
pot += msg.value;
// Compute some *almost random* value for selecting winner from current transaction.
// <yes> <report> TIME_MANIPULATION
var random = uint(sha3(block.timestamp)) % 2;
// Distribution: 50% of participants will be winners.
if (random == 0) {
// Send fee to bank account.
bank.transfer(FEE_AMOUNT);
// Send jackpot to winner.
msg.sender.transfer(pot - FEE_AMOUNT);
// Restart jackpot.
pot = 0;
}
}
}

View File

@@ -1,53 +0,0 @@
/*
* @source: http://blockchain.unica.it/projects/ethereum-survey/attacks.html#governmental
* @author: -
* @vulnerable_at_lines: 27
*/
//added pragma version
pragma solidity ^0.4.0;
contract Governmental {
address public owner;
address public lastInvestor;
uint public jackpot = 1 ether;
uint public lastInvestmentTimestamp;
uint public ONE_MINUTE = 1 minutes;
function Governmental() {
owner = msg.sender;
if (msg.value<1 ether) throw;
}
function invest() {
if (msg.value<jackpot/2) throw;
lastInvestor = msg.sender;
jackpot += msg.value/2;
// <yes> <report> TIME_MANIPULATION
lastInvestmentTimestamp = block.timestamp;
}
function resetInvestment() {
if (block.timestamp < lastInvestmentTimestamp+ONE_MINUTE)
throw;
lastInvestor.send(jackpot);
owner.send(this.balance-1 ether);
lastInvestor = 0;
jackpot = 1 ether;
lastInvestmentTimestamp = 0;
}
}
contract Attacker {
function attack(address target, uint count) {
if (0<=count && count<1023) {
this.attack.gas(msg.gas-2000)(target, count+1);
}
else {
Governmental(target).resetInvestment();
}
}
}

View File

@@ -1,33 +0,0 @@
/*
* @source: https://github.com/seresistvanandras/EthBench/blob/master/Benchmark/Simple/timestampdependent.sol
* @author: -
* @vulnerable_at_lines: 13,27
*/
pragma solidity ^0.4.0;
contract lottopollo {
address leader;
uint timestamp;
function payOut(uint rand) internal {
// <yes> <report> TIME MANIPULATION
if ( rand> 0 && now - rand > 24 hours ) {
msg.sender.send( msg.value );
if ( this.balance > 0 ) {
leader.send( this.balance );
}
}
else if ( msg.value >= 1 ether ) {
leader = msg.sender;
timestamp = rand;
}
}
function randomGen() constant returns (uint randomNumber) {
// <yes> <report> TIME MANIPULATION
return block.timestamp;
}
function draw(uint seed){
uint randomNumber=randomGen();
payOut(randomNumber);
}
}

View File

@@ -1,25 +0,0 @@
/*
* @source: https://github.com/sigp/solidity-security-blog
* @author: -
* @vulnerable_at_lines: 18,20
*/
pragma solidity ^0.4.25;
contract Roulette {
uint public pastBlockTime; // Forces one bet per block
constructor() public payable {} // initially fund contract
// fallback function used to make a bet
function () public payable {
require(msg.value == 10 ether); // must send 10 ether to play
// <yes> <report> TIME_MANIPULATION
require(now != pastBlockTime); // only 1 transaction per block
// <yes> <report> TIME_MANIPULATION
pastBlockTime = now;
if(now % 15 == 0) { // winner
msg.sender.transfer(this.balance);
}
}
}

View File

@@ -1,15 +0,0 @@
/*
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/timestamp_dependence/timed_crowdsale.sol
* @author: -
* @vulnerable_at_lines: 13
*/
pragma solidity ^0.4.25;
contract TimedCrowdsale {
// Sale should finish exactly at January 1, 2019
function isSaleFinished() view public returns (bool) {
// <yes> <report> TIME_MANIPULATION
return block.timestamp >= 1546300800;
}
}

View File

@@ -1,92 +0,0 @@
#!/usr/bin/env node
(async () => {
const fs = require('fs')
const getSolidityFiles = (dir, filelist) => {
files = fs.readdirSync(dir)
filelist = filelist || []
files.forEach(function(file) {
file_type = file.split(".").pop()
if (fs.statSync(dir + '/' + file).isDirectory()) {
filelist = getSolidityFiles(dir + '/' + file, filelist)
}
else if (file_type == "sol") {
const contract_dir = dir + '/' + file
const vuln_cat = dir.split("/").pop()
const params = {
name: file,
path: contract_dir,
cat: vuln_cat
}
filelist.push(params)
}
})
return filelist
}
const getResults = () => {
const results = []
const contracts = getSolidityFiles('dataset')
contracts.forEach(contract => {
let vulnerabilities = []
let result = {
name: contract.name,
path: contract.path,
source: '',
vulnerabilities: vulnerabilities
}
const contract_lines = fs.readFileSync(contract.path).toString().split("\n")
contract_lines.forEach(line => {
let contract_source, vuln_at_lines
//get source
if (line.includes('@source:')) {
contract_source = line.split("@source:").pop()
result.source = contract_source.trim()
return
}
//get vuln lines
if (line.includes('@vulnerable_at_lines')) {
vuln_at_lines = line.split("@vulnerable_at_lines: ").pop()
const lines = vuln_at_lines.split(",")
for (let index = 0; index < lines.length; index++){
let vuln
let vuln_flow = []
if((parseInt(lines[index]) + 1) === parseInt(lines[index + 1])){
while((parseInt(lines[index]) + 1) === parseInt(lines[index + 1])){
vuln_flow.push(parseInt(lines[index]))
index+=1
}
vuln_flow.push(parseInt(lines[index]))
vuln = {
lines: vuln_flow,
category: contract.cat
}
}
else{
vuln_flow.push(parseInt(lines[index]))
vuln = {
lines: vuln_flow,
category: contract.cat
}
}
vulnerabilities.push(vuln)
}
return
}
})
results.push(result)
})
return results
}
const result = getResults()
fs.writeFileSync('vulnerabilities.json', JSON.stringify(result))
process.exit()
})()

File diff suppressed because it is too large Load Diff