Vulnerability Type
stringclasses 10
values | File Name
stringlengths 9
47
| Source Code
stringlengths 228
96.8k
| input
stringlengths 116
49.7k
|
---|---|---|---|
bad_randomness | random_number_generator.sol | /*
* @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;
}
} | pragma solidity ^0.4.25;
contract RandomNumberGenerator {
uint256 private salt = block.timestamp;
function random(uint max) view private returns (uint256 result) {
uint256 x = salt * 100 / max;
uint256 y = salt * block.number / (salt % 5);
uint256 seed = block.number / 3 + (salt % 300) + y;
uint256 h = uint256(blockhash(seed));
return uint256((h / x)) % max + 1;
}
} |
bad_randomness | lottery.sol | /*
* @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);
}
} | 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;
function Lottery() {
organizer = msg.sender;
}
function() {
throw;
}
function makeBet() {
bool won = (block.number % 2) == 0;
bets.push(Bet(msg.value, block.number, won));
if(won) {
if(!msg.sender.send(msg.value)) {
throw;
}
}
}
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);
}
}
function destroy() {
if(msg.sender != organizer) { throw; }
suicide(organizer);
}
} |
bad_randomness | old_blockhash.sol | /*
* @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);
}
}
} | pragma solidity ^0.4.24;
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);
bytes32 answer = blockhash(guesses[msg.sender].block);
guesses[msg.sender].block = 0;
if (guesses[msg.sender].guess == answer) {
msg.sender.transfer(2 ether);
}
}
} |
bad_randomness | etheraffle.sol | /*
* @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);
}
}
} | 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
);
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;
address feeAddress;
bool public paused = false;
uint public raffleId = 1;
uint public blockNumber = block.number;
uint nextTicket = 0;
mapping (uint => Contestant) contestants;
uint[] gaps;
function Ethraffle_v4b() public {
feeAddress = msg.sender;
}
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;
}
if (nextTicket == totalTickets) {
chooseWinner();
}
if (moneySent > 0) {
msg.sender.transfer(moneySent);
}
}
function chooseWinner() private {
address seed1 = contestants[uint(block.coinbase) % totalTickets].addr;
address seed2 = contestants[uint(msg.sender) % totalTickets].addr;
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);
raffleId++;
nextTicket = 0;
blockNumber = block.number;
winningAddress.transfer(prize);
feeAddress.transfer(fee);
}
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);
}
}
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;
blockNumber = block.number;
gaps.length = 0;
}
}
function togglePause() public {
if (msg.sender == feeAddress) {
paused = !paused;
}
}
function kill() public {
if (msg.sender == feeAddress) {
selfdestruct(feeAddress);
}
}
} |
bad_randomness | blackjack.sol | /*
* @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.9;
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
}
} | pragma solidity ^0.4.9;
library Deck {
function deal(address player, uint8 cardNumber) internal returns (uint8) {
uint b = block.number;
uint timestamp = block.timestamp;
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) {
return 10;
}
if (value == 1 && isBigAce) {
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;
uint public maxBet = 5 ether;
uint8 BLACKJACK = 21;
enum GameState { Ongoing, Player, Tie, House }
struct Game {
address player;
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;
}
_;
}
event Deal(
bool isUser,
uint8 _card
);
event GameStatus(
uint8 houseScore,
uint8 houseScoreBig,
uint8 playerScore,
uint8 playerScoreBig
);
event Log(
uint8 value
);
function BlackJack() {
}
function () payable {
}
function deal() public payable {
if (games[msg.sender].player != 0 && games[msg.sender].state == GameState.Ongoing) {
throw;
}
if (msg.value < minBet || msg.value > maxBet) {
throw;
}
uint8[] memory houseCards = new uint8[](1);
uint8[] memory playerCards = new uint8[](2);
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);
}
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);
}
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);
}
function checkGameResult(Game game, bool finishGame) private {
var (houseScore, houseScoreBig) = calculateScore(game.houseCards);
var (playerScore, playerScoreBig) = calculateScore(game.playerCards);
GameStatus(houseScore, houseScoreBig, playerScore, playerScoreBig);
if (houseScoreBig == BLACKJACK || houseScore == BLACKJACK) {
if (playerScore == BLACKJACK || playerScoreBig == BLACKJACK) {
if (!msg.sender.send(game.bet)) throw;
games[msg.sender].state = GameState.Tie;
return;
} else {
games[msg.sender].state = GameState.House;
return;
}
} else {
if (playerScore == BLACKJACK || playerScoreBig == BLACKJACK) {
if (game.playerCards.length == 2 && (Deck.isTen(game.playerCards[0]) || Deck.isTen(game.playerCards[1]))) {
if (!msg.sender.send((game.bet * 5) / 2)) throw;
} else {
if (!msg.sender.send(game.bet * 2)) throw;
}
games[msg.sender].state = GameState.Player;
return;
} else {
if (playerScore > BLACKJACK) {
Log(1);
games[msg.sender].state = GameState.House;
return;
}
if (!finishGame) {
return;
}
uint8 playerShortage = 0;
uint8 houseShortage = 0;
if (playerScoreBig > BLACKJACK) {
if (playerScore > BLACKJACK) {
games[msg.sender].state = GameState.House;
return;
} else {
playerShortage = BLACKJACK - playerScore;
}
} else {
playerShortage = BLACKJACK - playerScoreBig;
}
if (houseScoreBig > BLACKJACK) {
if (houseScore > BLACKJACK) {
if (!msg.sender.send(game.bet * 2)) throw;
games[msg.sender].state = GameState.Player;
return;
} else {
houseShortage = BLACKJACK - houseScore;
}
} else {
houseShortage = BLACKJACK - houseScoreBig;
}
if (houseShortage == playerShortage) {
if (!msg.sender.send(game.bet)) throw;
games[msg.sender].state = GameState.Tie;
} else if (houseShortage > playerShortage) {
if (!msg.sender.send(game.bet * 2)) throw;
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;
bool bigAceUsed = false;
for (uint i = 0; i < cards.length; ++i) {
uint8 card = cards[i];
if (Deck.isAce(card) && !bigAceUsed) {
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 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;
}
} |
bad_randomness | lucky_doubler.sol | /*
* @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.';
}
}
} | pragma solidity ^0.4.0;
contract LuckyDoubler {
address private owner;
uint private balance = 0;
uint private fee = 5;
uint private multiplier = 125;
mapping (address => User) private users;
Entry[] private entries;
uint[] private unpaidEntries;
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;
}
function() {
init();
}
function init() private{
if (msg.value < 1 ether) {
msg.sender.send(msg.value);
return;
}
join();
}
function join() private {
uint dValue = 1 ether;
if (msg.value > 1 ether) {
msg.sender.send(msg.value - 1 ether);
dValue = 1 ether;
}
if (users[msg.sender].id == address(0))
{
users[msg.sender].id = msg.sender;
users[msg.sender].deposits = 0;
users[msg.sender].payoutsReceived = 0;
}
entries.push(Entry(msg.sender, dValue, (dValue * (multiplier) / 100), false));
users[msg.sender].deposits++;
unpaidEntries.push(entries.length -1);
balance += (dValue * (100 - fee)) / 100;
uint index = unpaidEntries.length > 1 ? rand(unpaidEntries.length) : 0;
Entry theEntry = entries[unpaidEntries[index]];
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--;
}
uint fees = this.balance - balance;
if (fees > 0)
{
owner.send(fees);
}
}
uint256 constant private FACTOR = 1157920892373161954235709850086879078532699846656405640394575840079131296399;
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;
}
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;
}
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.';
}
}
} |
bad_randomness | smart_billions.sol | /*
* @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;
}
}
}
} | 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;
address public 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;
}
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);
_;
}
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);
}
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
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);
}
function approve(address _spender, uint _value) {
assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract SmartBillions is StandardToken {
string public constant name = "SmartBillions Token";
string public constant symbol = "PLAY";
uint public constant decimals = 0;
struct Wallet {
uint208 balance;
uint16 lastDividendPeriod;
uint32 nextWithdrawBlock;
}
mapping (address => Wallet) wallets;
struct Bet {
uint192 value;
uint32 betHash;
uint32 blockNum;
}
mapping (address => Bet) bets;
uint public walletBalance = 0;
uint public investStart = 1;
uint public investBalance = 0;
uint public investBalanceMax = 200000 ether;
uint public dividendPeriod = 1;
uint[] public dividends;
uint public maxWin = 0;
uint public hashFirst = 0;
uint public hashLast = 0;
uint public hashNext = 0;
uint public hashBetSum = 0;
uint public hashBetMax = 5 ether;
uint[] public hashes;
uint public constant hashesSize = 16384 ;
uint public coldStoreLast = 0 ;
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);
_;
}
function SmartBillions() {
owner = msg.sender;
animator = msg.sender;
wallets[owner].lastDividendPeriod = uint16(dividendPeriod);
dividends.push(0);
dividends.push(0);
}
function hashesLength() constant external returns (uint) {
return uint(hashes.length);
}
function walletBalanceOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].balance);
}
function walletPeriodOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].lastDividendPeriod);
}
function walletBlockOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].nextWithdrawBlock);
}
function betValueOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].value);
}
function betHashOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].betHash);
}
function betBlockNumberOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].blockNum);
}
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)));
}
function changeOwner(address _who) external onlyOwner {
assert(_who != address(0));
commitDividend(msg.sender);
commitDividend(_who);
owner = _who;
}
function changeAnimator(address _who) external onlyAnimator {
assert(_who != address(0));
commitDividend(msg.sender);
commitDividend(_who);
animator = _who;
}
function setInvestStart(uint _when) external onlyOwner {
require(investStart == 1 && hashFirst > 0 && block.number < _when);
investStart = _when;
}
function setBetMax(uint _maxsum) external onlyOwner {
hashBetMax = _maxsum;
}
function resetBet() external onlyOwner {
hashNext = block.number + 3;
hashBetSum = 0;
}
function coldStore(uint _amount) external onlyOwner {
houseKeeping();
require(_amount > 0 && this.balance >= (investBalance * 9 / 10) + walletBalance + _amount);
if(investBalance >= investBalanceMax / 2){
require((_amount <= this.balance / 400) && coldStoreLast + 4 * 60 * 24 * 7 <= block.number);
}
msg.sender.transfer(_amount);
coldStoreLast = block.number;
}
function hotStore() payable external {
houseKeeping();
}
function houseKeeping() public {
if(investStart > 1 && block.number >= investStart + (hashesSize * 5)){
investStart = 0;
}
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++;
}
}
}
}
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);
msg.sender.transfer(maxpay);
}
}
function investDirect() payable external {
invest(owner);
}
function invest(address _partner) payable public {
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;
msg.sender.transfer(msg.value.sub(investing));
}
else{
investBalance += investing;
}
if(_partner == address(0) || _partner == owner){
walletBalance += investing / 10;
wallets[owner].balance += uint208(investing / 10);}
else{
walletBalance += (investing * 5 / 100) * 2;
wallets[owner].balance += uint208(investing * 5 / 100);
wallets[_partner].balance += uint208(investing * 5 / 100);}
wallets[msg.sender].lastDividendPeriod = uint16(dividendPeriod);
uint senderBalance = investing / 10**15;
uint ownerBalance = investing * 16 / 10**17 ;
uint animatorBalance = investing * 10 / 10**17 ;
balances[msg.sender] += senderBalance;
balances[owner] += ownerBalance ;
balances[animator] += animatorBalance ;
totalSupply += senderBalance + ownerBalance + animatorBalance;
Transfer(address(0),msg.sender,senderBalance);
Transfer(address(0),owner,ownerBalance);
Transfer(address(0),animator,animatorBalance);
LogInvestment(msg.sender,_partner,investing);
}
function disinvest() external {
require(investStart == 0);
commitDividend(msg.sender);
uint initialInvestment = balances[msg.sender] * 10**15;
Transfer(msg.sender,address(0),balances[msg.sender]);
delete balances[msg.sender];
investBalance -= initialInvestment;
wallets[msg.sender].balance += uint208(initialInvestment * 9 / 10);
payWallet();
}
function payDividends() external {
require(investStart == 0);
commitDividend(msg.sender);
payWallet();
}
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);
}
function betPrize(Bet _player, uint24 _hash) constant private returns (uint) {
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);
}
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){
return(betPrize(player,uint24(block.blockhash(player.blockNum))));
}
if(hashFirst>0){
uint32 hash = getHash(player.blockNum);
if(hash == 0x1000000) {
return(uint(player.value));
}
else{
return(betPrize(player,uint24(hash)));
}
}
return(0);
}
function won() public {
Bet memory player = bets[msg.sender];
if(player.blockNum==0){
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(player.blockNum + (10 * hashesSize) <= block.number){
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){
hash = uint24(block.blockhash(player.blockNum));
prize = betPrize(player,uint24(hash));
}
else {
if(hashFirst>0){
hash = getHash(player.blockNum);
if(hash == 0x1000000) {
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));
}
}
function () payable external {
if(msg.value > 0){
if(investStart>1){
invest(owner);
}
else{
play();
}
return;
}
if(investStart == 0 && balances[msg.sender]>0){
commitDividend(msg.sender);}
won();
}
function play() payable public returns (uint) {
return playSystem(uint(sha3(msg.sender,block.number)), address(0));
}
function playRandom(address _partner) payable public returns (uint) {
return playSystem(uint(sha3(msg.sender,block.number)), _partner);
}
function playSystem(uint _hash, address _partner) payable public returns (uint) {
won();
uint24 bethash = uint24(_hash);
require(msg.value <= 1 ether && msg.value < hashBetMax);
if(msg.value > 0){
if(investStart==0) {
dividends[dividendPeriod] += msg.value / 20;
}
if(_partner != address(0)) {
uint fee = msg.value / 100;
walletBalance += fee;
wallets[_partner].balance += uint208(fee);
}
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();
return(hashNext);
}
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++){
hashes[n] = 1;
}
if(hashes.length>=hashesSize) {
hashFirst = block.number - ( block.number % 10);
hashLast = hashFirst;
}
return(hashes.length);
}
function addHashes128() external returns (uint) {
return(addHashes(128));
}
function calcHashes(uint32 _lastb, uint32 _delta) constant private returns (uint) {
return( ( uint(block.blockhash(_lastb )) & 0xFFFFFF )
| ( ( uint(block.blockhash(_lastb+1)) & 0xFFFFFF ) << 24 )
| ( ( uint(block.blockhash(_lastb+2)) & 0xFFFFFF ) << 48 )
| ( ( uint(block.blockhash(_lastb+3)) & 0xFFFFFF ) << 72 )
| ( ( uint(block.blockhash(_lastb+4)) & 0xFFFFFF ) << 96 )
| ( ( uint(block.blockhash(_lastb+5)) & 0xFFFFFF ) << 120 )
| ( ( uint(block.blockhash(_lastb+6)) & 0xFFFFFF ) << 144 )
| ( ( uint(block.blockhash(_lastb+7)) & 0xFFFFFF ) << 168 )
| ( ( uint(block.blockhash(_lastb+8)) & 0xFFFFFF ) << 192 )
| ( ( 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);
}
uint slotp = (_block - hashFirst) % 10;
return(uint32((hash >> (24 * slotp)) & 0xFFFFFF));
}
function putHash() public returns (bool) {
uint lastb = hashLast;
if(lastb == 0 || block.number <= lastb + 10) {
return(false);
}
uint blockn256;
if(block.number<256) {
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);
}
function putHashes(uint _num) external {
uint n=0;
for(;n<_num;n++){
if(!putHash()){
return;
}
}
}
} |
bad_randomness | guess_the_random_number.sol | /*
* @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);
}
}
} | pragma solidity ^0.4.21;
contract GuessTheRandomNumberChallenge {
uint8 answer;
function GuessTheRandomNumberChallenge() public payable {
require(msg.value == 1 ether);
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);
}
}
} |
reentrancy | reentrancy_bonus.sol | /*
* @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/
* @author: consensys
* @vulnerable_at_lines: 28
*/
pragma solidity ^0.4.24;
contract Reentrancy_bonus{
// INSECURE
mapping (address => uint) private userBalances;
mapping (address => bool) private claimedBonus;
mapping (address => uint) private rewardsForA;
function withdrawReward(address recipient) public {
uint amountToWithdraw = rewardsForA[recipient];
rewardsForA[recipient] = 0;
(bool success, ) = recipient.call.value(amountToWithdraw)("");
require(success);
}
function getFirstWithdrawalBonus(address recipient) public {
require(!claimedBonus[recipient]); // Each recipient should only be able to claim the bonus once
rewardsForA[recipient] += 100;
// <yes> <report> REENTRANCY
withdrawReward(recipient); // At this point, the caller will be able to execute getFirstWithdrawalBonus again.
claimedBonus[recipient] = true;
}
} | pragma solidity ^0.4.24;
contract Reentrancy_bonus{
mapping (address => uint) private userBalances;
mapping (address => bool) private claimedBonus;
mapping (address => uint) private rewardsForA;
function withdrawReward(address recipient) public {
uint amountToWithdraw = rewardsForA[recipient];
rewardsForA[recipient] = 0;
(bool success, ) = recipient.call.value(amountToWithdraw)("");
require(success);
}
function getFirstWithdrawalBonus(address recipient) public {
require(!claimedBonus[recipient]);
rewardsForA[recipient] += 100;
withdrawReward(recipient);
claimedBonus[recipient] = true;
}
} |
reentrancy | 0xb93430ce38ac4a6bb47fb1fc085ea669353fd89e.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 38
*/
pragma solidity ^0.4.19;
contract PrivateBank
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
Log TransferLog;
function PrivateBank(address _lib)
{
TransferLog = Log(_lib);
}
function Deposit()
public
payable
{
if(msg.value >= MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
{
if(_am<=balances[msg.sender])
{
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} | pragma solidity ^0.4.19;
contract PrivateBank
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
Log TransferLog;
function PrivateBank(address _lib)
{
TransferLog = Log(_lib);
}
function Deposit()
public
payable
{
if(msg.value >= MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
{
if(_am<=balances[msg.sender])
{
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} |
reentrancy | 0x8c7777c45481dba411450c228cb692ac3d550344.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 41
*/
pragma solidity ^0.4.19;
contract ETH_VAULT
{
mapping (address => uint) public balances;
Log TransferLog;
uint public MinDeposit = 1 ether;
function ETH_VAULT(address _log)
public
{
TransferLog = Log(_log);
}
function Deposit()
public
payable
{
if(msg.value > MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
public
payable
{
if(_am<=balances[msg.sender])
{
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} | pragma solidity ^0.4.19;
contract ETH_VAULT
{
mapping (address => uint) public balances;
Log TransferLog;
uint public MinDeposit = 1 ether;
function ETH_VAULT(address _log)
public
{
TransferLog = Log(_log);
}
function Deposit()
public
payable
{
if(msg.value > MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
public
payable
{
if(_am<=balances[msg.sender])
{
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} |
reentrancy | 0xbaf51e761510c1a11bf48dd87c0307ac8a8c8a4f.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 41
*/
pragma solidity ^0.4.19;
contract ETH_VAULT
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
Log TransferLog;
function ETH_VAULT(address _log)
public
{
TransferLog = Log(_log);
}
function Deposit()
public
payable
{
if(msg.value > MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
public
payable
{
if(_am<=balances[msg.sender])
{
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} | pragma solidity ^0.4.19;
contract ETH_VAULT
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
Log TransferLog;
function ETH_VAULT(address _log)
public
{
TransferLog = Log(_log);
}
function Deposit()
public
payable
{
if(msg.value > MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
public
payable
{
if(_am<=balances[msg.sender])
{
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} |
reentrancy | 0xcead721ef5b11f1a7b530171aab69b16c5e66b6e.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 29
*/
pragma solidity ^0.4.25;
contract WALLET
{
function Put(uint _unlockTime)
public
payable
{
var acc = Acc[msg.sender];
acc.balance += msg.value;
acc.unlockTime = _unlockTime>now?_unlockTime:now;
LogFile.AddMessage(msg.sender,msg.value,"Put");
}
function Collect(uint _am)
public
payable
{
var acc = Acc[msg.sender];
if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime)
{
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_am)())
{
acc.balance-=_am;
LogFile.AddMessage(msg.sender,_am,"Collect");
}
}
}
function()
public
payable
{
Put(0);
}
struct Holder
{
uint unlockTime;
uint balance;
}
mapping (address => Holder) public Acc;
Log LogFile;
uint public MinSum = 1 ether;
function WALLET(address log) public{
LogFile = Log(log);
}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} | pragma solidity ^0.4.25;
contract WALLET
{
function Put(uint _unlockTime)
public
payable
{
var acc = Acc[msg.sender];
acc.balance += msg.value;
acc.unlockTime = _unlockTime>now?_unlockTime:now;
LogFile.AddMessage(msg.sender,msg.value,"Put");
}
function Collect(uint _am)
public
payable
{
var acc = Acc[msg.sender];
if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime)
{
if(msg.sender.call.value(_am)())
{
acc.balance-=_am;
LogFile.AddMessage(msg.sender,_am,"Collect");
}
}
}
function()
public
payable
{
Put(0);
}
struct Holder
{
uint unlockTime;
uint balance;
}
mapping (address => Holder) public Acc;
Log LogFile;
uint public MinSum = 1 ether;
function WALLET(address log) public{
LogFile = Log(log);
}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} |
reentrancy | 0x627fa62ccbb1c1b04ffaecd72a53e37fc0e17839.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 94
*/
pragma solidity ^0.4.19;
contract Ownable
{
address newOwner;
address owner = msg.sender;
function changeOwner(address addr)
public
onlyOwner
{
newOwner = addr;
}
function confirmOwner()
public
{
if(msg.sender==newOwner)
{
owner=newOwner;
}
}
modifier onlyOwner
{
if(owner == msg.sender)_;
}
}
contract Token is Ownable
{
address owner = msg.sender;
function WithdrawToken(address token, uint256 amount,address to)
public
onlyOwner
{
token.call(bytes4(sha3("transfer(address,uint256)")),to,amount);
}
}
contract TokenBank is Token
{
uint public MinDeposit;
mapping (address => uint) public Holders;
///Constructor
function initTokenBank()
public
{
owner = msg.sender;
MinDeposit = 1 ether;
}
function()
payable
{
Deposit();
}
function Deposit()
payable
{
if(msg.value>MinDeposit)
{
Holders[msg.sender]+=msg.value;
}
}
function WitdrawTokenToHolder(address _to,address _token,uint _amount)
public
onlyOwner
{
if(Holders[_to]>0)
{
Holders[_to]=0;
WithdrawToken(_token,_amount,_to);
}
}
function WithdrawToHolder(address _addr, uint _wei)
public
onlyOwner
payable
{
if(Holders[_addr]>0)
{
// <yes> <report> REENTRANCY
if(_addr.call.value(_wei)())
{
Holders[_addr]-=_wei;
}
}
}
} | pragma solidity ^0.4.19;
contract Ownable
{
address newOwner;
address owner = msg.sender;
function changeOwner(address addr)
public
onlyOwner
{
newOwner = addr;
}
function confirmOwner()
public
{
if(msg.sender==newOwner)
{
owner=newOwner;
}
}
modifier onlyOwner
{
if(owner == msg.sender)_;
}
}
contract Token is Ownable
{
address owner = msg.sender;
function WithdrawToken(address token, uint256 amount,address to)
public
onlyOwner
{
token.call(bytes4(sha3("transfer(address,uint256)")),to,amount);
}
}
contract TokenBank is Token
{
uint public MinDeposit;
mapping (address => uint) public Holders;
function initTokenBank()
public
{
owner = msg.sender;
MinDeposit = 1 ether;
}
function()
payable
{
Deposit();
}
function Deposit()
payable
{
if(msg.value>MinDeposit)
{
Holders[msg.sender]+=msg.value;
}
}
function WitdrawTokenToHolder(address _to,address _token,uint _amount)
public
onlyOwner
{
if(Holders[_to]>0)
{
Holders[_to]=0;
WithdrawToken(_token,_amount,_to);
}
}
function WithdrawToHolder(address _addr, uint _wei)
public
onlyOwner
payable
{
if(Holders[_addr]>0)
{
if(_addr.call.value(_wei)())
{
Holders[_addr]-=_wei;
}
}
}
} |
reentrancy | reentrance.sol | /*
* @source: https://ethernaut.zeppelin.solutions/level/0xf70706db003e94cfe4b5e27ffd891d5c81b39488
* @author: Alejandro Santander
* @vulnerable_at_lines: 24
*/
pragma solidity ^0.4.18;
contract Reentrance {
mapping(address => uint) public balances;
function donate(address _to) public payable {
balances[_to] += msg.value;
}
function balanceOf(address _who) public view returns (uint balance) {
return balances[_who];
}
function withdraw(uint _amount) public {
if(balances[msg.sender] >= _amount) {
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_amount)()) {
_amount;
}
balances[msg.sender] -= _amount;
}
}
function() public payable {}
} | pragma solidity ^0.4.18;
contract Reentrance {
mapping(address => uint) public balances;
function donate(address _to) public payable {
balances[_to] += msg.value;
}
function balanceOf(address _who) public view returns (uint balance) {
return balances[_who];
}
function withdraw(uint _amount) public {
if(balances[msg.sender] >= _amount) {
if(msg.sender.call.value(_amount)()) {
_amount;
}
balances[msg.sender] -= _amount;
}
}
function() public payable {}
} |
reentrancy | reentrancy_dao.sol | /*
* @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite
* @author: Suhabe Bugrara
* @vulnerable_at_lines: 18
*/
pragma solidity ^0.4.19;
contract ReentrancyDAO {
mapping (address => uint) credit;
uint balance;
function withdrawAll() public {
uint oCredit = credit[msg.sender];
if (oCredit > 0) {
balance -= oCredit;
// <yes> <report> REENTRANCY
bool callResult = msg.sender.call.value(oCredit)();
require (callResult);
credit[msg.sender] = 0;
}
}
function deposit() public payable {
credit[msg.sender] += msg.value;
balance += msg.value;
}
} | pragma solidity ^0.4.19;
contract ReentrancyDAO {
mapping (address => uint) credit;
uint balance;
function withdrawAll() public {
uint oCredit = credit[msg.sender];
if (oCredit > 0) {
balance -= oCredit;
bool callResult = msg.sender.call.value(oCredit)();
require (callResult);
credit[msg.sender] = 0;
}
}
function deposit() public payable {
credit[msg.sender] += msg.value;
balance += msg.value;
}
} |
reentrancy | modifier_reentrancy.sol | /*
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/reentracy/modifier_reentrancy.sol
* @author: -
* @vulnerable_at_lines: 15
*/
pragma solidity ^0.4.24;
contract ModifierEntrancy {
mapping (address => uint) public tokenBalance;
string constant name = "Nu Token";
//If a contract has a zero balance and supports the token give them some token
// <yes> <report> REENTRANCY
function airDrop() hasNoBalance supportsToken public{
tokenBalance[msg.sender] += 20;
}
//Checks that the contract responds the way we want
modifier supportsToken() {
require(keccak256(abi.encodePacked("Nu Token")) == Bank(msg.sender).supportsToken());
_;
}
//Checks that the caller has a zero balance
modifier hasNoBalance {
require(tokenBalance[msg.sender] == 0);
_;
}
}
contract Bank{
function supportsToken() external pure returns(bytes32){
return(keccak256(abi.encodePacked("Nu Token")));
}
}
contract attack{ //An example of a contract that breaks the contract above.
bool hasBeenCalled;
function supportsToken() external returns(bytes32){
if(!hasBeenCalled){
hasBeenCalled = true;
ModifierEntrancy(msg.sender).airDrop();
}
return(keccak256(abi.encodePacked("Nu Token")));
}
function call(address token) public{
ModifierEntrancy(token).airDrop();
}
} | pragma solidity ^0.4.24;
contract ModifierEntrancy {
mapping (address => uint) public tokenBalance;
string constant name = "Nu Token";
function airDrop() hasNoBalance supportsToken public{
tokenBalance[msg.sender] += 20;
}
modifier supportsToken() {
require(keccak256(abi.encodePacked("Nu Token")) == Bank(msg.sender).supportsToken());
_;
}
modifier hasNoBalance {
require(tokenBalance[msg.sender] == 0);
_;
}
}
contract Bank{
function supportsToken() external pure returns(bytes32){
return(keccak256(abi.encodePacked("Nu Token")));
}
}
contract attack{
bool hasBeenCalled;
function supportsToken() external returns(bytes32){
if(!hasBeenCalled){
hasBeenCalled = true;
ModifierEntrancy(msg.sender).airDrop();
}
return(keccak256(abi.encodePacked("Nu Token")));
}
function call(address token) public{
ModifierEntrancy(token).airDrop();
}
} |
reentrancy | 0x7a8721a9d64c74da899424c1b52acbf58ddc9782.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 52
*/
pragma solidity ^0.4.19;
contract PrivateDeposit
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
address public owner;
Log TransferLog;
modifier onlyOwner() {
require(tx.origin == owner);
_;
}
function PrivateDeposit()
{
owner = msg.sender;
TransferLog = new Log();
}
function setLog(address _lib) onlyOwner
{
TransferLog = Log(_lib);
}
function Deposit()
public
payable
{
if(msg.value >= MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
{
if(_am<=balances[msg.sender])
{
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} | pragma solidity ^0.4.19;
contract PrivateDeposit
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
address public owner;
Log TransferLog;
modifier onlyOwner() {
require(tx.origin == owner);
_;
}
function PrivateDeposit()
{
owner = msg.sender;
TransferLog = new Log();
}
function setLog(address _lib) onlyOwner
{
TransferLog = Log(_lib);
}
function Deposit()
public
payable
{
if(msg.value >= MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
}
}
function CashOut(uint _am)
{
if(_am<=balances[msg.sender])
{
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} |
reentrancy | reentrancy_cross_function.sol | /*
* @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/
* @author: consensys
* @vulnerable_at_lines: 24
*/
pragma solidity ^0.4.24;
contract Reentrancy_cross_function {
// INSECURE
mapping (address => uint) private userBalances;
function transfer(address to, uint amount) {
if (userBalances[msg.sender] >= amount) {
userBalances[to] += amount;
userBalances[msg.sender] -= amount;
}
}
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
// <yes> <report> REENTRANCY
(bool success, ) = msg.sender.call.value(amountToWithdraw)(""); // At this point, the caller's code is executed, and can call transfer()
require(success);
userBalances[msg.sender] = 0;
}
} | pragma solidity ^0.4.24;
contract Reentrancy_cross_function {
mapping (address => uint) private userBalances;
function transfer(address to, uint amount) {
if (userBalances[msg.sender] >= amount) {
userBalances[to] += amount;
userBalances[msg.sender] -= amount;
}
}
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
(bool success, ) = msg.sender.call.value(amountToWithdraw)("");
require(success);
userBalances[msg.sender] = 0;
}
} |
reentrancy | reentrancy_simple.sol | /*
* @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/reentrancy/Reentrancy.sol
* @author: -
* @vulnerable_at_lines: 24
*/
pragma solidity ^0.4.15;
contract Reentrance {
mapping (address => uint) userBalance;
function getBalance(address u) constant returns(uint){
return userBalance[u];
}
function addToBalance() payable{
userBalance[msg.sender] += msg.value;
}
function withdrawBalance(){
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
// <yes> <report> REENTRANCY
if( ! (msg.sender.call.value(userBalance[msg.sender])() ) ){
throw;
}
userBalance[msg.sender] = 0;
}
} | pragma solidity ^0.4.15;
contract Reentrance {
mapping (address => uint) userBalance;
function getBalance(address u) constant returns(uint){
return userBalance[u];
}
function addToBalance() payable{
userBalance[msg.sender] += msg.value;
}
function withdrawBalance(){
if( ! (msg.sender.call.value(userBalance[msg.sender])() ) ){
throw;
}
userBalance[msg.sender] = 0;
}
} |
reentrancy | 0x941d225236464a25eb18076df7da6a91d0f95e9e.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 44
*/
pragma solidity ^0.4.19;
contract ETH_FUND
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
Log TransferLog;
uint lastBlock;
function ETH_FUND(address _log)
public
{
TransferLog = Log(_log);
}
function Deposit()
public
payable
{
if(msg.value > MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
lastBlock = block.number;
}
}
function CashOut(uint _am)
public
payable
{
if(_am<=balances[msg.sender]&&block.number>lastBlock)
{
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} | pragma solidity ^0.4.19;
contract ETH_FUND
{
mapping (address => uint) public balances;
uint public MinDeposit = 1 ether;
Log TransferLog;
uint lastBlock;
function ETH_FUND(address _log)
public
{
TransferLog = Log(_log);
}
function Deposit()
public
payable
{
if(msg.value > MinDeposit)
{
balances[msg.sender]+=msg.value;
TransferLog.AddMessage(msg.sender,msg.value,"Deposit");
lastBlock = block.number;
}
}
function CashOut(uint _am)
public
payable
{
if(_am<=balances[msg.sender]&&block.number>lastBlock)
{
if(msg.sender.call.value(_am)())
{
balances[msg.sender]-=_am;
TransferLog.AddMessage(msg.sender,_am,"CashOut");
}
}
}
function() public payable{}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} |
reentrancy | etherstore.sol | /*
* @source: https://github.com/sigp/solidity-security-blog
* @author: Suhabe Bugrara
* @vulnerable_at_lines: 27
*/
//added pragma version
pragma solidity ^0.4.10;
contract EtherStore {
uint256 public withdrawalLimit = 1 ether;
mapping(address => uint256) public lastWithdrawTime;
mapping(address => uint256) public balances;
function depositFunds() public payable {
balances[msg.sender] += msg.value;
}
function withdrawFunds (uint256 _weiToWithdraw) public {
require(balances[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(_weiToWithdraw <= withdrawalLimit);
// limit the time allowed to withdraw
require(now >= lastWithdrawTime[msg.sender] + 1 weeks);
// <yes> <report> REENTRANCY
require(msg.sender.call.value(_weiToWithdraw)());
balances[msg.sender] -= _weiToWithdraw;
lastWithdrawTime[msg.sender] = now;
}
} | pragma solidity ^0.4.10;
contract EtherStore {
uint256 public withdrawalLimit = 1 ether;
mapping(address => uint256) public lastWithdrawTime;
mapping(address => uint256) public balances;
function depositFunds() public payable {
balances[msg.sender] += msg.value;
}
function withdrawFunds (uint256 _weiToWithdraw) public {
require(balances[msg.sender] >= _weiToWithdraw);
require(_weiToWithdraw <= withdrawalLimit);
require(now >= lastWithdrawTime[msg.sender] + 1 weeks);
require(msg.sender.call.value(_weiToWithdraw)());
balances[msg.sender] -= _weiToWithdraw;
lastWithdrawTime[msg.sender] = now;
}
} |
reentrancy | 0x7b368c4e805c3870b6c49a3f1f49f69af8662cf3.sol | /*
* @source: etherscan.io
* @author: -
* @vulnerable_at_lines: 29
*/
pragma solidity ^0.4.25;
contract W_WALLET
{
function Put(uint _unlockTime)
public
payable
{
var acc = Acc[msg.sender];
acc.balance += msg.value;
acc.unlockTime = _unlockTime>now?_unlockTime:now;
LogFile.AddMessage(msg.sender,msg.value,"Put");
}
function Collect(uint _am)
public
payable
{
var acc = Acc[msg.sender];
if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime)
{
// <yes> <report> REENTRANCY
if(msg.sender.call.value(_am)())
{
acc.balance-=_am;
LogFile.AddMessage(msg.sender,_am,"Collect");
}
}
}
function()
public
payable
{
Put(0);
}
struct Holder
{
uint unlockTime;
uint balance;
}
mapping (address => Holder) public Acc;
Log LogFile;
uint public MinSum = 1 ether;
function W_WALLET(address log) public{
LogFile = Log(log);
}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} | pragma solidity ^0.4.25;
contract W_WALLET
{
function Put(uint _unlockTime)
public
payable
{
var acc = Acc[msg.sender];
acc.balance += msg.value;
acc.unlockTime = _unlockTime>now?_unlockTime:now;
LogFile.AddMessage(msg.sender,msg.value,"Put");
}
function Collect(uint _am)
public
payable
{
var acc = Acc[msg.sender];
if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime)
{
if(msg.sender.call.value(_am)())
{
acc.balance-=_am;
LogFile.AddMessage(msg.sender,_am,"Collect");
}
}
}
function()
public
payable
{
Put(0);
}
struct Holder
{
uint unlockTime;
uint balance;
}
mapping (address => Holder) public Acc;
Log LogFile;
uint public MinSum = 1 ether;
function W_WALLET(address log) public{
LogFile = Log(log);
}
}
contract Log
{
struct Message
{
address Sender;
string Data;
uint Val;
uint Time;
}
Message[] public History;
Message LastMsg;
function AddMessage(address _adr,uint _val,string _data)
public
{
LastMsg.Sender = _adr;
LastMsg.Time = now;
LastMsg.Val = _val;
LastMsg.Data = _data;
History.push(LastMsg);
}
} |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 2