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); } }
reentrancy
spank_chain_payment.sol
/* * @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/reentrancy/SpankChain_source_code/SpankChain_Payment.sol * @author: - * @vulnerable_at_lines: 426,430 */ // https://etherscan.io/address/0xf91546835f756da0c10cfa0cda95b15577b84aa7#code pragma solidity ^0.4.23; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library ECTools { // @dev Recovers the address which has signed a message // @thanks https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d function recoverSigner(bytes32 _hashedMsg, string _sig) public pure returns (address) { require(_hashedMsg != 0x00); // need this for test RPC bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hashedMsg)); if (bytes(_sig).length != 132) { return 0x0; } bytes32 r; bytes32 s; uint8 v; bytes memory sig = hexstrToBytes(substring(_sig, 2, 132)); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } if (v < 27 || v > 28) { return 0x0; } return ecrecover(prefixedHash, v, r, s); } // @dev Verifies if the message is signed by an address function isSignedBy(bytes32 _hashedMsg, string _sig, address _addr) public pure returns (bool) { require(_addr != 0x0); return _addr == recoverSigner(_hashedMsg, _sig); } // @dev Converts an hexstring to bytes function hexstrToBytes(string _hexstr) public pure returns (bytes) { uint len = bytes(_hexstr).length; require(len % 2 == 0); bytes memory bstr = bytes(new string(len / 2)); uint k = 0; string memory s; string memory r; for (uint i = 0; i < len; i += 2) { s = substring(_hexstr, i, i + 1); r = substring(_hexstr, i + 1, i + 2); uint p = parseInt16Char(s) * 16 + parseInt16Char(r); bstr[k++] = uintToBytes32(p)[31]; } return bstr; } // @dev Parses a hexchar, like 'a', and returns its hex value, in this case 10 function parseInt16Char(string _char) public pure returns (uint) { bytes memory bresult = bytes(_char); // bool decimals = false; if ((bresult[0] >= 48) && (bresult[0] <= 57)) { return uint(bresult[0]) - 48; } else if ((bresult[0] >= 65) && (bresult[0] <= 70)) { return uint(bresult[0]) - 55; } else if ((bresult[0] >= 97) && (bresult[0] <= 102)) { return uint(bresult[0]) - 87; } else { revert(); } } // @dev Converts a uint to a bytes32 // @thanks https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity function uintToBytes32(uint _uint) public pure returns (bytes b) { b = new bytes(32); assembly {mstore(add(b, 32), _uint)} } // @dev Hashes the signed message // @ref https://github.com/ethereum/go-ethereum/issues/3731#issuecomment-293866868 function toEthereumSignedMessage(string _msg) public pure returns (bytes32) { uint len = bytes(_msg).length; require(len > 0); bytes memory prefix = "\x19Ethereum Signed Message:\n"; return keccak256(abi.encodePacked(prefix, uintToString(len), _msg)); } // @dev Converts a uint in a string function uintToString(uint _uint) public pure returns (string str) { uint len = 0; uint m = _uint + 0; while (m != 0) { len++; m /= 10; } bytes memory b = new bytes(len); uint i = len - 1; while (_uint != 0) { uint remainder = _uint % 10; _uint = _uint / 10; b[i--] = byte(48 + remainder); } str = string(b); } // @dev extract a substring // @thanks https://ethereum.stackexchange.com/questions/31457/substring-in-solidity function substring(string _str, uint _startIndex, uint _endIndex) public pure returns (string) { bytes memory strBytes = bytes(_str); require(_startIndex <= _endIndex); require(_startIndex >= 0); require(_endIndex <= strBytes.length); bytes memory result = new bytes(_endIndex - _startIndex); for (uint i = _startIndex; i < _endIndex; i++) { result[i - _startIndex] = strBytes[i]; } return string(result); } } contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract HumanStandardToken is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } contract LedgerChannel { string public constant NAME = "Ledger Channel"; string public constant VERSION = "0.0.1"; uint256 public numChannels = 0; event DidLCOpen ( bytes32 indexed channelId, address indexed partyA, address indexed partyI, uint256 ethBalanceA, address token, uint256 tokenBalanceA, uint256 LCopenTimeout ); event DidLCJoin ( bytes32 indexed channelId, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidLCDeposit ( bytes32 indexed channelId, address indexed recipient, uint256 deposit, bool isToken ); event DidLCUpdateState ( bytes32 indexed channelId, uint256 sequence, uint256 numOpenVc, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI, bytes32 vcRoot, uint256 updateLCtimeout ); event DidLCClose ( bytes32 indexed channelId, uint256 sequence, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidVCInit ( bytes32 indexed lcId, bytes32 indexed vcId, bytes proof, uint256 sequence, address partyA, address partyB, uint256 balanceA, uint256 balanceB ); event DidVCSettle ( bytes32 indexed lcId, bytes32 indexed vcId, uint256 updateSeq, uint256 updateBalA, uint256 updateBalB, address challenger, uint256 updateVCtimeout ); event DidVCClose( bytes32 indexed lcId, bytes32 indexed vcId, uint256 balanceA, uint256 balanceB ); struct Channel { //TODO: figure out if it's better just to split arrays by balances/deposits instead of eth/erc20 address[2] partyAddresses; // 0: partyA 1: partyI uint256[4] ethBalances; // 0: balanceA 1:balanceI 2:depositedA 3:depositedI uint256[4] erc20Balances; // 0: balanceA 1:balanceI 2:depositedA 3:depositedI uint256[2] initialDeposit; // 0: eth 1: tokens uint256 sequence; uint256 confirmTime; bytes32 VCrootHash; uint256 LCopenTimeout; uint256 updateLCtimeout; // when update LC times out bool isOpen; // true when both parties have joined bool isUpdateLCSettling; uint256 numOpenVC; HumanStandardToken token; } // virtual-channel state struct VirtualChannel { bool isClose; bool isInSettlementState; uint256 sequence; address challenger; // Initiator of challenge uint256 updateVCtimeout; // when update VC times out // channel state address partyA; // VC participant A address partyB; // VC participant B address partyI; // LC hub uint256[2] ethBalances; uint256[2] erc20Balances; uint256[2] bond; HumanStandardToken token; } mapping(bytes32 => VirtualChannel) public virtualChannels; mapping(bytes32 => Channel) public Channels; function createChannel( bytes32 _lcID, address _partyI, uint256 _confirmTime, address _token, uint256[2] _balances // [eth, token] ) public payable { require(Channels[_lcID].partyAddresses[0] == address(0), "Channel has already been created."); require(_partyI != 0x0, "No partyI address provided to LC creation"); require(_balances[0] >= 0 && _balances[1] >= 0, "Balances cannot be negative"); // Set initial ledger channel state // Alice must execute this and we assume the initial state // to be signed from this requirement // Alternative is to check a sig as in joinChannel Channels[_lcID].partyAddresses[0] = msg.sender; Channels[_lcID].partyAddresses[1] = _partyI; if(_balances[0] != 0) { require(msg.value == _balances[0], "Eth balance does not match sent value"); Channels[_lcID].ethBalances[0] = msg.value; } if(_balances[1] != 0) { Channels[_lcID].token = HumanStandardToken(_token); require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"CreateChannel: token transfer failure"); Channels[_lcID].erc20Balances[0] = _balances[1]; } Channels[_lcID].sequence = 0; Channels[_lcID].confirmTime = _confirmTime; // is close flag, lc state sequence, number open vc, vc root hash, partyA... //Channels[_lcID].stateHash = keccak256(uint256(0), uint256(0), uint256(0), bytes32(0x0), bytes32(msg.sender), bytes32(_partyI), balanceA, balanceI); Channels[_lcID].LCopenTimeout = now + _confirmTime; Channels[_lcID].initialDeposit = _balances; emit DidLCOpen(_lcID, msg.sender, _partyI, _balances[0], _token, _balances[1], Channels[_lcID].LCopenTimeout); } function LCOpenTimeout(bytes32 _lcID) public { require(msg.sender == Channels[_lcID].partyAddresses[0] && Channels[_lcID].isOpen == false); require(now > Channels[_lcID].LCopenTimeout); if(Channels[_lcID].initialDeposit[0] != 0) { // <yes> <report> REENTRANCY Channels[_lcID].partyAddresses[0].transfer(Channels[_lcID].ethBalances[0]); } if(Channels[_lcID].initialDeposit[1] != 0) { // <yes> <report> REENTRANCY require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], Channels[_lcID].erc20Balances[0]),"CreateChannel: token transfer failure"); } emit DidLCClose(_lcID, 0, Channels[_lcID].ethBalances[0], Channels[_lcID].erc20Balances[0], 0, 0); // only safe to delete since no action was taken on this channel delete Channels[_lcID]; } function joinChannel(bytes32 _lcID, uint256[2] _balances) public payable { // require the channel is not open yet require(Channels[_lcID].isOpen == false); require(msg.sender == Channels[_lcID].partyAddresses[1]); if(_balances[0] != 0) { require(msg.value == _balances[0], "state balance does not match sent value"); Channels[_lcID].ethBalances[1] = msg.value; } if(_balances[1] != 0) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"joinChannel: token transfer failure"); Channels[_lcID].erc20Balances[1] = _balances[1]; } Channels[_lcID].initialDeposit[0]+=_balances[0]; Channels[_lcID].initialDeposit[1]+=_balances[1]; // no longer allow joining functions to be called Channels[_lcID].isOpen = true; numChannels++; emit DidLCJoin(_lcID, _balances[0], _balances[1]); } // additive updates of monetary state // TODO check this for attack vectors function deposit(bytes32 _lcID, address recipient, uint256 _balance, bool isToken) public payable { require(Channels[_lcID].isOpen == true, "Tried adding funds to a closed channel"); require(recipient == Channels[_lcID].partyAddresses[0] || recipient == Channels[_lcID].partyAddresses[1]); //if(Channels[_lcID].token) if (Channels[_lcID].partyAddresses[0] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[2] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[2] += msg.value; } } if (Channels[_lcID].partyAddresses[1] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[3] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[3] += msg.value; } } emit DidLCDeposit(_lcID, recipient, _balance, isToken); } // TODO: Check there are no open virtual channels, the client should have cought this before signing a close LC state update function consensusCloseChannel( bytes32 _lcID, uint256 _sequence, uint256[4] _balances, // 0: ethBalanceA 1:ethBalanceI 2:tokenBalanceA 3:tokenBalanceI string _sigA, string _sigI ) public { // assume num open vc is 0 and root hash is 0x0 //require(Channels[_lcID].sequence < _sequence); require(Channels[_lcID].isOpen == true); uint256 totalEthDeposit = Channels[_lcID].initialDeposit[0] + Channels[_lcID].ethBalances[2] + Channels[_lcID].ethBalances[3]; uint256 totalTokenDeposit = Channels[_lcID].initialDeposit[1] + Channels[_lcID].erc20Balances[2] + Channels[_lcID].erc20Balances[3]; require(totalEthDeposit == _balances[0] + _balances[1]); require(totalTokenDeposit == _balances[2] + _balances[3]); bytes32 _state = keccak256( abi.encodePacked( _lcID, true, _sequence, uint256(0), bytes32(0x0), Channels[_lcID].partyAddresses[0], Channels[_lcID].partyAddresses[1], _balances[0], _balances[1], _balances[2], _balances[3] ) ); require(Channels[_lcID].partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(Channels[_lcID].partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); Channels[_lcID].isOpen = false; if(_balances[0] != 0 || _balances[1] != 0) { Channels[_lcID].partyAddresses[0].transfer(_balances[0]); Channels[_lcID].partyAddresses[1].transfer(_balances[1]); } if(_balances[2] != 0 || _balances[3] != 0) { require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], _balances[2]),"happyCloseChannel: token transfer failure"); require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[1], _balances[3]),"happyCloseChannel: token transfer failure"); } numChannels--; emit DidLCClose(_lcID, _sequence, _balances[0], _balances[1], _balances[2], _balances[3]); } // Byzantine functions function updateLCstate( bytes32 _lcID, uint256[6] updateParams, // [sequence, numOpenVc, ethbalanceA, ethbalanceI, tokenbalanceA, tokenbalanceI] bytes32 _VCroot, string _sigA, string _sigI ) public { Channel storage channel = Channels[_lcID]; require(channel.isOpen); require(channel.sequence < updateParams[0]); // do same as vc sequence check require(channel.ethBalances[0] + channel.ethBalances[1] >= updateParams[2] + updateParams[3]); require(channel.erc20Balances[0] + channel.erc20Balances[1] >= updateParams[4] + updateParams[5]); if(channel.isUpdateLCSettling == true) { require(channel.updateLCtimeout > now); } bytes32 _state = keccak256( abi.encodePacked( _lcID, false, updateParams[0], updateParams[1], _VCroot, channel.partyAddresses[0], channel.partyAddresses[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5] ) ); require(channel.partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(channel.partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); // update LC state channel.sequence = updateParams[0]; channel.numOpenVC = updateParams[1]; channel.ethBalances[0] = updateParams[2]; channel.ethBalances[1] = updateParams[3]; channel.erc20Balances[0] = updateParams[4]; channel.erc20Balances[1] = updateParams[5]; channel.VCrootHash = _VCroot; channel.isUpdateLCSettling = true; channel.updateLCtimeout = now + channel.confirmTime; // make settlement flag emit DidLCUpdateState ( _lcID, updateParams[0], updateParams[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5], _VCroot, channel.updateLCtimeout ); } // supply initial state of VC to "prime" the force push game function initVCstate( bytes32 _lcID, bytes32 _vcID, bytes _proof, address _partyA, address _partyB, uint256[2] _bond, uint256[4] _balances, // 0: ethBalanceA 1:ethBalanceI 2:tokenBalanceA 3:tokenBalanceI string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); // sub-channel must be open require(!virtualChannels[_vcID].isClose, "VC is closed."); // Check time has passed on updateLCtimeout and has not passed the time to store a vc state require(Channels[_lcID].updateLCtimeout < now, "LC timeout not over."); // prevent rentry of initializing vc state require(virtualChannels[_vcID].updateVCtimeout == 0); // partyB is now Ingrid bytes32 _initState = keccak256( abi.encodePacked(_vcID, uint256(0), _partyA, _partyB, _bond[0], _bond[1], _balances[0], _balances[1], _balances[2], _balances[3]) ); // Make sure Alice has signed initial vc state (A/B in oldState) require(_partyA == ECTools.recoverSigner(_initState, sigA)); // Check the oldState is in the root hash require(_isContained(_initState, _proof, Channels[_lcID].VCrootHash) == true); virtualChannels[_vcID].partyA = _partyA; // VC participant A virtualChannels[_vcID].partyB = _partyB; // VC participant B virtualChannels[_vcID].sequence = uint256(0); virtualChannels[_vcID].ethBalances[0] = _balances[0]; virtualChannels[_vcID].ethBalances[1] = _balances[1]; virtualChannels[_vcID].erc20Balances[0] = _balances[2]; virtualChannels[_vcID].erc20Balances[1] = _balances[3]; virtualChannels[_vcID].bond = _bond; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; virtualChannels[_vcID].isInSettlementState = true; emit DidVCInit(_lcID, _vcID, _proof, uint256(0), _partyA, _partyB, _balances[0], _balances[1]); } //TODO: verify state transition since the hub did not agree to this state // make sure the A/B balances are not beyond ingrids bonds // Params: vc init state, vc final balance, vcID function settleVC( bytes32 _lcID, bytes32 _vcID, uint256 updateSeq, address _partyA, address _partyB, uint256[4] updateBal, // [ethupdateBalA, ethupdateBalB, tokenupdateBalA, tokenupdateBalB] string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); // sub-channel must be open require(!virtualChannels[_vcID].isClose, "VC is closed."); require(virtualChannels[_vcID].sequence < updateSeq, "VC sequence is higher than update sequence."); require( virtualChannels[_vcID].ethBalances[1] < updateBal[1] && virtualChannels[_vcID].erc20Balances[1] < updateBal[3], "State updates may only increase recipient balance." ); require( virtualChannels[_vcID].bond[0] == updateBal[0] + updateBal[1] && virtualChannels[_vcID].bond[1] == updateBal[2] + updateBal[3], "Incorrect balances for bonded amount"); // Check time has passed on updateLCtimeout and has not passed the time to store a vc state // virtualChannels[_vcID].updateVCtimeout should be 0 on uninitialized vc state, and this should // fail if initVC() isn't called first // require(Channels[_lcID].updateLCtimeout < now && now < virtualChannels[_vcID].updateVCtimeout); require(Channels[_lcID].updateLCtimeout < now); // for testing! bytes32 _updateState = keccak256( abi.encodePacked( _vcID, updateSeq, _partyA, _partyB, virtualChannels[_vcID].bond[0], virtualChannels[_vcID].bond[1], updateBal[0], updateBal[1], updateBal[2], updateBal[3] ) ); // Make sure Alice has signed a higher sequence new state require(virtualChannels[_vcID].partyA == ECTools.recoverSigner(_updateState, sigA)); // store VC data // we may want to record who is initiating on-chain settles virtualChannels[_vcID].challenger = msg.sender; virtualChannels[_vcID].sequence = updateSeq; // channel state virtualChannels[_vcID].ethBalances[0] = updateBal[0]; virtualChannels[_vcID].ethBalances[1] = updateBal[1]; virtualChannels[_vcID].erc20Balances[0] = updateBal[2]; virtualChannels[_vcID].erc20Balances[1] = updateBal[3]; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; emit DidVCSettle(_lcID, _vcID, updateSeq, updateBal[0], updateBal[1], msg.sender, virtualChannels[_vcID].updateVCtimeout); } function closeVirtualChannel(bytes32 _lcID, bytes32 _vcID) public { // require(updateLCtimeout > now) require(Channels[_lcID].isOpen, "LC is closed."); require(virtualChannels[_vcID].isInSettlementState, "VC is not in settlement state."); require(virtualChannels[_vcID].updateVCtimeout < now, "Update vc timeout has not elapsed."); require(!virtualChannels[_vcID].isClose, "VC is already closed"); // reduce the number of open virtual channels stored on LC Channels[_lcID].numOpenVC--; // close vc flags virtualChannels[_vcID].isClose = true; // re-introduce the balances back into the LC state from the settled VC // decide if this lc is alice or bob in the vc if(virtualChannels[_vcID].partyA == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[0]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[1]; } else if (virtualChannels[_vcID].partyB == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[1]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[0]; } emit DidVCClose(_lcID, _vcID, virtualChannels[_vcID].erc20Balances[0], virtualChannels[_vcID].erc20Balances[1]); } // todo: allow ethier lc.end-user to nullify the settled LC state and return to off-chain function byzantineCloseChannel(bytes32 _lcID) public { Channel storage channel = Channels[_lcID]; // check settlement flag require(channel.isOpen, "Channel is not open"); require(channel.isUpdateLCSettling == true); require(channel.numOpenVC == 0); require(channel.updateLCtimeout < now, "LC timeout over."); // if off chain state update didnt reblance deposits, just return to deposit owner uint256 totalEthDeposit = channel.initialDeposit[0] + channel.ethBalances[2] + channel.ethBalances[3]; uint256 totalTokenDeposit = channel.initialDeposit[1] + channel.erc20Balances[2] + channel.erc20Balances[3]; uint256 possibleTotalEthBeforeDeposit = channel.ethBalances[0] + channel.ethBalances[1]; uint256 possibleTotalTokenBeforeDeposit = channel.erc20Balances[0] + channel.erc20Balances[1]; if(possibleTotalEthBeforeDeposit < totalEthDeposit) { channel.ethBalances[0]+=channel.ethBalances[2]; channel.ethBalances[1]+=channel.ethBalances[3]; } else { require(possibleTotalEthBeforeDeposit == totalEthDeposit); } if(possibleTotalTokenBeforeDeposit < totalTokenDeposit) { channel.erc20Balances[0]+=channel.erc20Balances[2]; channel.erc20Balances[1]+=channel.erc20Balances[3]; } else { require(possibleTotalTokenBeforeDeposit == totalTokenDeposit); } // reentrancy uint256 ethbalanceA = channel.ethBalances[0]; uint256 ethbalanceI = channel.ethBalances[1]; uint256 tokenbalanceA = channel.erc20Balances[0]; uint256 tokenbalanceI = channel.erc20Balances[1]; channel.ethBalances[0] = 0; channel.ethBalances[1] = 0; channel.erc20Balances[0] = 0; channel.erc20Balances[1] = 0; if(ethbalanceA != 0 || ethbalanceI != 0) { channel.partyAddresses[0].transfer(ethbalanceA); channel.partyAddresses[1].transfer(ethbalanceI); } if(tokenbalanceA != 0 || tokenbalanceI != 0) { require( channel.token.transfer(channel.partyAddresses[0], tokenbalanceA), "byzantineCloseChannel: token transfer failure" ); require( channel.token.transfer(channel.partyAddresses[1], tokenbalanceI), "byzantineCloseChannel: token transfer failure" ); } channel.isOpen = false; numChannels--; emit DidLCClose(_lcID, channel.sequence, ethbalanceA, ethbalanceI, tokenbalanceA, tokenbalanceI); } function _isContained(bytes32 _hash, bytes _proof, bytes32 _root) internal pure returns (bool) { bytes32 cursor = _hash; bytes32 proofElem; for (uint256 i = 64; i <= _proof.length; i += 32) { assembly { proofElem := mload(add(_proof, i)) } if (cursor < proofElem) { cursor = keccak256(abi.encodePacked(cursor, proofElem)); } else { cursor = keccak256(abi.encodePacked(proofElem, cursor)); } } return cursor == _root; } //Struct Getters function getChannel(bytes32 id) public view returns ( address[2], uint256[4], uint256[4], uint256[2], uint256, uint256, bytes32, uint256, uint256, bool, bool, uint256 ) { Channel memory channel = Channels[id]; return ( channel.partyAddresses, channel.ethBalances, channel.erc20Balances, channel.initialDeposit, channel.sequence, channel.confirmTime, channel.VCrootHash, channel.LCopenTimeout, channel.updateLCtimeout, channel.isOpen, channel.isUpdateLCSettling, channel.numOpenVC ); } function getVirtualChannel(bytes32 id) public view returns( bool, bool, uint256, address, uint256, address, address, address, uint256[2], uint256[2], uint256[2] ) { VirtualChannel memory virtualChannel = virtualChannels[id]; return( virtualChannel.isClose, virtualChannel.isInSettlementState, virtualChannel.sequence, virtualChannel.challenger, virtualChannel.updateVCtimeout, virtualChannel.partyA, virtualChannel.partyB, virtualChannel.partyI, virtualChannel.ethBalances, virtualChannel.erc20Balances, virtualChannel.bond ); } }
pragma solidity ^0.4.23; contract Token { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library ECTools { function recoverSigner(bytes32 _hashedMsg, string _sig) public pure returns (address) { require(_hashedMsg != 0x00); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hashedMsg)); if (bytes(_sig).length != 132) { return 0x0; } bytes32 r; bytes32 s; uint8 v; bytes memory sig = hexstrToBytes(substring(_sig, 2, 132)); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } if (v < 27 || v > 28) { return 0x0; } return ecrecover(prefixedHash, v, r, s); } function isSignedBy(bytes32 _hashedMsg, string _sig, address _addr) public pure returns (bool) { require(_addr != 0x0); return _addr == recoverSigner(_hashedMsg, _sig); } function hexstrToBytes(string _hexstr) public pure returns (bytes) { uint len = bytes(_hexstr).length; require(len % 2 == 0); bytes memory bstr = bytes(new string(len / 2)); uint k = 0; string memory s; string memory r; for (uint i = 0; i < len; i += 2) { s = substring(_hexstr, i, i + 1); r = substring(_hexstr, i + 1, i + 2); uint p = parseInt16Char(s) * 16 + parseInt16Char(r); bstr[k++] = uintToBytes32(p)[31]; } return bstr; } function parseInt16Char(string _char) public pure returns (uint) { bytes memory bresult = bytes(_char); if ((bresult[0] >= 48) && (bresult[0] <= 57)) { return uint(bresult[0]) - 48; } else if ((bresult[0] >= 65) && (bresult[0] <= 70)) { return uint(bresult[0]) - 55; } else if ((bresult[0] >= 97) && (bresult[0] <= 102)) { return uint(bresult[0]) - 87; } else { revert(); } } function uintToBytes32(uint _uint) public pure returns (bytes b) { b = new bytes(32); assembly {mstore(add(b, 32), _uint)} } function toEthereumSignedMessage(string _msg) public pure returns (bytes32) { uint len = bytes(_msg).length; require(len > 0); bytes memory prefix = "\x19Ethereum Signed Message:\n"; return keccak256(abi.encodePacked(prefix, uintToString(len), _msg)); } function uintToString(uint _uint) public pure returns (string str) { uint len = 0; uint m = _uint + 0; while (m != 0) { len++; m /= 10; } bytes memory b = new bytes(len); uint i = len - 1; while (_uint != 0) { uint remainder = _uint % 10; _uint = _uint / 10; b[i--] = byte(48 + remainder); } str = string(b); } function substring(string _str, uint _startIndex, uint _endIndex) public pure returns (string) { bytes memory strBytes = bytes(_str); require(_startIndex <= _endIndex); require(_startIndex >= 0); require(_endIndex <= strBytes.length); bytes memory result = new bytes(_endIndex - _startIndex); for (uint i = _startIndex; i < _endIndex; i++) { result[i - _startIndex] = strBytes[i]; } return string(result); } } contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract HumanStandardToken is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H0.1'; constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } contract LedgerChannel { string public constant NAME = "Ledger Channel"; string public constant VERSION = "0.0.1"; uint256 public numChannels = 0; event DidLCOpen ( bytes32 indexed channelId, address indexed partyA, address indexed partyI, uint256 ethBalanceA, address token, uint256 tokenBalanceA, uint256 LCopenTimeout ); event DidLCJoin ( bytes32 indexed channelId, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidLCDeposit ( bytes32 indexed channelId, address indexed recipient, uint256 deposit, bool isToken ); event DidLCUpdateState ( bytes32 indexed channelId, uint256 sequence, uint256 numOpenVc, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI, bytes32 vcRoot, uint256 updateLCtimeout ); event DidLCClose ( bytes32 indexed channelId, uint256 sequence, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidVCInit ( bytes32 indexed lcId, bytes32 indexed vcId, bytes proof, uint256 sequence, address partyA, address partyB, uint256 balanceA, uint256 balanceB ); event DidVCSettle ( bytes32 indexed lcId, bytes32 indexed vcId, uint256 updateSeq, uint256 updateBalA, uint256 updateBalB, address challenger, uint256 updateVCtimeout ); event DidVCClose( bytes32 indexed lcId, bytes32 indexed vcId, uint256 balanceA, uint256 balanceB ); struct Channel { address[2] partyAddresses; uint256[4] ethBalances; uint256[4] erc20Balances; uint256[2] initialDeposit; uint256 sequence; uint256 confirmTime; bytes32 VCrootHash; uint256 LCopenTimeout; uint256 updateLCtimeout; bool isOpen; bool isUpdateLCSettling; uint256 numOpenVC; HumanStandardToken token; } struct VirtualChannel { bool isClose; bool isInSettlementState; uint256 sequence; address challenger; uint256 updateVCtimeout; address partyA; address partyB; address partyI; uint256[2] ethBalances; uint256[2] erc20Balances; uint256[2] bond; HumanStandardToken token; } mapping(bytes32 => VirtualChannel) public virtualChannels; mapping(bytes32 => Channel) public Channels; function createChannel( bytes32 _lcID, address _partyI, uint256 _confirmTime, address _token, uint256[2] _balances ) public payable { require(Channels[_lcID].partyAddresses[0] == address(0), "Channel has already been created."); require(_partyI != 0x0, "No partyI address provided to LC creation"); require(_balances[0] >= 0 && _balances[1] >= 0, "Balances cannot be negative"); Channels[_lcID].partyAddresses[0] = msg.sender; Channels[_lcID].partyAddresses[1] = _partyI; if(_balances[0] != 0) { require(msg.value == _balances[0], "Eth balance does not match sent value"); Channels[_lcID].ethBalances[0] = msg.value; } if(_balances[1] != 0) { Channels[_lcID].token = HumanStandardToken(_token); require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"CreateChannel: token transfer failure"); Channels[_lcID].erc20Balances[0] = _balances[1]; } Channels[_lcID].sequence = 0; Channels[_lcID].confirmTime = _confirmTime; Channels[_lcID].LCopenTimeout = now + _confirmTime; Channels[_lcID].initialDeposit = _balances; emit DidLCOpen(_lcID, msg.sender, _partyI, _balances[0], _token, _balances[1], Channels[_lcID].LCopenTimeout); } function LCOpenTimeout(bytes32 _lcID) public { require(msg.sender == Channels[_lcID].partyAddresses[0] && Channels[_lcID].isOpen == false); require(now > Channels[_lcID].LCopenTimeout); if(Channels[_lcID].initialDeposit[0] != 0) { Channels[_lcID].partyAddresses[0].transfer(Channels[_lcID].ethBalances[0]); } if(Channels[_lcID].initialDeposit[1] != 0) { require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], Channels[_lcID].erc20Balances[0]),"CreateChannel: token transfer failure"); } emit DidLCClose(_lcID, 0, Channels[_lcID].ethBalances[0], Channels[_lcID].erc20Balances[0], 0, 0); delete Channels[_lcID]; } function joinChannel(bytes32 _lcID, uint256[2] _balances) public payable { require(Channels[_lcID].isOpen == false); require(msg.sender == Channels[_lcID].partyAddresses[1]); if(_balances[0] != 0) { require(msg.value == _balances[0], "state balance does not match sent value"); Channels[_lcID].ethBalances[1] = msg.value; } if(_balances[1] != 0) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"joinChannel: token transfer failure"); Channels[_lcID].erc20Balances[1] = _balances[1]; } Channels[_lcID].initialDeposit[0]+=_balances[0]; Channels[_lcID].initialDeposit[1]+=_balances[1]; Channels[_lcID].isOpen = true; numChannels++; emit DidLCJoin(_lcID, _balances[0], _balances[1]); } function deposit(bytes32 _lcID, address recipient, uint256 _balance, bool isToken) public payable { require(Channels[_lcID].isOpen == true, "Tried adding funds to a closed channel"); require(recipient == Channels[_lcID].partyAddresses[0] || recipient == Channels[_lcID].partyAddresses[1]); if (Channels[_lcID].partyAddresses[0] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[2] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[2] += msg.value; } } if (Channels[_lcID].partyAddresses[1] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[3] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[3] += msg.value; } } emit DidLCDeposit(_lcID, recipient, _balance, isToken); } function consensusCloseChannel( bytes32 _lcID, uint256 _sequence, uint256[4] _balances, string _sigA, string _sigI ) public { require(Channels[_lcID].isOpen == true); uint256 totalEthDeposit = Channels[_lcID].initialDeposit[0] + Channels[_lcID].ethBalances[2] + Channels[_lcID].ethBalances[3]; uint256 totalTokenDeposit = Channels[_lcID].initialDeposit[1] + Channels[_lcID].erc20Balances[2] + Channels[_lcID].erc20Balances[3]; require(totalEthDeposit == _balances[0] + _balances[1]); require(totalTokenDeposit == _balances[2] + _balances[3]); bytes32 _state = keccak256( abi.encodePacked( _lcID, true, _sequence, uint256(0), bytes32(0x0), Channels[_lcID].partyAddresses[0], Channels[_lcID].partyAddresses[1], _balances[0], _balances[1], _balances[2], _balances[3] ) ); require(Channels[_lcID].partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(Channels[_lcID].partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); Channels[_lcID].isOpen = false; if(_balances[0] != 0 || _balances[1] != 0) { Channels[_lcID].partyAddresses[0].transfer(_balances[0]); Channels[_lcID].partyAddresses[1].transfer(_balances[1]); } if(_balances[2] != 0 || _balances[3] != 0) { require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], _balances[2]),"happyCloseChannel: token transfer failure"); require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[1], _balances[3]),"happyCloseChannel: token transfer failure"); } numChannels--; emit DidLCClose(_lcID, _sequence, _balances[0], _balances[1], _balances[2], _balances[3]); } function updateLCstate( bytes32 _lcID, uint256[6] updateParams, bytes32 _VCroot, string _sigA, string _sigI ) public { Channel storage channel = Channels[_lcID]; require(channel.isOpen); require(channel.sequence < updateParams[0]); require(channel.ethBalances[0] + channel.ethBalances[1] >= updateParams[2] + updateParams[3]); require(channel.erc20Balances[0] + channel.erc20Balances[1] >= updateParams[4] + updateParams[5]); if(channel.isUpdateLCSettling == true) { require(channel.updateLCtimeout > now); } bytes32 _state = keccak256( abi.encodePacked( _lcID, false, updateParams[0], updateParams[1], _VCroot, channel.partyAddresses[0], channel.partyAddresses[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5] ) ); require(channel.partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(channel.partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); channel.sequence = updateParams[0]; channel.numOpenVC = updateParams[1]; channel.ethBalances[0] = updateParams[2]; channel.ethBalances[1] = updateParams[3]; channel.erc20Balances[0] = updateParams[4]; channel.erc20Balances[1] = updateParams[5]; channel.VCrootHash = _VCroot; channel.isUpdateLCSettling = true; channel.updateLCtimeout = now + channel.confirmTime; emit DidLCUpdateState ( _lcID, updateParams[0], updateParams[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5], _VCroot, channel.updateLCtimeout ); } function initVCstate( bytes32 _lcID, bytes32 _vcID, bytes _proof, address _partyA, address _partyB, uint256[2] _bond, uint256[4] _balances, string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); require(!virtualChannels[_vcID].isClose, "VC is closed."); require(Channels[_lcID].updateLCtimeout < now, "LC timeout not over."); require(virtualChannels[_vcID].updateVCtimeout == 0); bytes32 _initState = keccak256( abi.encodePacked(_vcID, uint256(0), _partyA, _partyB, _bond[0], _bond[1], _balances[0], _balances[1], _balances[2], _balances[3]) ); require(_partyA == ECTools.recoverSigner(_initState, sigA)); require(_isContained(_initState, _proof, Channels[_lcID].VCrootHash) == true); virtualChannels[_vcID].partyA = _partyA; virtualChannels[_vcID].partyB = _partyB; virtualChannels[_vcID].sequence = uint256(0); virtualChannels[_vcID].ethBalances[0] = _balances[0]; virtualChannels[_vcID].ethBalances[1] = _balances[1]; virtualChannels[_vcID].erc20Balances[0] = _balances[2]; virtualChannels[_vcID].erc20Balances[1] = _balances[3]; virtualChannels[_vcID].bond = _bond; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; virtualChannels[_vcID].isInSettlementState = true; emit DidVCInit(_lcID, _vcID, _proof, uint256(0), _partyA, _partyB, _balances[0], _balances[1]); } function settleVC( bytes32 _lcID, bytes32 _vcID, uint256 updateSeq, address _partyA, address _partyB, uint256[4] updateBal, string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); require(!virtualChannels[_vcID].isClose, "VC is closed."); require(virtualChannels[_vcID].sequence < updateSeq, "VC sequence is higher than update sequence."); require( virtualChannels[_vcID].ethBalances[1] < updateBal[1] && virtualChannels[_vcID].erc20Balances[1] < updateBal[3], "State updates may only increase recipient balance." ); require( virtualChannels[_vcID].bond[0] == updateBal[0] + updateBal[1] && virtualChannels[_vcID].bond[1] == updateBal[2] + updateBal[3], "Incorrect balances for bonded amount"); require(Channels[_lcID].updateLCtimeout < now); bytes32 _updateState = keccak256( abi.encodePacked( _vcID, updateSeq, _partyA, _partyB, virtualChannels[_vcID].bond[0], virtualChannels[_vcID].bond[1], updateBal[0], updateBal[1], updateBal[2], updateBal[3] ) ); require(virtualChannels[_vcID].partyA == ECTools.recoverSigner(_updateState, sigA)); virtualChannels[_vcID].challenger = msg.sender; virtualChannels[_vcID].sequence = updateSeq; virtualChannels[_vcID].ethBalances[0] = updateBal[0]; virtualChannels[_vcID].ethBalances[1] = updateBal[1]; virtualChannels[_vcID].erc20Balances[0] = updateBal[2]; virtualChannels[_vcID].erc20Balances[1] = updateBal[3]; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; emit DidVCSettle(_lcID, _vcID, updateSeq, updateBal[0], updateBal[1], msg.sender, virtualChannels[_vcID].updateVCtimeout); } function closeVirtualChannel(bytes32 _lcID, bytes32 _vcID) public { require(Channels[_lcID].isOpen, "LC is closed."); require(virtualChannels[_vcID].isInSettlementState, "VC is not in settlement state."); require(virtualChannels[_vcID].updateVCtimeout < now, "Update vc timeout has not elapsed."); require(!virtualChannels[_vcID].isClose, "VC is already closed"); Channels[_lcID].numOpenVC--; virtualChannels[_vcID].isClose = true; if(virtualChannels[_vcID].partyA == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[0]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[1]; } else if (virtualChannels[_vcID].partyB == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[1]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[0]; } emit DidVCClose(_lcID, _vcID, virtualChannels[_vcID].erc20Balances[0], virtualChannels[_vcID].erc20Balances[1]); } function byzantineCloseChannel(bytes32 _lcID) public { Channel storage channel = Channels[_lcID]; require(channel.isOpen, "Channel is not open"); require(channel.isUpdateLCSettling == true); require(channel.numOpenVC == 0); require(channel.updateLCtimeout < now, "LC timeout over."); uint256 totalEthDeposit = channel.initialDeposit[0] + channel.ethBalances[2] + channel.ethBalances[3]; uint256 totalTokenDeposit = channel.initialDeposit[1] + channel.erc20Balances[2] + channel.erc20Balances[3]; uint256 possibleTotalEthBeforeDeposit = channel.ethBalances[0] + channel.ethBalances[1]; uint256 possibleTotalTokenBeforeDeposit = channel.erc20Balances[0] + channel.erc20Balances[1]; if(possibleTotalEthBeforeDeposit < totalEthDeposit) { channel.ethBalances[0]+=channel.ethBalances[2]; channel.ethBalances[1]+=channel.ethBalances[3]; } else { require(possibleTotalEthBeforeDeposit == totalEthDeposit); } if(possibleTotalTokenBeforeDeposit < totalTokenDeposit) { channel.erc20Balances[0]+=channel.erc20Balances[2]; channel.erc20Balances[1]+=channel.erc20Balances[3]; } else { require(possibleTotalTokenBeforeDeposit == totalTokenDeposit); } uint256 ethbalanceA = channel.ethBalances[0]; uint256 ethbalanceI = channel.ethBalances[1]; uint256 tokenbalanceA = channel.erc20Balances[0]; uint256 tokenbalanceI = channel.erc20Balances[1]; channel.ethBalances[0] = 0; channel.ethBalances[1] = 0; channel.erc20Balances[0] = 0; channel.erc20Balances[1] = 0; if(ethbalanceA != 0 || ethbalanceI != 0) { channel.partyAddresses[0].transfer(ethbalanceA); channel.partyAddresses[1].transfer(ethbalanceI); } if(tokenbalanceA != 0 || tokenbalanceI != 0) { require( channel.token.transfer(channel.partyAddresses[0], tokenbalanceA), "byzantineCloseChannel: token transfer failure" ); require( channel.token.transfer(channel.partyAddresses[1], tokenbalanceI), "byzantineCloseChannel: token transfer failure" ); } channel.isOpen = false; numChannels--; emit DidLCClose(_lcID, channel.sequence, ethbalanceA, ethbalanceI, tokenbalanceA, tokenbalanceI); } function _isContained(bytes32 _hash, bytes _proof, bytes32 _root) internal pure returns (bool) { bytes32 cursor = _hash; bytes32 proofElem; for (uint256 i = 64; i <= _proof.length; i += 32) { assembly { proofElem := mload(add(_proof, i)) } if (cursor < proofElem) { cursor = keccak256(abi.encodePacked(cursor, proofElem)); } else { cursor = keccak256(abi.encodePacked(proofElem, cursor)); } } return cursor == _root; } function getChannel(bytes32 id) public view returns ( address[2], uint256[4], uint256[4], uint256[2], uint256, uint256, bytes32, uint256, uint256, bool, bool, uint256 ) { Channel memory channel = Channels[id]; return ( channel.partyAddresses, channel.ethBalances, channel.erc20Balances, channel.initialDeposit, channel.sequence, channel.confirmTime, channel.VCrootHash, channel.LCopenTimeout, channel.updateLCtimeout, channel.isOpen, channel.isUpdateLCSettling, channel.numOpenVC ); } function getVirtualChannel(bytes32 id) public view returns( bool, bool, uint256, address, uint256, address, address, address, uint256[2], uint256[2], uint256[2] ) { VirtualChannel memory virtualChannel = virtualChannels[id]; return( virtualChannel.isClose, virtualChannel.isInSettlementState, virtualChannel.sequence, virtualChannel.challenger, virtualChannel.updateVCtimeout, virtualChannel.partyA, virtualChannel.partyB, virtualChannel.partyI, virtualChannel.ethBalances, virtualChannel.erc20Balances, virtualChannel.bond ); } }
reentrancy
0xb5e1b1ee15c6fa0e48fce100125569d430f1bd12.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 40 */ pragma solidity ^0.4.19; contract Private_Bank { mapping (address => uint) public balances; uint public MinDeposit = 1 ether; Log TransferLog; function Private_Bank(address _log) { 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 Private_Bank { mapping (address => uint) public balances; uint public MinDeposit = 1 ether; Log TransferLog; function Private_Bank(address _log) { 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
0xbe4041d55db380c5ae9d4a9b9703f1ed4e7e3888.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 63 */ pragma solidity ^0.4.19; contract MONEY_BOX { struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; uint public MinSum; Log LogFile; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; LogFile = Log(_log); } function Initialized() public { intitalized = true; } function Put(uint _lockTime) public payable { var acc = Acc[msg.sender]; acc.balance += msg.value; if(now+_lockTime>acc.unlockTime)acc.unlockTime=now+_lockTime; 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); } } 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 MONEY_BOX { struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; uint public MinSum; Log LogFile; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; LogFile = Log(_log); } function Initialized() public { intitalized = true; } function Put(uint _lockTime) public payable { var acc = Acc[msg.sender]; acc.balance += msg.value; if(now+_lockTime>acc.unlockTime)acc.unlockTime=now+_lockTime; 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); } } 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
0x01f8c4e3fa3edeb29e514cba738d87ce8c091d3f.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 54 */ pragma solidity ^0.4.19; contract PERSONAL_BANK { mapping (address=>uint256) public balances; uint public MinSum = 1 ether; LogFile Log = LogFile(0x0486cF65A2F2F3A392CBEa398AFB7F5f0B72FF46); bool intitalized; function SetMinSum(uint _val) public { if(intitalized)revert(); MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)revert(); Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { // <yes> <report> REENTRANCY if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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 PERSONAL_BANK { mapping (address=>uint256) public balances; uint public MinSum = 1 ether; LogFile Log = LogFile(0x0486cF65A2F2F3A392CBEa398AFB7F5f0B72FF46); bool intitalized; function SetMinSum(uint _val) public { if(intitalized)revert(); MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)revert(); Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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
0x4320e6f8c05b27ab4707cd1f6d5ce6f3e4b3a5a1.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 55 */ pragma solidity ^0.4.19; contract ACCURAL_DEPOSIT { mapping (address=>uint256) public balances; uint public MinSum = 1 ether; LogFile Log = LogFile(0x0486cF65A2F2F3A392CBEa398AFB7F5f0B72FF46); bool intitalized; function SetMinSum(uint _val) public { if(intitalized)revert(); MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)revert(); Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { // <yes> <report> REENTRANCY if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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 ACCURAL_DEPOSIT { mapping (address=>uint256) public balances; uint public MinSum = 1 ether; LogFile Log = LogFile(0x0486cF65A2F2F3A392CBEa398AFB7F5f0B72FF46); bool intitalized; function SetMinSum(uint _val) public { if(intitalized)revert(); MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)revert(); Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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
0x7541b76cb60f4c60af330c208b0623b7f54bf615.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 29 */ pragma solidity ^0.4.25; contract U_BANK { 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 = 2 ether; function U_BANK(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 U_BANK { 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 = 2 ether; function U_BANK(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
0x96edbe868531bd23a6c05e9d0c424ea64fb1b78b.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 63 */ pragma solidity ^0.4.19; contract PENNY_BY_PENNY { struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Put(uint _lockTime) public payable { var acc = Acc[msg.sender]; acc.balance += msg.value; if(now+_lockTime>acc.unlockTime)acc.unlockTime=now+_lockTime; Log.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; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Put(0); } } contract LogFile { 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 PENNY_BY_PENNY { struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Put(uint _lockTime) public payable { var acc = Acc[msg.sender]; acc.balance += msg.value; if(now+_lockTime>acc.unlockTime)acc.unlockTime=now+_lockTime; Log.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; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Put(0); } } contract LogFile { 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
0x561eac93c92360949ab1f1403323e6db345cbf31.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 54 */ pragma solidity ^0.4.19; contract BANK_SAFE { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { // <yes> <report> REENTRANCY if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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 BANK_SAFE { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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
0x23a91059fdc9579a9fbd0edc5f2ea0bfdb70deb4.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 _log) { 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) { 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 _log) { 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) { 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
0x4e73b32ed6c35f570686b89848e5f39f20ecc106.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 54 */ pragma solidity ^0.4.19; contract PRIVATE_ETH_CELL { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { require(!intitalized); MinSum = _val; } function SetLogFile(address _log) public { require(!intitalized); Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { // <yes> <report> REENTRANCY if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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 PRIVATE_ETH_CELL { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { require(!intitalized); MinSum = _val; } function SetLogFile(address _log) public { require(!intitalized); Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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_insecure.sol
/* * @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/ * @author: consensys * @vulnerable_at_lines: 17 */ pragma solidity ^0.5.0; contract Reentrancy_insecure { // INSECURE mapping (address => uint) private userBalances; 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 withdrawBalance again require(success); userBalances[msg.sender] = 0; } }
pragma solidity ^0.5.0; contract Reentrancy_insecure { mapping (address => uint) private userBalances; function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; (bool success, ) = msg.sender.call.value(amountToWithdraw)(""); require(success); userBalances[msg.sender] = 0; } }
reentrancy
etherbank.sol
/* * @source: https://github.com/seresistvanandras/EthBench/blob/master/Benchmark/Simple/reentrant.sol * @author: - * @vulnerable_at_lines: 21 */ pragma solidity ^0.4.0; contract EtherBank{ mapping (address => uint) userBalances; function getBalance(address user) constant returns(uint) { return userBalances[user]; } function addToBalance() { userBalances[msg.sender] += msg.value; } function withdrawBalance() { uint amountToWithdraw = userBalances[msg.sender]; // <yes> <report> REENTRANCY if (!(msg.sender.call.value(amountToWithdraw)())) { throw; } userBalances[msg.sender] = 0; } }
pragma solidity ^0.4.0; contract EtherBank{ mapping (address => uint) userBalances; function getBalance(address user) constant returns(uint) { return userBalances[user]; } function addToBalance() { userBalances[msg.sender] += msg.value; } function withdrawBalance() { uint amountToWithdraw = userBalances[msg.sender]; if (!(msg.sender.call.value(amountToWithdraw)())) { throw; } userBalances[msg.sender] = 0; } }
reentrancy
simple_dao.sol
/* * @source: http://blockchain.unica.it/projects/ethereum-survey/attacks.html#simpledao * @author: - * @vulnerable_at_lines: 19 */ pragma solidity ^0.4.2; contract SimpleDAO { mapping (address => uint) public credit; function donate(address to) payable { credit[to] += msg.value; } function withdraw(uint amount) { if (credit[msg.sender]>= amount) { // <yes> <report> REENTRANCY bool res = msg.sender.call.value(amount)(); credit[msg.sender]-=amount; } } function queryCredit(address to) returns (uint){ return credit[to]; } }
pragma solidity ^0.4.2; contract SimpleDAO { mapping (address => uint) public credit; function donate(address to) payable { credit[to] += msg.value; } function withdraw(uint amount) { if (credit[msg.sender]>= amount) { bool res = msg.sender.call.value(amount)(); credit[msg.sender]-=amount; } } function queryCredit(address to) returns (uint){ return credit[to]; } }
reentrancy
0xaae1f51cf3339f18b6d3f3bdc75a5facd744b0b8.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 54 */ pragma solidity ^0.4.19; contract DEP_BANK { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { // <yes> <report> REENTRANCY if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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 DEP_BANK { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Deposit(); } } contract LogFile { 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
0x93c32845fae42c83a70e5f06214c8433665c2ab5.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 29 */ pragma solidity ^0.4.25; contract X_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 X_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 X_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 X_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
0xf015c35649c82f5467c9c74b7f28ee67665aad68.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 29 */ pragma solidity ^0.4.25; contract MY_BANK { 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 MY_BANK(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 MY_BANK { 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 MY_BANK(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); } }
unchecked_low_level_calls
0xb11b2fed6c9354f7aa2f658d3b4d7b31d8a13b77.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 14 */ pragma solidity ^0.4.24; contract Proxy { modifier onlyOwner { if (msg.sender == Owner) _; } address Owner = msg.sender; function transferOwner(address _owner) public onlyOwner { Owner = _owner; } function proxy(address target, bytes data) public payable { // <yes> <report> UNCHECKED_LL_CALLS target.call.value(msg.value)(data); } } contract DepositProxy is Proxy { address public Owner; mapping (address => uint256) public Deposits; function () public payable { } function Vault() public payable { if (msg.sender == tx.origin) { Owner = msg.sender; deposit(); } } function deposit() public payable { if (msg.value > 0.5 ether) { Deposits[msg.sender] += msg.value; } } function withdraw(uint256 amount) public onlyOwner { if (amount>0 && Deposits[msg.sender]>=amount) { msg.sender.transfer(amount); } } }
pragma solidity ^0.4.24; contract Proxy { modifier onlyOwner { if (msg.sender == Owner) _; } address Owner = msg.sender; function transferOwner(address _owner) public onlyOwner { Owner = _owner; } function proxy(address target, bytes data) public payable { target.call.value(msg.value)(data); } } contract DepositProxy is Proxy { address public Owner; mapping (address => uint256) public Deposits; function () public payable { } function Vault() public payable { if (msg.sender == tx.origin) { Owner = msg.sender; deposit(); } } function deposit() public payable { if (msg.value > 0.5 ether) { Deposits[msg.sender] += msg.value; } } function withdraw(uint256 amount) public onlyOwner { if (amount>0 && Deposits[msg.sender]>=amount) { msg.sender.transfer(amount); } } }
unchecked_low_level_calls
0x78c2a1e91b52bca4130b6ed9edd9fbcfd4671c37.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 45 */ pragma solidity ^0.4.19; contract WhaleGiveaway1 { address public Owner = msg.sender; uint constant public minEligibility = 0.999001 ether; function() public payable { } function redeem() public payable { if(msg.value>=minEligibility) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract WhaleGiveaway1 { address public Owner = msg.sender; uint constant public minEligibility = 0.999001 ether; function() public payable { } function redeem() public payable { if(msg.value>=minEligibility) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
0x3a0e9acd953ffc0dd18d63603488846a6b8b2b01.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44,97 */ pragma solidity ^0.4.18; 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 { // <yes> <report> UNCHECKED_LL_CALLS 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[msg.sender]>0) { if(Holders[_addr]>=_wei) { // <yes> <report> UNCHECKED_LL_CALLS _addr.call.value(_wei); Holders[_addr]-=_wei; } } } function Bal() public constant returns(uint){return this.balance;} }
pragma solidity ^0.4.18; 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[msg.sender]>0) { if(Holders[_addr]>=_wei) { _addr.call.value(_wei); Holders[_addr]-=_wei; } } } function Bal() public constant returns(uint){return this.balance;} }
unchecked_low_level_calls
0x4051334adc52057aca763453820cb0e045076ef3.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 16 */ pragma solidity ^0.4.24; contract airdrop{ function transfer(address from,address caddress,address[] _tos,uint v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ // <yes> <report> UNCHECKED_LL_CALLS caddress.call(id,from,_tos[i],v); } return true; } }
pragma solidity ^0.4.24; contract airdrop{ function transfer(address from,address caddress,address[] _tos,uint v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ caddress.call(id,from,_tos[i],v); } return true; } }
unchecked_low_level_calls
0x7d09edb07d23acb532a82be3da5c17d9d85806b4.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 198,210 */ pragma solidity ^0.4.24; contract PoCGame { /** * Modifiers */ modifier onlyOwner() { require(msg.sender == owner); _; } modifier isOpenToPublic() { require(openToPublic); _; } modifier onlyRealPeople() { require (msg.sender == tx.origin); _; } modifier onlyPlayers() { require (wagers[msg.sender] > 0); _; } /** * Events */ event Wager(uint256 amount, address depositer); event Win(uint256 amount, address paidTo); event Lose(uint256 amount, address loser); event Donate(uint256 amount, address paidTo, address donator); event DifficultyChanged(uint256 currentDifficulty); event BetLimitChanged(uint256 currentBetLimit); /** * Global Variables */ address private whale; uint256 betLimit; uint difficulty; uint private randomSeed; address owner; mapping(address => uint256) timestamps; mapping(address => uint256) wagers; bool openToPublic; uint256 totalDonated; /** * Constructor */ constructor(address whaleAddress, uint256 wagerLimit) onlyRealPeople() public { openToPublic = false; owner = msg.sender; whale = whaleAddress; totalDonated = 0; betLimit = wagerLimit; } /** * Let the public play */ function OpenToThePublic() onlyOwner() public { openToPublic = true; } /** * Adjust the bet amounts */ function AdjustBetAmounts(uint256 amount) onlyOwner() public { betLimit = amount; emit BetLimitChanged(betLimit); } /** * Adjust the difficulty */ function AdjustDifficulty(uint256 amount) onlyOwner() public { difficulty = amount; emit DifficultyChanged(difficulty); } function() public payable { } /** * Wager your bet */ function wager() isOpenToPublic() onlyRealPeople() payable public { //You have to send exactly 0.01 ETH. require(msg.value == betLimit); //log the wager and timestamp(block number) timestamps[msg.sender] = block.number; wagers[msg.sender] = msg.value; emit Wager(msg.value, msg.sender); } /** * method to determine winners and losers */ function play() isOpenToPublic() onlyRealPeople() onlyPlayers() public { uint256 blockNumber = timestamps[msg.sender]; if(blockNumber < block.number) { timestamps[msg.sender] = 0; wagers[msg.sender] = 0; uint256 winningNumber = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), msg.sender)))%difficulty +1; if(winningNumber == difficulty / 2) { payout(msg.sender); } else { //player loses loseWager(betLimit / 2); } } else { revert(); } } /** * For those that just want to donate to the whale */ function donate() isOpenToPublic() public payable { donateToWhale(msg.value); } /** * Payout ETH to winner */ function payout(address winner) internal { uint256 ethToTransfer = address(this).balance / 2; winner.transfer(ethToTransfer); emit Win(ethToTransfer, winner); } /** * Payout ETH to whale */ function donateToWhale(uint256 amount) internal { // <yes> <report> UNCHECKED_LL_CALLS whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Donate(amount, whale, msg.sender); } /** * Payout ETH to whale when player loses */ function loseWager(uint256 amount) internal { // <yes> <report> UNCHECKED_LL_CALLS whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Lose(amount, msg.sender); } /** * ETH balance of contract */ function ethBalance() public view returns (uint256) { return address(this).balance; } /** * current difficulty of the game */ function currentDifficulty() public view returns (uint256) { return difficulty; } /** * current bet amount for the game */ function currentBetLimit() public view returns (uint256) { return betLimit; } function hasPlayerWagered(address player) public view returns (bool) { if(wagers[player] > 0) { return true; } else { return false; } } /** * For the UI to properly display the winner's pot */ function winnersPot() public view returns (uint256) { return address(this).balance / 2; } /** * A trap door for when someone sends tokens other than the intended ones so the overseers can decide where to send them. */ function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) public onlyOwner() returns (bool success) { return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); } } //Define ERC20Interface.transfer, so PoCWHALE can transfer tokens accidently sent to it. contract ERC20Interface { function transfer(address to, uint256 tokens) public returns (bool success); }
pragma solidity ^0.4.24; contract PoCGame { modifier onlyOwner() { require(msg.sender == owner); _; } modifier isOpenToPublic() { require(openToPublic); _; } modifier onlyRealPeople() { require (msg.sender == tx.origin); _; } modifier onlyPlayers() { require (wagers[msg.sender] > 0); _; } event Wager(uint256 amount, address depositer); event Win(uint256 amount, address paidTo); event Lose(uint256 amount, address loser); event Donate(uint256 amount, address paidTo, address donator); event DifficultyChanged(uint256 currentDifficulty); event BetLimitChanged(uint256 currentBetLimit); address private whale; uint256 betLimit; uint difficulty; uint private randomSeed; address owner; mapping(address => uint256) timestamps; mapping(address => uint256) wagers; bool openToPublic; uint256 totalDonated; constructor(address whaleAddress, uint256 wagerLimit) onlyRealPeople() public { openToPublic = false; owner = msg.sender; whale = whaleAddress; totalDonated = 0; betLimit = wagerLimit; } function OpenToThePublic() onlyOwner() public { openToPublic = true; } function AdjustBetAmounts(uint256 amount) onlyOwner() public { betLimit = amount; emit BetLimitChanged(betLimit); } function AdjustDifficulty(uint256 amount) onlyOwner() public { difficulty = amount; emit DifficultyChanged(difficulty); } function() public payable { } function wager() isOpenToPublic() onlyRealPeople() payable public { require(msg.value == betLimit); timestamps[msg.sender] = block.number; wagers[msg.sender] = msg.value; emit Wager(msg.value, msg.sender); } function play() isOpenToPublic() onlyRealPeople() onlyPlayers() public { uint256 blockNumber = timestamps[msg.sender]; if(blockNumber < block.number) { timestamps[msg.sender] = 0; wagers[msg.sender] = 0; uint256 winningNumber = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), msg.sender)))%difficulty +1; if(winningNumber == difficulty / 2) { payout(msg.sender); } else { loseWager(betLimit / 2); } } else { revert(); } } function donate() isOpenToPublic() public payable { donateToWhale(msg.value); } function payout(address winner) internal { uint256 ethToTransfer = address(this).balance / 2; winner.transfer(ethToTransfer); emit Win(ethToTransfer, winner); } function donateToWhale(uint256 amount) internal { whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Donate(amount, whale, msg.sender); } function loseWager(uint256 amount) internal { whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Lose(amount, msg.sender); } function ethBalance() public view returns (uint256) { return address(this).balance; } function currentDifficulty() public view returns (uint256) { return difficulty; } function currentBetLimit() public view returns (uint256) { return betLimit; } function hasPlayerWagered(address player) public view returns (bool) { if(wagers[player] > 0) { return true; } else { return false; } } function winnersPot() public view returns (uint256) { return address(this).balance / 2; } function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) public onlyOwner() returns (bool success) { return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); } } contract ERC20Interface { function transfer(address to, uint256 tokens) public returns (bool success); }
unchecked_low_level_calls
0x0cbe050f75bc8f8c2d6c0d249fea125fd6e1acc9.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 12 */ pragma solidity ^0.4.10; contract Caller { function callAddress(address a) { // <yes> <report> UNCHECKED_LL_CALLS a.call(); } }
pragma solidity ^0.4.10; contract Caller { function callAddress(address a) { a.call(); } }
unchecked_low_level_calls
0xa46edd6a9a93feec36576ee5048146870ea2c3ae.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 16 */ pragma solidity ^0.4.18; contract EBU{ function transfer(address from,address caddress,address[] _tos,uint[] v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ // <yes> <report> UNCHECKED_LL_CALLS caddress.call(id,from,_tos[i],v[i]); } return true; } }
pragma solidity ^0.4.18; contract EBU{ function transfer(address from,address caddress,address[] _tos,uint[] v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ caddress.call(id,from,_tos[i],v[i]); } return true; } }
unchecked_low_level_calls
0x52d2e0f9b01101a59b38a3d05c80b7618aeed984.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 27 */ pragma solidity ^0.4.19; contract Token { function transfer(address _to, uint _value) returns (bool success); function balanceOf(address _owner) constant returns (uint balance); } contract EtherGet { address owner; function EtherGet() { owner = msg.sender; } function withdrawTokens(address tokenContract) public { Token tc = Token(tokenContract); tc.transfer(owner, tc.balanceOf(this)); } function withdrawEther() public { owner.transfer(this.balance); } function getTokens(uint num, address addr) public { for(uint i = 0; i < num; i++){ // <yes> <report> UNCHECKED_LL_CALLS addr.call.value(0 wei)(); } } }
pragma solidity ^0.4.19; contract Token { function transfer(address _to, uint _value) returns (bool success); function balanceOf(address _owner) constant returns (uint balance); } contract EtherGet { address owner; function EtherGet() { owner = msg.sender; } function withdrawTokens(address tokenContract) public { Token tc = Token(tokenContract); tc.transfer(owner, tc.balanceOf(this)); } function withdrawEther() public { owner.transfer(this.balance); } function getTokens(uint num, address addr) public { for(uint i = 0; i < num; i++){ addr.call.value(0 wei)(); } } }
unchecked_low_level_calls
0x627fa62ccbb1c1b04ffaecd72a53e37fc0e17839.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44 */ 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 { // <yes> <report> UNCHECKED_LL_CALLS 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) { 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; } } } }
unchecked_low_level_calls
0x3e013fc32a54c4c5b6991ba539dcd0ec4355c859.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 29 */ pragma solidity ^0.4.18; contract MultiplicatorX4 { address public Owner = msg.sender; function() public payable{} function withdraw() payable public { require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } function multiplicate(address adr) public payable { if(msg.value>=this.balance) { adr.transfer(this.balance+msg.value); } } }
pragma solidity ^0.4.18; contract MultiplicatorX4 { address public Owner = msg.sender; function() public payable{} function withdraw() payable public { require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } function multiplicate(address adr) public payable { if(msg.value>=this.balance) { adr.transfer(this.balance+msg.value); } } }
unchecked_low_level_calls
0x19cf8481ea15427a98ba3cdd6d9e14690011ab10.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 439,465 */ //DAO Polska Token deployment pragma solidity ^0.4.11; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } // title Migration Agent interface contract MigrationAgent { function migrateFrom(address _from, uint256 _value); } contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMath { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; // what exaclt ether was sent mapping(address => uint) balancesRAW; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; /* Interface declaration */ function isToken() public constant returns (bool weAre) { return true; } function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } // daoPOLSKAtokens contract daoPOLSKAtokens{ string public name = "DAO POLSKA TOKEN version 1"; string public symbol = "DPL"; uint8 public constant decimals = 18; // 18 decimal places, the same as ETC/ETH/HEE. // Receives address public owner; address public migrationMaster; // The current total token supply. uint256 public otherchainstotalsupply =1.0 ether; uint256 public supplylimit = 10000.0 ether; //totalSupply uint256 public totalSupply = 0.0 ether; //chains: address public Chain1 = 0x0; address public Chain2 = 0x0; address public Chain3 = 0x0; address public Chain4 = 0x0; address public migrationAgent=0x8585D5A25b1FA2A0E6c3BcfC098195bac9789BE2; uint256 public totalMigrated; event Migrate(address indexed _from, address indexed _to, uint256 _value); event Refund(address indexed _from, uint256 _value); struct sendTokenAway{ StandardToken coinContract; uint amount; address recipient; } mapping(uint => sendTokenAway) transfers; uint numTransfers=0; mapping (address => uint256) balances; mapping (address => uint256) balancesRAW; mapping (address => mapping (address => uint256)) allowed; event UpdatedTokenInformation(string newName, string newSymbol); event Transfer(address indexed _from, address indexed _to, uint256 _value); event receivedEther(address indexed _from,uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); //tokenCreationCap bool public supplylimitset = false; bool public otherchainstotalset = false; function daoPOLSKAtokens() { owner=msg.sender; migrationMaster=msg.sender; } function setSupply(uint256 supplyLOCKER) public { if (msg.sender != owner) { throw; } if (supplylimitset != false) { throw; } supplylimitset = true; supplylimit = supplyLOCKER ** uint256(decimals); //balances[owner]=supplylimit; } function setotherchainstotalsupply(uint256 supplyLOCKER) public { if (msg.sender != owner) { throw; } if (supplylimitset != false) { throw; } otherchainstotalset = true; otherchainstotalsupply = supplyLOCKER ** uint256(decimals); } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { //if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function () payable public { if(funding){ receivedEther(msg.sender, msg.value); balances[msg.sender]=balances[msg.sender]+msg.value; } else throw; } function setTokenInformation(string _name, string _symbol) { if (msg.sender != owner) { throw; } name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } function setChainsAddresses(address chainAd, int chainnumber) { if (msg.sender != owner) { throw; } if(chainnumber==1){Chain1=chainAd;} if(chainnumber==2){Chain2=chainAd;} if(chainnumber==3){Chain3=chainAd;} if(chainnumber==4){Chain4=chainAd;} } function DAOPolskaTokenICOregulations() external returns(string wow) { return 'Regulations of preICO and ICO are present at website DAO Polska Token.network and by using this smartcontract and blockchains you commit that you accept and will follow those rules'; } // if accidentally other token was donated to Project Dev function sendTokenAw(address StandardTokenAddress, address receiver, uint amount){ if (msg.sender != owner) { throw; } sendTokenAway t = transfers[numTransfers]; t.coinContract = StandardToken(StandardTokenAddress); t.amount = amount; t.recipient = receiver; t.coinContract.transfer(receiver, amount); numTransfers++; } // Crowdfunding: uint public tokenCreationRate=1000; uint public bonusCreationRate=1000; uint public CreationRate=1761; uint256 public constant oneweek = 36000; uint256 public fundingEndBlock = 5433616; bool public funding = true; bool public refundstate = false; bool public migratestate= false; function createDaoPOLSKAtokens(address holder) payable { if (!funding) throw; // Do not allow creating 0 or more than the cap tokens. if (msg.value == 0) throw; // check the maximum token creation cap if (msg.value > (supplylimit - totalSupply) / CreationRate) throw; //bonus structure // in early stage there is about 100% more details in ico regulations on website // price and converstion rate in tabled to PLN not ether, and is updated daily var numTokensRAW = msg.value; var numTokens = msg.value * CreationRate; totalSupply += numTokens; // Assign new tokens to the sender balances[holder] += numTokens; balancesRAW[holder] += numTokensRAW; // Log token creation event Transfer(0, holder, numTokens); // Create additional Dao Tokens for the community and developers around 12% uint256 percentOfTotal = 12; uint256 additionalTokens = numTokens * percentOfTotal / (100); totalSupply += additionalTokens; balances[migrationMaster] += additionalTokens; Transfer(0, migrationMaster, additionalTokens); } function setBonusCreationRate(uint newRate){ if(msg.sender == owner) { bonusCreationRate=newRate; CreationRate=tokenCreationRate+bonusCreationRate; } } function FundsTransfer() external { if(funding==true) throw; if (!owner.send(this.balance)) throw; } function PartialFundsTransfer(uint SubX) external { if (msg.sender != owner) throw; // <yes> <report> UNCHECKED_LL_CALLS owner.send(this.balance - SubX); } function turnrefund() external { if (msg.sender != owner) throw; refundstate=!refundstate; } function fundingState() external { if (msg.sender != owner) throw; funding=!funding; } function turnmigrate() external { if (msg.sender != migrationMaster) throw; migratestate=!migratestate; } // notice Finalize crowdfunding clossing funding options function finalize() external { if (block.number <= fundingEndBlock+8*oneweek) throw; // Switch to Operational state. This is the only place this can happen. funding = false; refundstate=!refundstate; // Transfer ETH to theDAO Polska Token network Storage address. if (msg.sender==owner) // <yes> <report> UNCHECKED_LL_CALLS owner.send(this.balance); } function migrate(uint256 _value) external { // Abort if not in Operational Migration state. if (migratestate) throw; // Validate input value. if (_value == 0) throw; if (_value > balances[msg.sender]) throw; balances[msg.sender] -= _value; totalSupply -= _value; totalMigrated += _value; MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value); Migrate(msg.sender, migrationAgent, _value); } function refundTRA() external { // Abort if not in Funding Failure state. if (funding) throw; if (!refundstate) throw; var DAOPLTokenValue = balances[msg.sender]; var ETHValue = balancesRAW[msg.sender]; if (ETHValue == 0) throw; balancesRAW[msg.sender] = 0; totalSupply -= DAOPLTokenValue; Refund(msg.sender, ETHValue); msg.sender.transfer(ETHValue); } function preICOregulations() external returns(string wow) { return 'Regulations of preICO are present at website daopolska.pl and by using this smartcontract you commit that you accept and will follow those rules'; } } //------------------------------------------------------
pragma solidity ^0.4.11; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract MigrationAgent { function migrateFrom(address _from, uint256 _value); } contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract StandardToken is ERC20, SafeMath { event Minted(address receiver, uint amount); mapping(address => uint) balances; mapping(address => uint) balancesRAW; mapping (address => mapping (address => uint)) allowed; function isToken() public constant returns (bool weAre) { return true; } function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract daoPOLSKAtokens{ string public name = "DAO POLSKA TOKEN version 1"; string public symbol = "DPL"; uint8 public constant decimals = 18; address public owner; address public migrationMaster; uint256 public otherchainstotalsupply =1.0 ether; uint256 public supplylimit = 10000.0 ether; uint256 public totalSupply = 0.0 ether; address public Chain1 = 0x0; address public Chain2 = 0x0; address public Chain3 = 0x0; address public Chain4 = 0x0; address public migrationAgent=0x8585D5A25b1FA2A0E6c3BcfC098195bac9789BE2; uint256 public totalMigrated; event Migrate(address indexed _from, address indexed _to, uint256 _value); event Refund(address indexed _from, uint256 _value); struct sendTokenAway{ StandardToken coinContract; uint amount; address recipient; } mapping(uint => sendTokenAway) transfers; uint numTransfers=0; mapping (address => uint256) balances; mapping (address => uint256) balancesRAW; mapping (address => mapping (address => uint256)) allowed; event UpdatedTokenInformation(string newName, string newSymbol); event Transfer(address indexed _from, address indexed _to, uint256 _value); event receivedEther(address indexed _from,uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); bool public supplylimitset = false; bool public otherchainstotalset = false; function daoPOLSKAtokens() { owner=msg.sender; migrationMaster=msg.sender; } function setSupply(uint256 supplyLOCKER) public { if (msg.sender != owner) { throw; } if (supplylimitset != false) { throw; } supplylimitset = true; supplylimit = supplyLOCKER ** uint256(decimals); } function setotherchainstotalsupply(uint256 supplyLOCKER) public { if (msg.sender != owner) { throw; } if (supplylimitset != false) { throw; } otherchainstotalset = true; otherchainstotalsupply = supplyLOCKER ** uint256(decimals); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); balances[_from] -= _value; allowed[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function () payable public { if(funding){ receivedEther(msg.sender, msg.value); balances[msg.sender]=balances[msg.sender]+msg.value; } else throw; } function setTokenInformation(string _name, string _symbol) { if (msg.sender != owner) { throw; } name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } function setChainsAddresses(address chainAd, int chainnumber) { if (msg.sender != owner) { throw; } if(chainnumber==1){Chain1=chainAd;} if(chainnumber==2){Chain2=chainAd;} if(chainnumber==3){Chain3=chainAd;} if(chainnumber==4){Chain4=chainAd;} } function DAOPolskaTokenICOregulations() external returns(string wow) { return 'Regulations of preICO and ICO are present at website DAO Polska Token.network and by using this smartcontract and blockchains you commit that you accept and will follow those rules'; } function sendTokenAw(address StandardTokenAddress, address receiver, uint amount){ if (msg.sender != owner) { throw; } sendTokenAway t = transfers[numTransfers]; t.coinContract = StandardToken(StandardTokenAddress); t.amount = amount; t.recipient = receiver; t.coinContract.transfer(receiver, amount); numTransfers++; } uint public tokenCreationRate=1000; uint public bonusCreationRate=1000; uint public CreationRate=1761; uint256 public constant oneweek = 36000; uint256 public fundingEndBlock = 5433616; bool public funding = true; bool public refundstate = false; bool public migratestate= false; function createDaoPOLSKAtokens(address holder) payable { if (!funding) throw; if (msg.value == 0) throw; if (msg.value > (supplylimit - totalSupply) / CreationRate) throw; var numTokensRAW = msg.value; var numTokens = msg.value * CreationRate; totalSupply += numTokens; balances[holder] += numTokens; balancesRAW[holder] += numTokensRAW; Transfer(0, holder, numTokens); uint256 percentOfTotal = 12; uint256 additionalTokens = numTokens * percentOfTotal / (100); totalSupply += additionalTokens; balances[migrationMaster] += additionalTokens; Transfer(0, migrationMaster, additionalTokens); } function setBonusCreationRate(uint newRate){ if(msg.sender == owner) { bonusCreationRate=newRate; CreationRate=tokenCreationRate+bonusCreationRate; } } function FundsTransfer() external { if(funding==true) throw; if (!owner.send(this.balance)) throw; } function PartialFundsTransfer(uint SubX) external { if (msg.sender != owner) throw; owner.send(this.balance - SubX); } function turnrefund() external { if (msg.sender != owner) throw; refundstate=!refundstate; } function fundingState() external { if (msg.sender != owner) throw; funding=!funding; } function turnmigrate() external { if (msg.sender != migrationMaster) throw; migratestate=!migratestate; } function finalize() external { if (block.number <= fundingEndBlock+8*oneweek) throw; funding = false; refundstate=!refundstate; if (msg.sender==owner) owner.send(this.balance); } function migrate(uint256 _value) external { if (migratestate) throw; if (_value == 0) throw; if (_value > balances[msg.sender]) throw; balances[msg.sender] -= _value; totalSupply -= _value; totalMigrated += _value; MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value); Migrate(msg.sender, migrationAgent, _value); } function refundTRA() external { if (funding) throw; if (!refundstate) throw; var DAOPLTokenValue = balances[msg.sender]; var ETHValue = balancesRAW[msg.sender]; if (ETHValue == 0) throw; balancesRAW[msg.sender] = 0; totalSupply -= DAOPLTokenValue; Refund(msg.sender, ETHValue); msg.sender.transfer(ETHValue); } function preICOregulations() external returns(string wow) { return 'Regulations of preICO are present at website daopolska.pl and by using this smartcontract you commit that you accept and will follow those rules'; } }
unchecked_low_level_calls
0x4b71ad9c1a84b9b643aa54fdd66e2dec96e8b152.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 17 */ pragma solidity ^0.4.24; contract airPort{ function transfer(address from,address caddress,address[] _tos,uint v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ // <yes> <report> UNCHECKED_LL_CALLS caddress.call(id,from,_tos[i],v); } return true; } }
pragma solidity ^0.4.24; contract airPort{ function transfer(address from,address caddress,address[] _tos,uint v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ caddress.call(id,from,_tos[i],v); } return true; } }
unchecked_low_level_calls
0xe09b1ab8111c2729a76f16de96bc86a7af837928.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 150 */ pragma solidity ^0.4.24; /* This is fiftyflip a simple yet elegant game contract that is connected to Proof of Community contract(0x1739e311ddBf1efdFbc39b74526Fd8b600755ADa). Greed serves no-one but the one, But charity is kind, suffereth not and envieth not. Charity is to give of oneself in the service of his fellow beings. Play on Players. and Remember fifty feeds the multiudes and gives to the PoC community Forever and ever. */ contract FiftyFlip { uint constant DONATING_X = 20; // 2% kujira // Need to be discussed uint constant JACKPOT_FEE = 10; // 1% jackpot uint constant JACKPOT_MODULO = 1000; // 0.1% jackpotwin uint constant DEV_FEE = 20; // 2% devfee uint constant WIN_X = 1900; // 1.9x // There is minimum and maximum bets. uint constant MIN_BET = 0.01 ether; uint constant MAX_BET = 1 ether; uint constant BET_EXPIRATION_BLOCKS = 250; // owner and PoC contract address address public owner; address public autoPlayBot; address public secretSigner; address private whale; // Accumulated jackpot fund. uint256 public jackpotSize; uint256 public devFeeSize; // Funds that are locked in potentially winning bets. uint256 public lockedInBets; uint256 public totalAmountToWhale; struct Bet { // Wager amount in wei. uint amount; // Block number of placeBet tx. uint256 blockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). bool betMask; // Address of a player, used to pay out winning bets. address player; } mapping (uint => Bet) bets; mapping (address => uint) donateAmount; // events event Wager(uint ticketID, uint betAmount, uint256 betBlockNumber, bool betMask, address betPlayer); event Win(address winner, uint amount, uint ticketID, bool maskRes, uint jackpotRes); event Lose(address loser, uint amount, uint ticketID, bool maskRes, uint jackpotRes); event Refund(uint ticketID, uint256 amount, address requester); event Donate(uint256 amount, address donator); event FailedPayment(address paidUser, uint amount); event Payment(address noPaidUser, uint amount); event JackpotPayment(address player, uint ticketID, uint jackpotWin); // constructor constructor (address whaleAddress, address autoPlayBotAddress, address secretSignerAddress) public { owner = msg.sender; autoPlayBot = autoPlayBotAddress; whale = whaleAddress; secretSigner = secretSignerAddress; jackpotSize = 0; devFeeSize = 0; lockedInBets = 0; totalAmountToWhale = 0; } // modifiers modifier onlyOwner() { require (msg.sender == owner, "You are not the owner of this contract!"); _; } modifier onlyBot() { require (msg.sender == autoPlayBot, "You are not the bot of this contract!"); _; } modifier checkContractHealth() { require (address(this).balance >= lockedInBets + jackpotSize + devFeeSize, "This contract doesn't have enough balance, it is stopped till someone donate to this game!"); _; } // betMast: // false is front, true is back function() public payable { } function setBotAddress(address autoPlayBotAddress) onlyOwner() external { autoPlayBot = autoPlayBotAddress; } function setSecretSigner(address _secretSigner) onlyOwner() external { secretSigner = _secretSigner; } // wager function function wager(bool bMask, uint ticketID, uint ticketLastBlock, uint8 v, bytes32 r, bytes32 s) checkContractHealth() external payable { Bet storage bet = bets[ticketID]; uint amount = msg.value; address player = msg.sender; require (bet.player == address(0), "Ticket is not new one!"); require (amount >= MIN_BET, "Your bet is lower than minimum bet amount"); require (amount <= MAX_BET, "Your bet is higher than maximum bet amount"); require (getCollateralBalance() >= 2 * amount, "If we accept this, this contract will be in danger!"); require (block.number <= ticketLastBlock, "Ticket has expired."); bytes32 signatureHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n37', uint40(ticketLastBlock), ticketID)); require (secretSigner == ecrecover(signatureHash, v, r, s), "web3 vrs signature is not valid."); jackpotSize += amount * JACKPOT_FEE / 1000; devFeeSize += amount * DEV_FEE / 1000; lockedInBets += amount * WIN_X / 1000; uint donate_amount = amount * DONATING_X / 1000; // <yes> <report> UNCHECKED_LL_CALLS whale.call.value(donate_amount)(bytes4(keccak256("donate()"))); totalAmountToWhale += donate_amount; bet.amount = amount; bet.blockNumber = block.number; bet.betMask = bMask; bet.player = player; emit Wager(ticketID, bet.amount, bet.blockNumber, bet.betMask, bet.player); } // method to determine winners and losers function play(uint ticketReveal) checkContractHealth() external { uint ticketID = uint(keccak256(abi.encodePacked(ticketReveal))); Bet storage bet = bets[ticketID]; require (bet.player != address(0), "TicketID is not correct!"); require (bet.amount != 0, "Ticket is already used one!"); uint256 blockNumber = bet.blockNumber; if(blockNumber < block.number && blockNumber >= block.number - BET_EXPIRATION_BLOCKS) { uint256 random = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), ticketReveal))); bool maskRes = (random % 2) !=0; uint jackpotRes = random % JACKPOT_MODULO; uint tossWinAmount = bet.amount * WIN_X / 1000; uint tossWin = 0; uint jackpotWin = 0; if(bet.betMask == maskRes) { tossWin = tossWinAmount; } if(jackpotRes == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } if (jackpotWin > 0) { emit JackpotPayment(bet.player, ticketID, jackpotWin); } if(tossWin + jackpotWin > 0) { payout(bet.player, tossWin + jackpotWin, ticketID, maskRes, jackpotRes); } else { loseWager(bet.player, bet.amount, ticketID, maskRes, jackpotRes); } lockedInBets -= tossWinAmount; bet.amount = 0; } else { revert(); } } function donateForContractHealth() external payable { donateAmount[msg.sender] += msg.value; emit Donate(msg.value, msg.sender); } function withdrawDonation(uint amount) external { require(donateAmount[msg.sender] >= amount, "You are going to withdraw more than you donated!"); if (sendFunds(msg.sender, amount)){ donateAmount[msg.sender] -= amount; } } // method to refund function refund(uint ticketID) checkContractHealth() external { Bet storage bet = bets[ticketID]; require (bet.amount != 0, "this ticket has no balance"); require (block.number > bet.blockNumber + BET_EXPIRATION_BLOCKS, "this ticket is expired."); sendRefund(ticketID); } // Funds withdrawl function withdrawDevFee(address withdrawAddress, uint withdrawAmount) onlyOwner() checkContractHealth() external { require (devFeeSize >= withdrawAmount, "You are trying to withdraw more amount than developer fee."); require (withdrawAmount <= address(this).balance, "Contract balance is lower than withdrawAmount"); require (devFeeSize <= address(this).balance, "Not enough funds to withdraw."); if (sendFunds(withdrawAddress, withdrawAmount)){ devFeeSize -= withdrawAmount; } } // Funds withdrawl function withdrawBotFee(uint withdrawAmount) onlyBot() checkContractHealth() external { require (devFeeSize >= withdrawAmount, "You are trying to withdraw more amount than developer fee."); require (withdrawAmount <= address(this).balance, "Contract balance is lower than withdrawAmount"); require (devFeeSize <= address(this).balance, "Not enough funds to withdraw."); if (sendFunds(autoPlayBot, withdrawAmount)){ devFeeSize -= withdrawAmount; } } // Get Bet Info from id function getBetInfo(uint ticketID) constant external returns (uint, uint256, bool, address){ Bet storage bet = bets[ticketID]; return (bet.amount, bet.blockNumber, bet.betMask, bet.player); } // Get Bet Info from id function getContractBalance() constant external returns (uint){ return address(this).balance; } // Get Collateral for Bet function getCollateralBalance() constant public returns (uint){ if (address(this).balance > lockedInBets + jackpotSize + devFeeSize) return address(this).balance - lockedInBets - jackpotSize - devFeeSize; return 0; } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner() { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } // Payout ETH to winner function payout(address winner, uint ethToTransfer, uint ticketID, bool maskRes, uint jackpotRes) internal { winner.transfer(ethToTransfer); emit Win(winner, ethToTransfer, ticketID, maskRes, jackpotRes); } // sendRefund to requester function sendRefund(uint ticketID) internal { Bet storage bet = bets[ticketID]; address requester = bet.player; uint256 ethToTransfer = bet.amount; requester.transfer(ethToTransfer); uint tossWinAmount = bet.amount * WIN_X / 1000; lockedInBets -= tossWinAmount; bet.amount = 0; emit Refund(ticketID, ethToTransfer, requester); } // Helper routine to process the payment. function sendFunds(address paidUser, uint amount) private returns (bool){ bool success = paidUser.send(amount); if (success) { emit Payment(paidUser, amount); } else { emit FailedPayment(paidUser, amount); } return success; } // Payout ETH to whale when player loses function loseWager(address player, uint amount, uint ticketID, bool maskRes, uint jackpotRes) internal { emit Lose(player, amount, ticketID, maskRes, jackpotRes); } // bulk clean the storage. function clearStorage(uint[] toCleanTicketIDs) external { uint length = toCleanTicketIDs.length; for (uint i = 0; i < length; i++) { clearProcessedBet(toCleanTicketIDs[i]); } } // Helper routine to move 'processed' bets into 'clean' state. function clearProcessedBet(uint ticketID) private { Bet storage bet = bets[ticketID]; // Do not overwrite active bets with zeros; additionally prevent cleanup of bets // for which ticketID signatures may have not expired yet (see whitepaper for details). if (bet.amount != 0 || block.number <= bet.blockNumber + BET_EXPIRATION_BLOCKS) { return; } bet.blockNumber = 0; bet.betMask = false; bet.player = address(0); } // A trap door for when someone sends tokens other than the intended ones so the overseers can decide where to send them. function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) public onlyOwner() returns (bool success) { return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); } } //Define ERC20Interface.transfer, so PoCWHALE can transfer tokens accidently sent to it. contract ERC20Interface { function transfer(address to, uint256 tokens) public returns (bool success); }
pragma solidity ^0.4.24; contract FiftyFlip { uint constant DONATING_X = 20; uint constant JACKPOT_FEE = 10; uint constant JACKPOT_MODULO = 1000; uint constant DEV_FEE = 20; uint constant WIN_X = 1900; uint constant MIN_BET = 0.01 ether; uint constant MAX_BET = 1 ether; uint constant BET_EXPIRATION_BLOCKS = 250; address public owner; address public autoPlayBot; address public secretSigner; address private whale; uint256 public jackpotSize; uint256 public devFeeSize; uint256 public lockedInBets; uint256 public totalAmountToWhale; struct Bet { uint amount; uint256 blockNumber; bool betMask; address player; } mapping (uint => Bet) bets; mapping (address => uint) donateAmount; event Wager(uint ticketID, uint betAmount, uint256 betBlockNumber, bool betMask, address betPlayer); event Win(address winner, uint amount, uint ticketID, bool maskRes, uint jackpotRes); event Lose(address loser, uint amount, uint ticketID, bool maskRes, uint jackpotRes); event Refund(uint ticketID, uint256 amount, address requester); event Donate(uint256 amount, address donator); event FailedPayment(address paidUser, uint amount); event Payment(address noPaidUser, uint amount); event JackpotPayment(address player, uint ticketID, uint jackpotWin); constructor (address whaleAddress, address autoPlayBotAddress, address secretSignerAddress) public { owner = msg.sender; autoPlayBot = autoPlayBotAddress; whale = whaleAddress; secretSigner = secretSignerAddress; jackpotSize = 0; devFeeSize = 0; lockedInBets = 0; totalAmountToWhale = 0; } modifier onlyOwner() { require (msg.sender == owner, "You are not the owner of this contract!"); _; } modifier onlyBot() { require (msg.sender == autoPlayBot, "You are not the bot of this contract!"); _; } modifier checkContractHealth() { require (address(this).balance >= lockedInBets + jackpotSize + devFeeSize, "This contract doesn't have enough balance, it is stopped till someone donate to this game!"); _; } function() public payable { } function setBotAddress(address autoPlayBotAddress) onlyOwner() external { autoPlayBot = autoPlayBotAddress; } function setSecretSigner(address _secretSigner) onlyOwner() external { secretSigner = _secretSigner; } function wager(bool bMask, uint ticketID, uint ticketLastBlock, uint8 v, bytes32 r, bytes32 s) checkContractHealth() external payable { Bet storage bet = bets[ticketID]; uint amount = msg.value; address player = msg.sender; require (bet.player == address(0), "Ticket is not new one!"); require (amount >= MIN_BET, "Your bet is lower than minimum bet amount"); require (amount <= MAX_BET, "Your bet is higher than maximum bet amount"); require (getCollateralBalance() >= 2 * amount, "If we accept this, this contract will be in danger!"); require (block.number <= ticketLastBlock, "Ticket has expired."); bytes32 signatureHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n37', uint40(ticketLastBlock), ticketID)); require (secretSigner == ecrecover(signatureHash, v, r, s), "web3 vrs signature is not valid."); jackpotSize += amount * JACKPOT_FEE / 1000; devFeeSize += amount * DEV_FEE / 1000; lockedInBets += amount * WIN_X / 1000; uint donate_amount = amount * DONATING_X / 1000; whale.call.value(donate_amount)(bytes4(keccak256("donate()"))); totalAmountToWhale += donate_amount; bet.amount = amount; bet.blockNumber = block.number; bet.betMask = bMask; bet.player = player; emit Wager(ticketID, bet.amount, bet.blockNumber, bet.betMask, bet.player); } function play(uint ticketReveal) checkContractHealth() external { uint ticketID = uint(keccak256(abi.encodePacked(ticketReveal))); Bet storage bet = bets[ticketID]; require (bet.player != address(0), "TicketID is not correct!"); require (bet.amount != 0, "Ticket is already used one!"); uint256 blockNumber = bet.blockNumber; if(blockNumber < block.number && blockNumber >= block.number - BET_EXPIRATION_BLOCKS) { uint256 random = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), ticketReveal))); bool maskRes = (random % 2) !=0; uint jackpotRes = random % JACKPOT_MODULO; uint tossWinAmount = bet.amount * WIN_X / 1000; uint tossWin = 0; uint jackpotWin = 0; if(bet.betMask == maskRes) { tossWin = tossWinAmount; } if(jackpotRes == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } if (jackpotWin > 0) { emit JackpotPayment(bet.player, ticketID, jackpotWin); } if(tossWin + jackpotWin > 0) { payout(bet.player, tossWin + jackpotWin, ticketID, maskRes, jackpotRes); } else { loseWager(bet.player, bet.amount, ticketID, maskRes, jackpotRes); } lockedInBets -= tossWinAmount; bet.amount = 0; } else { revert(); } } function donateForContractHealth() external payable { donateAmount[msg.sender] += msg.value; emit Donate(msg.value, msg.sender); } function withdrawDonation(uint amount) external { require(donateAmount[msg.sender] >= amount, "You are going to withdraw more than you donated!"); if (sendFunds(msg.sender, amount)){ donateAmount[msg.sender] -= amount; } } function refund(uint ticketID) checkContractHealth() external { Bet storage bet = bets[ticketID]; require (bet.amount != 0, "this ticket has no balance"); require (block.number > bet.blockNumber + BET_EXPIRATION_BLOCKS, "this ticket is expired."); sendRefund(ticketID); } function withdrawDevFee(address withdrawAddress, uint withdrawAmount) onlyOwner() checkContractHealth() external { require (devFeeSize >= withdrawAmount, "You are trying to withdraw more amount than developer fee."); require (withdrawAmount <= address(this).balance, "Contract balance is lower than withdrawAmount"); require (devFeeSize <= address(this).balance, "Not enough funds to withdraw."); if (sendFunds(withdrawAddress, withdrawAmount)){ devFeeSize -= withdrawAmount; } } function withdrawBotFee(uint withdrawAmount) onlyBot() checkContractHealth() external { require (devFeeSize >= withdrawAmount, "You are trying to withdraw more amount than developer fee."); require (withdrawAmount <= address(this).balance, "Contract balance is lower than withdrawAmount"); require (devFeeSize <= address(this).balance, "Not enough funds to withdraw."); if (sendFunds(autoPlayBot, withdrawAmount)){ devFeeSize -= withdrawAmount; } } function getBetInfo(uint ticketID) constant external returns (uint, uint256, bool, address){ Bet storage bet = bets[ticketID]; return (bet.amount, bet.blockNumber, bet.betMask, bet.player); } function getContractBalance() constant external returns (uint){ return address(this).balance; } function getCollateralBalance() constant public returns (uint){ if (address(this).balance > lockedInBets + jackpotSize + devFeeSize) return address(this).balance - lockedInBets - jackpotSize - devFeeSize; return 0; } function kill() external onlyOwner() { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } function payout(address winner, uint ethToTransfer, uint ticketID, bool maskRes, uint jackpotRes) internal { winner.transfer(ethToTransfer); emit Win(winner, ethToTransfer, ticketID, maskRes, jackpotRes); } function sendRefund(uint ticketID) internal { Bet storage bet = bets[ticketID]; address requester = bet.player; uint256 ethToTransfer = bet.amount; requester.transfer(ethToTransfer); uint tossWinAmount = bet.amount * WIN_X / 1000; lockedInBets -= tossWinAmount; bet.amount = 0; emit Refund(ticketID, ethToTransfer, requester); } function sendFunds(address paidUser, uint amount) private returns (bool){ bool success = paidUser.send(amount); if (success) { emit Payment(paidUser, amount); } else { emit FailedPayment(paidUser, amount); } return success; } function loseWager(address player, uint amount, uint ticketID, bool maskRes, uint jackpotRes) internal { emit Lose(player, amount, ticketID, maskRes, jackpotRes); } function clearStorage(uint[] toCleanTicketIDs) external { uint length = toCleanTicketIDs.length; for (uint i = 0; i < length; i++) { clearProcessedBet(toCleanTicketIDs[i]); } } function clearProcessedBet(uint ticketID) private { Bet storage bet = bets[ticketID]; if (bet.amount != 0 || block.number <= bet.blockNumber + BET_EXPIRATION_BLOCKS) { return; } bet.blockNumber = 0; bet.betMask = false; bet.player = address(0); } function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) public onlyOwner() returns (bool success) { return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); } } contract ERC20Interface { function transfer(address to, uint256 tokens) public returns (bool success); }
unchecked_low_level_calls
0x84d9ec85c9c568eb332b7226a8f826d897e0a4a8.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 56 */ pragma solidity ^0.4.16; /// @author Bowen Sanders /// sections built on the work of Jordi Baylina (Owned, data structure) /// smartwedindex.sol contains a simple index of contract address, couple name, actual marriage date, bool displayValues to /// be used to create an array of all SmartWed contracts that are deployed /// contract 0wned is licesned under GNU-3 /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed contract Owned { /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require(msg.sender == owner); _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Owned() { owner = msg.sender; } address public newOwner; /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } /// @notice `newOwner` has to accept the ownership before it is transferred /// Any account or any contract with the ability to call `acceptOwnership` /// can be used to accept ownership of this contract, including a contract /// with no other functions function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } // This is a general safty function that allows the owner to do a lot // of things in the unlikely event that something goes wrong // _dst is the contract being called making this like a 1/1 multisig function execute(address _dst, uint _value, bytes _data) onlyOwner { // <yes> <report> UNCHECKED_LL_CALLS _dst.call.value(_value)(_data); } } // contract WedIndex contract WedIndex is Owned { // declare index data variables string public wedaddress; string public partnernames; uint public indexdate; uint public weddingdate; uint public displaymultisig; IndexArray[] public indexarray; struct IndexArray { uint indexdate; string wedaddress; string partnernames; uint weddingdate; uint displaymultisig; } function numberOfIndex() constant public returns (uint) { return indexarray.length; } // make functions to write and read index entries and nubmer of entries function writeIndex(uint indexdate, string wedaddress, string partnernames, uint weddingdate, uint displaymultisig) { indexarray.push(IndexArray(now, wedaddress, partnernames, weddingdate, displaymultisig)); IndexWritten(now, wedaddress, partnernames, weddingdate, displaymultisig); } // declare events event IndexWritten (uint time, string contractaddress, string partners, uint weddingdate, uint display); }
pragma solidity ^0.4.16; contract Owned { modifier onlyOwner() { require(msg.sender == owner); _; } address public owner; function Owned() { owner = msg.sender; } address public newOwner; function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } function execute(address _dst, uint _value, bytes _data) onlyOwner { _dst.call.value(_value)(_data); } } contract WedIndex is Owned { string public wedaddress; string public partnernames; uint public indexdate; uint public weddingdate; uint public displaymultisig; IndexArray[] public indexarray; struct IndexArray { uint indexdate; string wedaddress; string partnernames; uint weddingdate; uint displaymultisig; } function numberOfIndex() constant public returns (uint) { return indexarray.length; } function writeIndex(uint indexdate, string wedaddress, string partnernames, uint weddingdate, uint displaymultisig) { indexarray.push(IndexArray(now, wedaddress, partnernames, weddingdate, displaymultisig)); IndexWritten(now, wedaddress, partnernames, weddingdate, displaymultisig); } event IndexWritten (uint time, string contractaddress, string partners, uint weddingdate, uint display); }
unchecked_low_level_calls
0x524960d55174d912768678d8c606b4d50b79d7b1.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 21 */ pragma solidity ^0.4.13; contract Centra4 { function transfer() returns (bool) { address contract_address; contract_address = 0x96a65609a7b84e8842732deb08f56c3e21ac6f8a; address c1; address c2; uint256 k; k = 1; c2 = 0xaa27f8c1160886aacba64b2319d8d5469ef2af79; // <yes> <report> UNCHECKED_LL_CALLS contract_address.call("register", "CentraToken"); if(!contract_address.call(bytes4(keccak256("transfer(address,uint256)")),c2,k)) return false; return true; } }
pragma solidity ^0.4.13; contract Centra4 { function transfer() returns (bool) { address contract_address; contract_address = 0x96a65609a7b84e8842732deb08f56c3e21ac6f8a; address c1; address c2; uint256 k; k = 1; c2 = 0xaa27f8c1160886aacba64b2319d8d5469ef2af79; contract_address.call("register", "CentraToken"); if(!contract_address.call(bytes4(keccak256("transfer(address,uint256)")),c2,k)) return false; return true; } }
unchecked_low_level_calls
etherpot_lotto.sol
/* * @source: https://github.com/etherpot/contract/blob/master/app/contracts/lotto.sol * @author: - * @vulnerable_at_lines: 109,141 */ //added pragma version pragma solidity ^0.4.0; contract Lotto { uint constant public blocksPerRound = 6800; // there are an infinite number of rounds (just like a real lottery that takes place every week). `blocksPerRound` decides how many blocks each round will last. 6800 is around a day. uint constant public ticketPrice = 100000000000000000; // the cost of each ticket is .1 ether. uint constant public blockReward = 5000000000000000000; function getBlocksPerRound() constant returns(uint){ return blocksPerRound; } function getTicketPrice() constant returns(uint){ return ticketPrice; } //accessors for constants struct Round { address[] buyers; uint pot; uint ticketsCount; mapping(uint=>bool) isCashed; mapping(address=>uint) ticketsCountByBuyer; } mapping(uint => Round) rounds; //the contract maintains a mapping of rounds. Each round maintains a list of tickets, the total amount of the pot, and whether or not the round was "cashed". "Cashing" is the act of paying out the pot to the winner. function getRoundIndex() constant returns (uint){ //The round index tells us which round we're on. For example if we're on block 24, we're on round 2. Division in Solidity automatically rounds down, so we don't need to worry about decimals. return block.number/blocksPerRound; } function getIsCashed(uint roundIndex,uint subpotIndex) constant returns (bool){ //Determine if a given. return rounds[roundIndex].isCashed[subpotIndex]; } function calculateWinner(uint roundIndex, uint subpotIndex) constant returns(address){ //note this function only calculates the winners. It does not do any state changes and therefore does not include various validitiy checks var decisionBlockNumber = getDecisionBlockNumber(roundIndex,subpotIndex); if(decisionBlockNumber>block.number) return; //We can't decided the winner if the round isn't over yet var decisionBlockHash = getHashOfBlock(decisionBlockNumber); var winningTicketIndex = decisionBlockHash%rounds[roundIndex].ticketsCount; //We perform a modulus of the blockhash to determine the winner var ticketIndex = uint256(0); for(var buyerIndex = 0; buyerIndex<rounds[roundIndex].buyers.length; buyerIndex++){ var buyer = rounds[roundIndex].buyers[buyerIndex]; ticketIndex+=rounds[roundIndex].ticketsCountByBuyer[buyer]; if(ticketIndex>winningTicketIndex){ return buyer; } } } function getDecisionBlockNumber(uint roundIndex,uint subpotIndex) constant returns (uint){ return ((roundIndex+1)*blocksPerRound)+subpotIndex; } function getSubpotsCount(uint roundIndex) constant returns(uint){ var subpotsCount = rounds[roundIndex].pot/blockReward; if(rounds[roundIndex].pot%blockReward>0) subpotsCount++; return subpotsCount; } function getSubpot(uint roundIndex) constant returns(uint){ return rounds[roundIndex].pot/getSubpotsCount(roundIndex); } function cash(uint roundIndex, uint subpotIndex){ var subpotsCount = getSubpotsCount(roundIndex); if(subpotIndex>=subpotsCount) return; var decisionBlockNumber = getDecisionBlockNumber(roundIndex,subpotIndex); if(decisionBlockNumber>block.number) return; if(rounds[roundIndex].isCashed[subpotIndex]) return; //Subpots can only be cashed once. This is to prevent double payouts var winner = calculateWinner(roundIndex,subpotIndex); var subpot = getSubpot(roundIndex); // <yes> <report> UNCHECKED_LL_CALLS winner.send(subpot); rounds[roundIndex].isCashed[subpotIndex] = true; //Mark the round as cashed } function getHashOfBlock(uint blockIndex) constant returns(uint){ return uint(block.blockhash(blockIndex)); } function getBuyers(uint roundIndex,address buyer) constant returns (address[]){ return rounds[roundIndex].buyers; } function getTicketsCountByBuyer(uint roundIndex,address buyer) constant returns (uint){ return rounds[roundIndex].ticketsCountByBuyer[buyer]; } function getPot(uint roundIndex) constant returns(uint){ return rounds[roundIndex].pot; } function() { //this is the function that gets called when people send money to the contract. var roundIndex = getRoundIndex(); var value = msg.value-(msg.value%ticketPrice); if(value==0) return; if(value<msg.value){ // <yes> <report> UNCHECKED_LL_CALLS msg.sender.send(msg.value-value); } //no partial tickets, send a partial refund var ticketsCount = value/ticketPrice; rounds[roundIndex].ticketsCount+=ticketsCount; if(rounds[roundIndex].ticketsCountByBuyer[msg.sender]==0){ var buyersLength = rounds[roundIndex].buyers.length++; rounds[roundIndex].buyers[buyersLength] = msg.sender; } rounds[roundIndex].ticketsCountByBuyer[msg.sender]+=ticketsCount; rounds[roundIndex].ticketsCount+=ticketsCount; //keep track of the total tickets rounds[roundIndex].pot+=value; //keep track of the total pot } }
pragma solidity ^0.4.0; contract Lotto { uint constant public blocksPerRound = 6800; uint constant public ticketPrice = 100000000000000000; uint constant public blockReward = 5000000000000000000; function getBlocksPerRound() constant returns(uint){ return blocksPerRound; } function getTicketPrice() constant returns(uint){ return ticketPrice; } struct Round { address[] buyers; uint pot; uint ticketsCount; mapping(uint=>bool) isCashed; mapping(address=>uint) ticketsCountByBuyer; } mapping(uint => Round) rounds; function getRoundIndex() constant returns (uint){ return block.number/blocksPerRound; } function getIsCashed(uint roundIndex,uint subpotIndex) constant returns (bool){ return rounds[roundIndex].isCashed[subpotIndex]; } function calculateWinner(uint roundIndex, uint subpotIndex) constant returns(address){ var decisionBlockNumber = getDecisionBlockNumber(roundIndex,subpotIndex); if(decisionBlockNumber>block.number) return; var decisionBlockHash = getHashOfBlock(decisionBlockNumber); var winningTicketIndex = decisionBlockHash%rounds[roundIndex].ticketsCount; var ticketIndex = uint256(0); for(var buyerIndex = 0; buyerIndex<rounds[roundIndex].buyers.length; buyerIndex++){ var buyer = rounds[roundIndex].buyers[buyerIndex]; ticketIndex+=rounds[roundIndex].ticketsCountByBuyer[buyer]; if(ticketIndex>winningTicketIndex){ return buyer; } } } function getDecisionBlockNumber(uint roundIndex,uint subpotIndex) constant returns (uint){ return ((roundIndex+1)*blocksPerRound)+subpotIndex; } function getSubpotsCount(uint roundIndex) constant returns(uint){ var subpotsCount = rounds[roundIndex].pot/blockReward; if(rounds[roundIndex].pot%blockReward>0) subpotsCount++; return subpotsCount; } function getSubpot(uint roundIndex) constant returns(uint){ return rounds[roundIndex].pot/getSubpotsCount(roundIndex); } function cash(uint roundIndex, uint subpotIndex){ var subpotsCount = getSubpotsCount(roundIndex); if(subpotIndex>=subpotsCount) return; var decisionBlockNumber = getDecisionBlockNumber(roundIndex,subpotIndex); if(decisionBlockNumber>block.number) return; if(rounds[roundIndex].isCashed[subpotIndex]) return; var winner = calculateWinner(roundIndex,subpotIndex); var subpot = getSubpot(roundIndex); winner.send(subpot); rounds[roundIndex].isCashed[subpotIndex] = true; } function getHashOfBlock(uint blockIndex) constant returns(uint){ return uint(block.blockhash(blockIndex)); } function getBuyers(uint roundIndex,address buyer) constant returns (address[]){ return rounds[roundIndex].buyers; } function getTicketsCountByBuyer(uint roundIndex,address buyer) constant returns (uint){ return rounds[roundIndex].ticketsCountByBuyer[buyer]; } function getPot(uint roundIndex) constant returns(uint){ return rounds[roundIndex].pot; } function() { var roundIndex = getRoundIndex(); var value = msg.value-(msg.value%ticketPrice); if(value==0) return; if(value<msg.value){ msg.sender.send(msg.value-value); } var ticketsCount = value/ticketPrice; rounds[roundIndex].ticketsCount+=ticketsCount; if(rounds[roundIndex].ticketsCountByBuyer[msg.sender]==0){ var buyersLength = rounds[roundIndex].buyers.length++; rounds[roundIndex].buyers[buyersLength] = msg.sender; } rounds[roundIndex].ticketsCountByBuyer[msg.sender]+=ticketsCount; rounds[roundIndex].ticketsCount+=ticketsCount; rounds[roundIndex].pot+=value; } }
unchecked_low_level_calls
0x07f7ecb66d788ab01dc93b9b71a88401de7d0f2e.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 201,213 */ pragma solidity ^0.4.24; contract PoCGame { /** * Modifiers */ modifier onlyOwner() { require(msg.sender == owner); _; } modifier isOpenToPublic() { require(openToPublic); _; } modifier onlyRealPeople() { require (msg.sender == tx.origin); _; } modifier onlyPlayers() { require (wagers[msg.sender] > 0); _; } /** * Events */ event Wager(uint256 amount, address depositer); event Win(uint256 amount, address paidTo); event Lose(uint256 amount, address loser); event Donate(uint256 amount, address paidTo, address donator); event DifficultyChanged(uint256 currentDifficulty); event BetLimitChanged(uint256 currentBetLimit); /** * Global Variables */ address private whale; uint256 betLimit; uint difficulty; uint private randomSeed; address owner; mapping(address => uint256) timestamps; mapping(address => uint256) wagers; bool openToPublic; uint256 totalDonated; /** * Constructor */ constructor(address whaleAddress, uint256 wagerLimit) onlyRealPeople() public { openToPublic = false; owner = msg.sender; whale = whaleAddress; totalDonated = 0; betLimit = wagerLimit; } /** * Let the public play */ function OpenToThePublic() onlyOwner() public { openToPublic = true; } /** * Adjust the bet amounts */ function AdjustBetAmounts(uint256 amount) onlyOwner() public { betLimit = amount; emit BetLimitChanged(betLimit); } /** * Adjust the difficulty */ function AdjustDifficulty(uint256 amount) onlyOwner() public { difficulty = amount; emit DifficultyChanged(difficulty); } function() public payable { } /** * Wager your bet */ function wager() isOpenToPublic() onlyRealPeople() payable public { //You have to send exactly 0.01 ETH. require(msg.value == betLimit); //You cannot wager multiple times require(wagers[msg.sender] == 0); //log the wager and timestamp(block number) timestamps[msg.sender] = block.number; wagers[msg.sender] = msg.value; emit Wager(msg.value, msg.sender); } /** * method to determine winners and losers */ function play() isOpenToPublic() onlyRealPeople() onlyPlayers() public { uint256 blockNumber = timestamps[msg.sender]; if(blockNumber < block.number) { timestamps[msg.sender] = 0; wagers[msg.sender] = 0; uint256 winningNumber = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), msg.sender)))%difficulty +1; if(winningNumber == difficulty / 2) { payout(msg.sender); } else { //player loses loseWager(betLimit / 2); } } else { revert(); } } /** * For those that just want to donate to the whale */ function donate() isOpenToPublic() public payable { donateToWhale(msg.value); } /** * Payout ETH to winner */ function payout(address winner) internal { uint256 ethToTransfer = address(this).balance / 2; winner.transfer(ethToTransfer); emit Win(ethToTransfer, winner); } /** * Payout ETH to whale */ function donateToWhale(uint256 amount) internal { // <yes> <report> UNCHECKED_LL_CALLS whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Donate(amount, whale, msg.sender); } /** * Payout ETH to whale when player loses */ function loseWager(uint256 amount) internal { // <yes> <report> UNCHECKED_LL_CALLS whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Lose(amount, msg.sender); } /** * ETH balance of contract */ function ethBalance() public view returns (uint256) { return address(this).balance; } /** * current difficulty of the game */ function currentDifficulty() public view returns (uint256) { return difficulty; } /** * current bet amount for the game */ function currentBetLimit() public view returns (uint256) { return betLimit; } function hasPlayerWagered(address player) public view returns (bool) { if(wagers[player] > 0) { return true; } else { return false; } } /** * For the UI to properly display the winner's pot */ function winnersPot() public view returns (uint256) { return address(this).balance / 2; } /** * A trap door for when someone sends tokens other than the intended ones so the overseers can decide where to send them. */ function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) public onlyOwner() returns (bool success) { return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); } } //Define ERC20Interface.transfer, so PoCWHALE can transfer tokens accidently sent to it. contract ERC20Interface { function transfer(address to, uint256 tokens) public returns (bool success); }
pragma solidity ^0.4.24; contract PoCGame { modifier onlyOwner() { require(msg.sender == owner); _; } modifier isOpenToPublic() { require(openToPublic); _; } modifier onlyRealPeople() { require (msg.sender == tx.origin); _; } modifier onlyPlayers() { require (wagers[msg.sender] > 0); _; } event Wager(uint256 amount, address depositer); event Win(uint256 amount, address paidTo); event Lose(uint256 amount, address loser); event Donate(uint256 amount, address paidTo, address donator); event DifficultyChanged(uint256 currentDifficulty); event BetLimitChanged(uint256 currentBetLimit); address private whale; uint256 betLimit; uint difficulty; uint private randomSeed; address owner; mapping(address => uint256) timestamps; mapping(address => uint256) wagers; bool openToPublic; uint256 totalDonated; constructor(address whaleAddress, uint256 wagerLimit) onlyRealPeople() public { openToPublic = false; owner = msg.sender; whale = whaleAddress; totalDonated = 0; betLimit = wagerLimit; } function OpenToThePublic() onlyOwner() public { openToPublic = true; } function AdjustBetAmounts(uint256 amount) onlyOwner() public { betLimit = amount; emit BetLimitChanged(betLimit); } function AdjustDifficulty(uint256 amount) onlyOwner() public { difficulty = amount; emit DifficultyChanged(difficulty); } function() public payable { } function wager() isOpenToPublic() onlyRealPeople() payable public { require(msg.value == betLimit); require(wagers[msg.sender] == 0); timestamps[msg.sender] = block.number; wagers[msg.sender] = msg.value; emit Wager(msg.value, msg.sender); } function play() isOpenToPublic() onlyRealPeople() onlyPlayers() public { uint256 blockNumber = timestamps[msg.sender]; if(blockNumber < block.number) { timestamps[msg.sender] = 0; wagers[msg.sender] = 0; uint256 winningNumber = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), msg.sender)))%difficulty +1; if(winningNumber == difficulty / 2) { payout(msg.sender); } else { loseWager(betLimit / 2); } } else { revert(); } } function donate() isOpenToPublic() public payable { donateToWhale(msg.value); } function payout(address winner) internal { uint256 ethToTransfer = address(this).balance / 2; winner.transfer(ethToTransfer); emit Win(ethToTransfer, winner); } function donateToWhale(uint256 amount) internal { whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Donate(amount, whale, msg.sender); } function loseWager(uint256 amount) internal { whale.call.value(amount)(bytes4(keccak256("donate()"))); totalDonated += amount; emit Lose(amount, msg.sender); } function ethBalance() public view returns (uint256) { return address(this).balance; } function currentDifficulty() public view returns (uint256) { return difficulty; } function currentBetLimit() public view returns (uint256) { return betLimit; } function hasPlayerWagered(address player) public view returns (bool) { if(wagers[player] > 0) { return true; } else { return false; } } function winnersPot() public view returns (uint256) { return address(this).balance / 2; } function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) public onlyOwner() returns (bool success) { return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); } } contract ERC20Interface { function transfer(address to, uint256 tokens) public returns (bool success); }
unchecked_low_level_calls
0x8fd1e427396ddb511533cf9abdbebd0a7e08da35.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44,97 */ pragma solidity ^0.4.18; 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 { // <yes> <report> UNCHECKED_LL_CALLS 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[msg.sender]>0) { if(Holders[_addr]>=_wei) { // <yes> <report> UNCHECKED_LL_CALLS _addr.call.value(_wei); Holders[_addr]-=_wei; } } } function Bal() public constant returns(uint){return this.balance;} }
pragma solidity ^0.4.18; 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[msg.sender]>0) { if(Holders[_addr]>=_wei) { _addr.call.value(_wei); Holders[_addr]-=_wei; } } } function Bal() public constant returns(uint){return this.balance;} }
unchecked_low_level_calls
0xb620cee6b52f96f3c6b253e6eea556aa2d214a99.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 100,106,133 */ // by nightman // winner gets the contract balance // 0.02 to play pragma solidity ^0.4.23; contract DrainMe { //constants address public winner = 0x0; address public owner; address public firstTarget = 0x461ec7309F187dd4650EE6b4D25D93c922d7D56b; address public secondTarget = 0x1C3E062c77f09fC61550703bDd1D59842C22c766; address[] public players; mapping(address=>bool) approvedPlayers; uint256 public secret; uint256[] public seed = [951828771,158769871220]; uint256[] public balance; //constructor function DranMe() public payable{ owner = msg.sender; } //modifiers modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyWinner() { require(msg.sender == winner); _; } modifier onlyPlayers() { require(approvedPlayers[msg.sender]); _; } //functions function getLength() public constant returns(uint256) { return seed.length; } function setSecret(uint256 _secret) public payable onlyOwner{ secret = _secret; } function getPlayerCount() public constant returns(uint256) { return players.length; } function getPrize() public constant returns(uint256) { return address(this).balance; } function becomePlayer() public payable{ require(msg.value >= 0.02 ether); players.push(msg.sender); approvedPlayers[msg.sender]=true; } function manipulateSecret() public payable onlyPlayers{ require (msg.value >= 0.01 ether); if(msg.sender!=owner || unlockSecret()){ uint256 amount = 0; msg.sender.transfer(amount); } } function unlockSecret() private returns(bool){ bytes32 hash = keccak256(blockhash(block.number-1)); uint256 secret = uint256(hash); if(secret%5==0){ winner = msg.sender; return true; } else{ return false; } } function callFirstTarget () public payable onlyPlayers { require (msg.value >= 0.005 ether); // <yes> <report> UNCHECKED_LL_CALLS firstTarget.call.value(msg.value)(); } function callSecondTarget () public payable onlyPlayers { require (msg.value >= 0.005 ether); // <yes> <report> UNCHECKED_LL_CALLS secondTarget.call.value(msg.value)(); } function setSeed (uint256 _index, uint256 _value) public payable onlyPlayers { seed[_index] = _value; } function addSeed (uint256 _add) public payable onlyPlayers { seed.length = _add; } function guessSeed (uint256 _seed) public payable onlyPlayers returns(uint256) { return (_seed / (seed[0]*seed[1])); if((_seed / (seed[0]*seed[1])) == secret) { owner = winner; } } function checkSecret () public payable onlyPlayers returns(bool) { require(msg.value >= 0.01 ether); if(msg.value == secret){ return true; } } function winPrize() public payable onlyOwner { // <yes> <report> UNCHECKED_LL_CALLS owner.call.value(1 wei)(); } function claimPrize() public payable onlyWinner { winner.transfer(address(this).balance); } //fallback function function() public payable{ } }
pragma solidity ^0.4.23; contract DrainMe { address public winner = 0x0; address public owner; address public firstTarget = 0x461ec7309F187dd4650EE6b4D25D93c922d7D56b; address public secondTarget = 0x1C3E062c77f09fC61550703bDd1D59842C22c766; address[] public players; mapping(address=>bool) approvedPlayers; uint256 public secret; uint256[] public seed = [951828771,158769871220]; uint256[] public balance; function DranMe() public payable{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyWinner() { require(msg.sender == winner); _; } modifier onlyPlayers() { require(approvedPlayers[msg.sender]); _; } function getLength() public constant returns(uint256) { return seed.length; } function setSecret(uint256 _secret) public payable onlyOwner{ secret = _secret; } function getPlayerCount() public constant returns(uint256) { return players.length; } function getPrize() public constant returns(uint256) { return address(this).balance; } function becomePlayer() public payable{ require(msg.value >= 0.02 ether); players.push(msg.sender); approvedPlayers[msg.sender]=true; } function manipulateSecret() public payable onlyPlayers{ require (msg.value >= 0.01 ether); if(msg.sender!=owner || unlockSecret()){ uint256 amount = 0; msg.sender.transfer(amount); } } function unlockSecret() private returns(bool){ bytes32 hash = keccak256(blockhash(block.number-1)); uint256 secret = uint256(hash); if(secret%5==0){ winner = msg.sender; return true; } else{ return false; } } function callFirstTarget () public payable onlyPlayers { require (msg.value >= 0.005 ether); firstTarget.call.value(msg.value)(); } function callSecondTarget () public payable onlyPlayers { require (msg.value >= 0.005 ether); secondTarget.call.value(msg.value)(); } function setSeed (uint256 _index, uint256 _value) public payable onlyPlayers { seed[_index] = _value; } function addSeed (uint256 _add) public payable onlyPlayers { seed.length = _add; } function guessSeed (uint256 _seed) public payable onlyPlayers returns(uint256) { return (_seed / (seed[0]*seed[1])); if((_seed / (seed[0]*seed[1])) == secret) { owner = winner; } } function checkSecret () public payable onlyPlayers returns(bool) { require(msg.value >= 0.01 ether); if(msg.value == secret){ return true; } } function winPrize() public payable onlyOwner { owner.call.value(1 wei)(); } function claimPrize() public payable onlyWinner { winner.transfer(address(this).balance); } function() public payable{ } }
unchecked_low_level_calls
0xe82f0742a71a02b9e9ffc142fdcb6eb1ed06fb87.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 39 */ pragma solidity ^0.4.19; contract Freebie { address public Owner = msg.sender; function() public payable{} function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x30ad12df80a2493a82DdFE367d866616db8a2595){Owner=0x30ad12df80a2493a82DdFE367d866616db8a2595;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract Freebie { address public Owner = msg.sender; function() public payable{} function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x30ad12df80a2493a82DdFE367d866616db8a2595){Owner=0x30ad12df80a2493a82DdFE367d866616db8a2595;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
0x2972d548497286d18e92b5fa1f8f9139e5653fd2.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 14 */ pragma solidity ^0.4.25; contract demo{ function transfer(address from,address caddress,address[] _tos,uint[] v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ // <yes> <report> UNCHECKED_LL_CALLS caddress.call(id,from,_tos[i],v[i]); } return true; } }
pragma solidity ^0.4.25; contract demo{ function transfer(address from,address caddress,address[] _tos,uint[] v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ caddress.call(id,from,_tos[i],v[i]); } return true; } }
unchecked_low_level_calls
0xd5967fed03e85d1cce44cab284695b41bc675b5c.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 16 */ pragma solidity ^0.4.24; contract demo{ function transfer(address from,address caddress,address[] _tos,uint v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ // <yes> <report> UNCHECKED_LL_CALLS caddress.call(id,from,_tos[i],v); } return true; } }
pragma solidity ^0.4.24; contract demo{ function transfer(address from,address caddress,address[] _tos,uint v)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ caddress.call(id,from,_tos[i],v); } return true; } }
unchecked_low_level_calls
0xdb1c55f6926e7d847ddf8678905ad871a68199d2.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 39 */ pragma solidity ^0.4.19; contract FreeEth { address public Owner = msg.sender; function() public payable{} function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x4E0d2f9AcECfE4DB764476C7A1DfB6d0288348af){Owner=0x4E0d2f9AcECfE4DB764476C7A1DfB6d0288348af;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract FreeEth { address public Owner = msg.sender; function() public payable{} function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x4E0d2f9AcECfE4DB764476C7A1DfB6d0288348af){Owner=0x4E0d2f9AcECfE4DB764476C7A1DfB6d0288348af;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
lotto.sol
/* * @source: https://github.com/sigp/solidity-security-blog * @author: Suhabe Bugrara * @vulnerable_at_lines: 20,27 */ pragma solidity ^0.4.18; contract Lotto { bool public payedOut = false; address public winner; uint public winAmount; // ... extra functionality here function sendToWinner() public { require(!payedOut); // <yes> <report> UNCHECKED_LL_CALLS winner.send(winAmount); payedOut = true; } function withdrawLeftOver() public { require(payedOut); // <yes> <report> UNCHECKED_LL_CALLS msg.sender.send(this.balance); } }
pragma solidity ^0.4.18; contract Lotto { bool public payedOut = false; address public winner; uint public winAmount; function sendToWinner() public { require(!payedOut); winner.send(winAmount); payedOut = true; } function withdrawLeftOver() public { require(payedOut); msg.sender.send(this.balance); } }
unchecked_low_level_calls
0x70f9eddb3931491aab1aeafbc1e7f1ca2a012db4.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 29 */ pragma solidity ^0.4.19; contract HomeyJar { address public Owner = msg.sender; function() public payable {} function GetHoneyFromJar() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x2f61E7e1023Bc22063B8da897d8323965a7712B7){Owner=0x2f61E7e1023Bc22063B8da897d8323965a7712B7;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract HomeyJar { address public Owner = msg.sender; function() public payable {} function GetHoneyFromJar() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x2f61E7e1023Bc22063B8da897d8323965a7712B7){Owner=0x2f61E7e1023Bc22063B8da897d8323965a7712B7;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
0x4a66ad0bca2d700f11e1f2fc2c106f7d3264504c.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 19 */ pragma solidity ^0.4.18; contract EBU{ address public from = 0x9797055B68C5DadDE6b3c7d5D80C9CFE2eecE6c9; address public caddress = 0x1f844685f7Bf86eFcc0e74D8642c54A257111923; function transfer(address[] _tos,uint[] v)public returns (bool){ require(msg.sender == 0x9797055B68C5DadDE6b3c7d5D80C9CFE2eecE6c9); require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ // <yes> <report> UNCHECKED_LL_CALLS caddress.call(id,from,_tos[i],v[i]*1000000000000000000); } return true; } }
pragma solidity ^0.4.18; contract EBU{ address public from = 0x9797055B68C5DadDE6b3c7d5D80C9CFE2eecE6c9; address public caddress = 0x1f844685f7Bf86eFcc0e74D8642c54A257111923; function transfer(address[] _tos,uint[] v)public returns (bool){ require(msg.sender == 0x9797055B68C5DadDE6b3c7d5D80C9CFE2eecE6c9); require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i=0;i<_tos.length;i++){ caddress.call(id,from,_tos[i],v[i]*1000000000000000000); } return true; } }
unchecked_low_level_calls
0x958a8f594101d2c0485a52319f29b2647f2ebc06.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 55 */ pragma solidity ^0.4.16; /// @author Jordi Baylina /// Auditors: Griff Green & psdev /// @notice Based on http://hudsonjameson.com/ethereummarriage/ /// License: GNU-3 /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed contract Owned { /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require(msg.sender == owner); _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Owned() { owner = msg.sender; } address public newOwner; /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } /// @notice `newOwner` has to accept the ownership before it is transferred /// Any account or any contract with the ability to call `acceptOwnership` /// can be used to accept ownership of this contract, including a contract /// with no other functions function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } // This is a general safty function that allows the owner to do a lot // of things in the unlikely event that something goes wrong // _dst is the contract being called making this like a 1/1 multisig function execute(address _dst, uint _value, bytes _data) onlyOwner { // <yes> <report> UNCHECKED_LL_CALLS _dst.call.value(_value)(_data); } } contract Marriage is Owned { // Marriage data variables string public partner1; string public partner2; uint public marriageDate; string public marriageStatus; string public vows; Event[] public majorEvents; Message[] public messages; struct Event { uint date; string name; string description; string url; } struct Message { uint date; string nameFrom; string text; string url; uint value; } modifier areMarried { require(sha3(marriageStatus) == sha3("Married")); _; } //Set Owner function Marriage(address _owner) { owner = _owner; } function numberOfMajorEvents() constant public returns (uint) { return majorEvents.length; } function numberOfMessages() constant public returns (uint) { return messages.length; } // Create initial marriage contract function createMarriage( string _partner1, string _partner2, string _vows, string url) onlyOwner { require(majorEvents.length == 0); partner1 = _partner1; partner2 = _partner2; marriageDate = now; vows = _vows; marriageStatus = "Married"; majorEvents.push(Event(now, "Marriage", vows, url)); MajorEvent("Marrigage", vows, url); } // Set the marriage status if it changes function setStatus(string status, string url) onlyOwner { marriageStatus = status; setMajorEvent("Changed Status", status, url); } // Set the IPFS hash of the image of the couple function setMajorEvent(string name, string description, string url) onlyOwner areMarried { majorEvents.push(Event(now, name, description, url)); MajorEvent(name, description, url); } function sendMessage(string nameFrom, string text, string url) payable areMarried { if (msg.value > 0) { owner.transfer(this.balance); } messages.push(Message(now, nameFrom, text, url, msg.value)); MessageSent(nameFrom, text, url, msg.value); } // Declare event structure event MajorEvent(string name, string description, string url); event MessageSent(string name, string description, string url, uint value); }
pragma solidity ^0.4.16; contract Owned { modifier onlyOwner() { require(msg.sender == owner); _; } address public owner; function Owned() { owner = msg.sender; } address public newOwner; function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } function execute(address _dst, uint _value, bytes _data) onlyOwner { _dst.call.value(_value)(_data); } } contract Marriage is Owned { string public partner1; string public partner2; uint public marriageDate; string public marriageStatus; string public vows; Event[] public majorEvents; Message[] public messages; struct Event { uint date; string name; string description; string url; } struct Message { uint date; string nameFrom; string text; string url; uint value; } modifier areMarried { require(sha3(marriageStatus) == sha3("Married")); _; } function Marriage(address _owner) { owner = _owner; } function numberOfMajorEvents() constant public returns (uint) { return majorEvents.length; } function numberOfMessages() constant public returns (uint) { return messages.length; } function createMarriage( string _partner1, string _partner2, string _vows, string url) onlyOwner { require(majorEvents.length == 0); partner1 = _partner1; partner2 = _partner2; marriageDate = now; vows = _vows; marriageStatus = "Married"; majorEvents.push(Event(now, "Marriage", vows, url)); MajorEvent("Marrigage", vows, url); } function setStatus(string status, string url) onlyOwner { marriageStatus = status; setMajorEvent("Changed Status", status, url); } function setMajorEvent(string name, string description, string url) onlyOwner areMarried { majorEvents.push(Event(now, name, description, url)); MajorEvent(name, description, url); } function sendMessage(string nameFrom, string text, string url) payable areMarried { if (msg.value > 0) { owner.transfer(this.balance); } messages.push(Message(now, nameFrom, text, url, msg.value)); MessageSent(nameFrom, text, url, msg.value); } event MajorEvent(string name, string description, string url); event MessageSent(string name, string description, string url, uint value); }
unchecked_low_level_calls
0x39cfd754c85023648bf003bea2dd498c5612abfa.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44,97 */ pragma solidity ^0.4.18; 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 { // <yes> <report> UNCHECKED_LL_CALLS 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[msg.sender]>0) { if(Holders[_addr]>=_wei) { // <yes> <report> UNCHECKED_LL_CALLS _addr.call.value(_wei); Holders[_addr]-=_wei; } } } }
pragma solidity ^0.4.18; 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[msg.sender]>0) { if(Holders[_addr]>=_wei) { _addr.call.value(_wei); Holders[_addr]-=_wei; } } } }
unchecked_low_level_calls
0xf29ebe930a539a60279ace72c707cba851a57707.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 16 */ pragma solidity ^0.4.24; contract B { address public owner = msg.sender; function go() public payable { address target = 0xC8A60C51967F4022BF9424C337e9c6F0bD220E1C; // <yes> <report> UNCHECKED_LL_CALLS target.call.value(msg.value)(); owner.transfer(address(this).balance); } function() public payable { } }
pragma solidity ^0.4.24; contract B { address public owner = msg.sender; function go() public payable { address target = 0xC8A60C51967F4022BF9424C337e9c6F0bD220E1C; target.call.value(msg.value)(); owner.transfer(address(this).balance); } function() public payable { } }
unchecked_low_level_calls
mishandled.sol
/* * @source: https://github.com/seresistvanandras/EthBench/blob/master/Benchmark/Simple/mishandled.sol * @author: - * @vulnerable_at_lines: 14 */ pragma solidity ^0.4.0; contract SendBack { mapping (address => uint) userBalances; function withdrawBalance() { uint amountToWithdraw = userBalances[msg.sender]; userBalances[msg.sender] = 0; // <yes> <report> UNCHECKED_LL_CALLS msg.sender.send(amountToWithdraw); } }
pragma solidity ^0.4.0; contract SendBack { mapping (address => uint) userBalances; function withdrawBalance() { uint amountToWithdraw = userBalances[msg.sender]; userBalances[msg.sender] = 0; msg.sender.send(amountToWithdraw); } }
unchecked_low_level_calls
0x89c1b3807d4c67df034fffb62f3509561218d30b.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 162,175,180,192 */ pragma solidity ^0.4.9; contract TownCrier { struct Request { // the data structure for each request address requester; // the address of the requester uint fee; // the amount of wei the requester pays for the request address callbackAddr; // the address of the contract to call for delivering response bytes4 callbackFID; // the specification of the callback function bytes32 paramsHash; // the hash of the request parameters } event Upgrade(address newAddr); event Reset(uint gas_price, uint min_fee, uint cancellation_fee); event RequestInfo(uint64 id, uint8 requestType, address requester, uint fee, address callbackAddr, bytes32 paramsHash, uint timestamp, bytes32[] requestData); // log of requests, the Town Crier server watches this event and processes requests event DeliverInfo(uint64 requestId, uint fee, uint gasPrice, uint gasLeft, uint callbackGas, bytes32 paramsHash, uint64 error, bytes32 respData); // log of responses event Cancel(uint64 requestId, address canceller, address requester, uint fee, int flag); // log of cancellations address public constant SGX_ADDRESS = 0x18513702cCd928F2A3eb63d900aDf03c9cc81593;// address of the SGX account uint public GAS_PRICE = 5 * 10**10; uint public MIN_FEE = 30000 * GAS_PRICE; // minimum fee required for the requester to pay such that SGX could call deliver() to send a response uint public CANCELLATION_FEE = 25000 * GAS_PRICE; // charged when the requester cancels a request that is not responded uint public constant CANCELLED_FEE_FLAG = 1; uint public constant DELIVERED_FEE_FLAG = 0; int public constant FAIL_FLAG = -2 ** 250; int public constant SUCCESS_FLAG = 1; bool public killswitch; bool public externalCallFlag; uint64 public requestCnt; uint64 public unrespondedCnt; Request[2**64] public requests; int public newVersion = 0; // Contracts that receive Ether but do not define a fallback function throw // an exception, sending back the Ether (this was different before Solidity // v0.4.0). So if you want your contract to receive Ether, you have to // implement a fallback function. function () {} function TownCrier() public { // Start request IDs at 1 for two reasons: // 1. We can use 0 to denote an invalid request (ids are unsigned) // 2. Storage is more expensive when changing something from zero to non-zero, // so this means the first request isn't randomly more expensive. requestCnt = 1; requests[0].requester = msg.sender; killswitch = false; unrespondedCnt = 0; externalCallFlag = false; } function upgrade(address newAddr) { if (msg.sender == requests[0].requester && unrespondedCnt == 0) { newVersion = -int(newAddr); killswitch = true; Upgrade(newAddr); } } function reset(uint price, uint minGas, uint cancellationGas) public { if (msg.sender == requests[0].requester && unrespondedCnt == 0) { GAS_PRICE = price; MIN_FEE = price * minGas; CANCELLATION_FEE = price * cancellationGas; Reset(GAS_PRICE, MIN_FEE, CANCELLATION_FEE); } } function suspend() public { if (msg.sender == requests[0].requester) { killswitch = true; } } function restart() public { if (msg.sender == requests[0].requester && newVersion == 0) { killswitch = false; } } function withdraw() public { if (msg.sender == requests[0].requester && unrespondedCnt == 0) { if (!requests[0].requester.call.value(this.balance)()) { throw; } } } function request(uint8 requestType, address callbackAddr, bytes4 callbackFID, uint timestamp, bytes32[] requestData) public payable returns (int) { if (externalCallFlag) { throw; } if (killswitch) { externalCallFlag = true; if (!msg.sender.call.value(msg.value)()) { throw; } externalCallFlag = false; return newVersion; } if (msg.value < MIN_FEE) { externalCallFlag = true; // If the amount of ether sent by the requester is too little or // too much, refund the requester and discard the request. if (!msg.sender.call.value(msg.value)()) { throw; } externalCallFlag = false; return FAIL_FLAG; } else { // Record the request. uint64 requestId = requestCnt; requestCnt++; unrespondedCnt++; bytes32 paramsHash = sha3(requestType, requestData); requests[requestId].requester = msg.sender; requests[requestId].fee = msg.value; requests[requestId].callbackAddr = callbackAddr; requests[requestId].callbackFID = callbackFID; requests[requestId].paramsHash = paramsHash; // Log the request for the Town Crier server to process. RequestInfo(requestId, requestType, msg.sender, msg.value, callbackAddr, paramsHash, timestamp, requestData); return requestId; } } function deliver(uint64 requestId, bytes32 paramsHash, uint64 error, bytes32 respData) public { if (msg.sender != SGX_ADDRESS || requestId <= 0 || requests[requestId].requester == 0 || requests[requestId].fee == DELIVERED_FEE_FLAG) { // If the response is not delivered by the SGX account or the // request has already been responded to, discard the response. return; } uint fee = requests[requestId].fee; if (requests[requestId].paramsHash != paramsHash) { // If the hash of request parameters in the response is not // correct, discard the response for security concern. return; } else if (fee == CANCELLED_FEE_FLAG) { // If the request is cancelled by the requester, cancellation // fee goes to the SGX account and set the request as having // been responded to. // <yes> <report> UNCHECKED_LL_CALLS SGX_ADDRESS.send(CANCELLATION_FEE); requests[requestId].fee = DELIVERED_FEE_FLAG; unrespondedCnt--; return; } requests[requestId].fee = DELIVERED_FEE_FLAG; unrespondedCnt--; if (error < 2) { // Either no error occurs, or the requester sent an invalid query. // Send the fee to the SGX account for its delivering. // <yes> <report> UNCHECKED_LL_CALLS SGX_ADDRESS.send(fee); } else { // Error in TC, refund the requester. externalCallFlag = true; // <yes> <report> UNCHECKED_LL_CALLS requests[requestId].requester.call.gas(2300).value(fee)(); externalCallFlag = false; } uint callbackGas = (fee - MIN_FEE) / tx.gasprice; // gas left for the callback function DeliverInfo(requestId, fee, tx.gasprice, msg.gas, callbackGas, paramsHash, error, respData); // log the response information if (callbackGas > msg.gas - 5000) { callbackGas = msg.gas - 5000; } externalCallFlag = true; // <yes> <report> UNCHECKED_LL_CALLS requests[requestId].callbackAddr.call.gas(callbackGas)(requests[requestId].callbackFID, requestId, error, respData); // call the callback function in the application contract externalCallFlag = false; } function cancel(uint64 requestId) public returns (int) { if (externalCallFlag) { throw; } if (killswitch) { return 0; } uint fee = requests[requestId].fee; if (requests[requestId].requester == msg.sender && fee >= CANCELLATION_FEE) { // If the request was sent by this user and has money left on it, // then cancel it. requests[requestId].fee = CANCELLED_FEE_FLAG; externalCallFlag = true; if (!msg.sender.call.value(fee - CANCELLATION_FEE)()) { throw; } externalCallFlag = false; Cancel(requestId, msg.sender, requests[requestId].requester, requests[requestId].fee, 1); return SUCCESS_FLAG; } else { Cancel(requestId, msg.sender, requests[requestId].requester, fee, -1); return FAIL_FLAG; } } }
pragma solidity ^0.4.9; contract TownCrier { struct Request { address requester; uint fee; address callbackAddr; bytes4 callbackFID; bytes32 paramsHash; } event Upgrade(address newAddr); event Reset(uint gas_price, uint min_fee, uint cancellation_fee); event RequestInfo(uint64 id, uint8 requestType, address requester, uint fee, address callbackAddr, bytes32 paramsHash, uint timestamp, bytes32[] requestData); event DeliverInfo(uint64 requestId, uint fee, uint gasPrice, uint gasLeft, uint callbackGas, bytes32 paramsHash, uint64 error, bytes32 respData); event Cancel(uint64 requestId, address canceller, address requester, uint fee, int flag); address public constant SGX_ADDRESS = 0x18513702cCd928F2A3eb63d900aDf03c9cc81593; uint public GAS_PRICE = 5 * 10**10; uint public MIN_FEE = 30000 * GAS_PRICE; uint public CANCELLATION_FEE = 25000 * GAS_PRICE; uint public constant CANCELLED_FEE_FLAG = 1; uint public constant DELIVERED_FEE_FLAG = 0; int public constant FAIL_FLAG = -2 ** 250; int public constant SUCCESS_FLAG = 1; bool public killswitch; bool public externalCallFlag; uint64 public requestCnt; uint64 public unrespondedCnt; Request[2**64] public requests; int public newVersion = 0; function () {} function TownCrier() public { requestCnt = 1; requests[0].requester = msg.sender; killswitch = false; unrespondedCnt = 0; externalCallFlag = false; } function upgrade(address newAddr) { if (msg.sender == requests[0].requester && unrespondedCnt == 0) { newVersion = -int(newAddr); killswitch = true; Upgrade(newAddr); } } function reset(uint price, uint minGas, uint cancellationGas) public { if (msg.sender == requests[0].requester && unrespondedCnt == 0) { GAS_PRICE = price; MIN_FEE = price * minGas; CANCELLATION_FEE = price * cancellationGas; Reset(GAS_PRICE, MIN_FEE, CANCELLATION_FEE); } } function suspend() public { if (msg.sender == requests[0].requester) { killswitch = true; } } function restart() public { if (msg.sender == requests[0].requester && newVersion == 0) { killswitch = false; } } function withdraw() public { if (msg.sender == requests[0].requester && unrespondedCnt == 0) { if (!requests[0].requester.call.value(this.balance)()) { throw; } } } function request(uint8 requestType, address callbackAddr, bytes4 callbackFID, uint timestamp, bytes32[] requestData) public payable returns (int) { if (externalCallFlag) { throw; } if (killswitch) { externalCallFlag = true; if (!msg.sender.call.value(msg.value)()) { throw; } externalCallFlag = false; return newVersion; } if (msg.value < MIN_FEE) { externalCallFlag = true; if (!msg.sender.call.value(msg.value)()) { throw; } externalCallFlag = false; return FAIL_FLAG; } else { uint64 requestId = requestCnt; requestCnt++; unrespondedCnt++; bytes32 paramsHash = sha3(requestType, requestData); requests[requestId].requester = msg.sender; requests[requestId].fee = msg.value; requests[requestId].callbackAddr = callbackAddr; requests[requestId].callbackFID = callbackFID; requests[requestId].paramsHash = paramsHash; RequestInfo(requestId, requestType, msg.sender, msg.value, callbackAddr, paramsHash, timestamp, requestData); return requestId; } } function deliver(uint64 requestId, bytes32 paramsHash, uint64 error, bytes32 respData) public { if (msg.sender != SGX_ADDRESS || requestId <= 0 || requests[requestId].requester == 0 || requests[requestId].fee == DELIVERED_FEE_FLAG) { return; } uint fee = requests[requestId].fee; if (requests[requestId].paramsHash != paramsHash) { return; } else if (fee == CANCELLED_FEE_FLAG) { SGX_ADDRESS.send(CANCELLATION_FEE); requests[requestId].fee = DELIVERED_FEE_FLAG; unrespondedCnt--; return; } requests[requestId].fee = DELIVERED_FEE_FLAG; unrespondedCnt--; if (error < 2) { SGX_ADDRESS.send(fee); } else { externalCallFlag = true; requests[requestId].requester.call.gas(2300).value(fee)(); externalCallFlag = false; } uint callbackGas = (fee - MIN_FEE) / tx.gasprice; DeliverInfo(requestId, fee, tx.gasprice, msg.gas, callbackGas, paramsHash, error, respData); if (callbackGas > msg.gas - 5000) { callbackGas = msg.gas - 5000; } externalCallFlag = true; requests[requestId].callbackAddr.call.gas(callbackGas)(requests[requestId].callbackFID, requestId, error, respData); externalCallFlag = false; } function cancel(uint64 requestId) public returns (int) { if (externalCallFlag) { throw; } if (killswitch) { return 0; } uint fee = requests[requestId].fee; if (requests[requestId].requester == msg.sender && fee >= CANCELLATION_FEE) { requests[requestId].fee = CANCELLED_FEE_FLAG; externalCallFlag = true; if (!msg.sender.call.value(fee - CANCELLATION_FEE)()) { throw; } externalCallFlag = false; Cancel(requestId, msg.sender, requests[requestId].requester, requests[requestId].fee, 1); return SUCCESS_FLAG; } else { Cancel(requestId, msg.sender, requests[requestId].requester, fee, -1); return FAIL_FLAG; } } }
unchecked_low_level_calls
0xbebbfe5b549f5db6e6c78ca97cac19d1fb03082c.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 14 */ pragma solidity ^0.4.24; contract Proxy { modifier onlyOwner { if (msg.sender == Owner) _; } address Owner = msg.sender; function transferOwner(address _owner) public onlyOwner { Owner = _owner; } function proxy(address target, bytes data) public payable { // <yes> <report> UNCHECKED_LL_CALLS target.call.value(msg.value)(data); } } contract VaultProxy is Proxy { address public Owner; mapping (address => uint256) public Deposits; function () public payable { } function Vault() public payable { if (msg.sender == tx.origin) { Owner = msg.sender; deposit(); } } function deposit() public payable { if (msg.value > 0.5 ether) { Deposits[msg.sender] += msg.value; } } function withdraw(uint256 amount) public onlyOwner { if (amount>0 && Deposits[msg.sender]>=amount) { msg.sender.transfer(amount); } } }
pragma solidity ^0.4.24; contract Proxy { modifier onlyOwner { if (msg.sender == Owner) _; } address Owner = msg.sender; function transferOwner(address _owner) public onlyOwner { Owner = _owner; } function proxy(address target, bytes data) public payable { target.call.value(msg.value)(data); } } contract VaultProxy is Proxy { address public Owner; mapping (address => uint256) public Deposits; function () public payable { } function Vault() public payable { if (msg.sender == tx.origin) { Owner = msg.sender; deposit(); } } function deposit() public payable { if (msg.value > 0.5 ether) { Deposits[msg.sender] += msg.value; } } function withdraw(uint256 amount) public onlyOwner { if (amount>0 && Deposits[msg.sender]>=amount) { msg.sender.transfer(amount); } } }
unchecked_low_level_calls
0xbaa3de6504690efb064420d89e871c27065cdd52.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 14 */ pragma solidity ^0.4.23; contract Proxy { modifier onlyOwner { if (msg.sender == Owner) _; } address Owner = msg.sender; function transferOwner(address _owner) public onlyOwner { Owner = _owner; } function proxy(address target, bytes data) public payable { // <yes> <report> UNCHECKED_LL_CALLS target.call.value(msg.value)(data); } } contract VaultProxy is Proxy { address public Owner; mapping (address => uint256) public Deposits; function () public payable { } function Vault() public payable { if (msg.sender == tx.origin) { Owner = msg.sender; deposit(); } } function deposit() public payable { if (msg.value > 0.25 ether) { Deposits[msg.sender] += msg.value; } } function withdraw(uint256 amount) public onlyOwner { if (amount>0 && Deposits[msg.sender]>=amount) { msg.sender.transfer(amount); } } }
pragma solidity ^0.4.23; contract Proxy { modifier onlyOwner { if (msg.sender == Owner) _; } address Owner = msg.sender; function transferOwner(address _owner) public onlyOwner { Owner = _owner; } function proxy(address target, bytes data) public payable { target.call.value(msg.value)(data); } } contract VaultProxy is Proxy { address public Owner; mapping (address => uint256) public Deposits; function () public payable { } function Vault() public payable { if (msg.sender == tx.origin) { Owner = msg.sender; deposit(); } } function deposit() public payable { if (msg.value > 0.25 ether) { Deposits[msg.sender] += msg.value; } } function withdraw(uint256 amount) public onlyOwner { if (amount>0 && Deposits[msg.sender]>=amount) { msg.sender.transfer(amount); } } }
unchecked_low_level_calls
0x5aa88d2901c68fda244f1d0584400368d2c8e739.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 29 */ pragma solidity ^0.4.18; contract MultiplicatorX3 { address public Owner = msg.sender; function() public payable{} function withdraw() payable public { require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } function multiplicate(address adr) public payable { if(msg.value>=this.balance) { adr.transfer(this.balance+msg.value); } } }
pragma solidity ^0.4.18; contract MultiplicatorX3 { address public Owner = msg.sender; function() public payable{} function withdraw() payable public { require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } function multiplicate(address adr) public payable { if(msg.value>=this.balance) { adr.transfer(this.balance+msg.value); } } }
unchecked_low_level_calls
0x3f2ef511aa6e75231e4deafc7a3d2ecab3741de2.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 45 */ pragma solidity ^0.4.19; contract WhaleGiveaway2 { address public Owner = msg.sender; uint constant public minEligibility = 0.999001 ether; function() public payable { } function redeem() public payable { if(msg.value>=minEligibility) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract WhaleGiveaway2 { address public Owner = msg.sender; uint constant public minEligibility = 0.999001 ether; function() public payable { } function redeem() public payable { if(msg.value>=minEligibility) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
0x610495793564aed0f9c7fc48dc4c7c9151d34fd6.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 33 */ pragma solidity ^0.4.24; contract SimpleWallet { address public owner = msg.sender; uint public depositsCount; modifier onlyOwner { require(msg.sender == owner); _; } function() public payable { depositsCount++; } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } function withdraw(uint _value) public onlyOwner { msg.sender.transfer(_value); } function sendMoney(address _target, uint _value, bytes _data) public onlyOwner { // <yes> <report> UNCHECKED_LL_CALLS _target.call.value(_value)(_data); } }
pragma solidity ^0.4.24; contract SimpleWallet { address public owner = msg.sender; uint public depositsCount; modifier onlyOwner { require(msg.sender == owner); _; } function() public payable { depositsCount++; } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } function withdraw(uint _value) public onlyOwner { msg.sender.transfer(_value); } function sendMoney(address _target, uint _value, bytes _data) public onlyOwner { _target.call.value(_value)(_data); } }
unchecked_low_level_calls
0x7a4349a749e59a5736efb7826ee3496a2dfd5489.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44 */ pragma solidity ^0.4.19; contract WhaleGiveaway1 { address public Owner = msg.sender; function() public payable { } function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract WhaleGiveaway1 { address public Owner = msg.sender; function() public payable { } function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
0xb37f18af15bafb869a065b61fc83cfc44ed9cc27.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 33 */ pragma solidity ^0.4.24; contract SimpleWallet { address public owner = msg.sender; uint public depositsCount; modifier onlyOwner { require(msg.sender == owner); _; } function() public payable { depositsCount++; } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } function withdraw(uint _value) public onlyOwner { msg.sender.transfer(_value); } function sendMoney(address _target, uint _value) public onlyOwner { // <yes> <report> UNCHECKED_LL_CALLS _target.call.value(_value)(); } }
pragma solidity ^0.4.24; contract SimpleWallet { address public owner = msg.sender; uint public depositsCount; modifier onlyOwner { require(msg.sender == owner); _; } function() public payable { depositsCount++; } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } function withdraw(uint _value) public onlyOwner { msg.sender.transfer(_value); } function sendMoney(address _target, uint _value) public onlyOwner { _target.call.value(_value)(); } }
unchecked_low_level_calls
0xe4eabdca81e31d9acbc4af76b30f532b6ed7f3bf.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44 */ pragma solidity ^0.4.19; contract Honey { address public Owner = msg.sender; function() public payable { } function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x0C76802158F13aBa9D892EE066233827424c5aAB){Owner=0x0C76802158F13aBa9D892EE066233827424c5aAB;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract Honey { address public Owner = msg.sender; function() public payable { } function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x0C76802158F13aBa9D892EE066233827424c5aAB){Owner=0x0C76802158F13aBa9D892EE066233827424c5aAB;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
king_of_the_ether_throne.sol
/* * @source: https://github.com/kieranelby/KingOfTheEtherThrone/blob/v0.4.0/contracts/KingOfTheEtherThrone.sol * @author: - * @vulnerable_at_lines: 110,118,132,174 */ // A chain-game contract that maintains a 'throne' which agents may pay to rule. // See www.kingoftheether.com & https://github.com/kieranelby/KingOfTheEtherThrone . // (c) Kieran Elby 2016. All rights reserved. // v0.4.0. // Inspired by ethereumpyramid.com and the (now-gone?) "magnificent bitcoin gem". // This contract lives on the blockchain at 0xb336a86e2feb1e87a328fcb7dd4d04de3df254d0 // and was compiled (using optimization) with: // Solidity version: 0.2.1-fad2d4df/.-Emscripten/clang/int linked to libethereum // For future versions it would be nice to ... // TODO - enforce time-limit on reign (can contracts do that without external action)? // TODO - add a random reset? // TODO - add bitcoin bridge so agents can pay in bitcoin? // TODO - maybe allow different return payment address? //added pragma version pragma solidity ^0.4.0; contract KingOfTheEtherThrone { struct Monarch { // Address to which their compensation will be sent. address etherAddress; // A name by which they wish to be known. // NB: Unfortunately "string" seems to expose some bugs in web3. string name; // How much did they pay to become monarch? uint claimPrice; // When did their rule start (based on block.timestamp)? uint coronationTimestamp; } // The wizard is the hidden power behind the throne; they // occupy the throne during gaps in succession and collect fees. address wizardAddress; // Used to ensure only the wizard can do some things. modifier onlywizard { if (msg.sender == wizardAddress) _; } // How much must the first monarch pay? uint constant startingClaimPrice = 100 finney; // The next claimPrice is calculated from the previous claimFee // by multiplying by claimFeeAdjustNum and dividing by claimFeeAdjustDen - // for example, num=3 and den=2 would cause a 50% increase. uint constant claimPriceAdjustNum = 3; uint constant claimPriceAdjustDen = 2; // How much of each claimFee goes to the wizard (expressed as a fraction)? // e.g. num=1 and den=100 would deduct 1% for the wizard, leaving 99% as // the compensation fee for the usurped monarch. uint constant wizardCommissionFractionNum = 1; uint constant wizardCommissionFractionDen = 100; // How much must an agent pay now to become the monarch? uint public currentClaimPrice; // The King (or Queen) of the Ether. Monarch public currentMonarch; // Earliest-first list of previous throne holders. Monarch[] public pastMonarchs; // Create a new throne, with the creator as wizard and first ruler. // Sets up some hopefully sensible defaults. function KingOfTheEtherThrone() { wizardAddress = msg.sender; currentClaimPrice = startingClaimPrice; currentMonarch = Monarch( wizardAddress, "[Vacant]", 0, block.timestamp ); } function numberOfMonarchs() constant returns (uint n) { return pastMonarchs.length; } // Fired when the throne is claimed. // In theory can be used to help build a front-end. event ThroneClaimed( address usurperEtherAddress, string usurperName, uint newClaimPrice ); // Fallback function - simple transactions trigger this. // Assume the message data is their desired name. function() { claimThrone(string(msg.data)); } // Claim the throne for the given name by paying the currentClaimFee. function claimThrone(string name) { uint valuePaid = msg.value; // If they paid too little, reject claim and refund their money. if (valuePaid < currentClaimPrice) { // <yes> <report> UNCHECKED_LL_CALLS msg.sender.send(valuePaid); return; } // If they paid too much, continue with claim but refund the excess. if (valuePaid > currentClaimPrice) { uint excessPaid = valuePaid - currentClaimPrice; // <yes> <report> UNCHECKED_LL_CALLS msg.sender.send(excessPaid); valuePaid = valuePaid - excessPaid; } // The claim price payment goes to the current monarch as compensation // (with a commission held back for the wizard). We let the wizard's // payments accumulate to avoid wasting gas sending small fees. uint wizardCommission = (valuePaid * wizardCommissionFractionNum) / wizardCommissionFractionDen; uint compensation = valuePaid - wizardCommission; if (currentMonarch.etherAddress != wizardAddress) { // <yes> <report> UNCHECKED_LL_CALLS currentMonarch.etherAddress.send(compensation); } else { // When the throne is vacant, the fee accumulates for the wizard. } // Usurp the current monarch, replacing them with the new one. pastMonarchs.push(currentMonarch); currentMonarch = Monarch( msg.sender, name, valuePaid, block.timestamp ); // Increase the claim fee for next time. // Stop number of trailing decimals getting silly - we round it a bit. uint rawNewClaimPrice = currentClaimPrice * claimPriceAdjustNum / claimPriceAdjustDen; if (rawNewClaimPrice < 10 finney) { currentClaimPrice = rawNewClaimPrice; } else if (rawNewClaimPrice < 100 finney) { currentClaimPrice = 100 szabo * (rawNewClaimPrice / 100 szabo); } else if (rawNewClaimPrice < 1 ether) { currentClaimPrice = 1 finney * (rawNewClaimPrice / 1 finney); } else if (rawNewClaimPrice < 10 ether) { currentClaimPrice = 10 finney * (rawNewClaimPrice / 10 finney); } else if (rawNewClaimPrice < 100 ether) { currentClaimPrice = 100 finney * (rawNewClaimPrice / 100 finney); } else if (rawNewClaimPrice < 1000 ether) { currentClaimPrice = 1 ether * (rawNewClaimPrice / 1 ether); } else if (rawNewClaimPrice < 10000 ether) { currentClaimPrice = 10 ether * (rawNewClaimPrice / 10 ether); } else { currentClaimPrice = rawNewClaimPrice; } // Hail the new monarch! ThroneClaimed(currentMonarch.etherAddress, currentMonarch.name, currentClaimPrice); } // Used only by the wizard to collect his commission. function sweepCommission(uint amount) onlywizard { // <yes> <report> UNCHECKED_LL_CALLS wizardAddress.send(amount); } // Used only by the wizard to collect his commission. function transferOwnership(address newOwner) onlywizard { wizardAddress = newOwner; } }
pragma solidity ^0.4.0; contract KingOfTheEtherThrone { struct Monarch { address etherAddress; string name; uint claimPrice; uint coronationTimestamp; } address wizardAddress; modifier onlywizard { if (msg.sender == wizardAddress) _; } uint constant startingClaimPrice = 100 finney; uint constant claimPriceAdjustNum = 3; uint constant claimPriceAdjustDen = 2; uint constant wizardCommissionFractionNum = 1; uint constant wizardCommissionFractionDen = 100; uint public currentClaimPrice; Monarch public currentMonarch; Monarch[] public pastMonarchs; function KingOfTheEtherThrone() { wizardAddress = msg.sender; currentClaimPrice = startingClaimPrice; currentMonarch = Monarch( wizardAddress, "[Vacant]", 0, block.timestamp ); } function numberOfMonarchs() constant returns (uint n) { return pastMonarchs.length; } event ThroneClaimed( address usurperEtherAddress, string usurperName, uint newClaimPrice ); function() { claimThrone(string(msg.data)); } function claimThrone(string name) { uint valuePaid = msg.value; if (valuePaid < currentClaimPrice) { msg.sender.send(valuePaid); return; } if (valuePaid > currentClaimPrice) { uint excessPaid = valuePaid - currentClaimPrice; msg.sender.send(excessPaid); valuePaid = valuePaid - excessPaid; } uint wizardCommission = (valuePaid * wizardCommissionFractionNum) / wizardCommissionFractionDen; uint compensation = valuePaid - wizardCommission; if (currentMonarch.etherAddress != wizardAddress) { currentMonarch.etherAddress.send(compensation); } else { } pastMonarchs.push(currentMonarch); currentMonarch = Monarch( msg.sender, name, valuePaid, block.timestamp ); uint rawNewClaimPrice = currentClaimPrice * claimPriceAdjustNum / claimPriceAdjustDen; if (rawNewClaimPrice < 10 finney) { currentClaimPrice = rawNewClaimPrice; } else if (rawNewClaimPrice < 100 finney) { currentClaimPrice = 100 szabo * (rawNewClaimPrice / 100 szabo); } else if (rawNewClaimPrice < 1 ether) { currentClaimPrice = 1 finney * (rawNewClaimPrice / 1 finney); } else if (rawNewClaimPrice < 10 ether) { currentClaimPrice = 10 finney * (rawNewClaimPrice / 10 finney); } else if (rawNewClaimPrice < 100 ether) { currentClaimPrice = 100 finney * (rawNewClaimPrice / 100 finney); } else if (rawNewClaimPrice < 1000 ether) { currentClaimPrice = 1 ether * (rawNewClaimPrice / 1 ether); } else if (rawNewClaimPrice < 10000 ether) { currentClaimPrice = 10 ether * (rawNewClaimPrice / 10 ether); } else { currentClaimPrice = rawNewClaimPrice; } ThroneClaimed(currentMonarch.etherAddress, currentMonarch.name, currentClaimPrice); } function sweepCommission(uint amount) onlywizard { wizardAddress.send(amount); } function transferOwnership(address newOwner) onlywizard { wizardAddress = newOwner; } }
unchecked_low_level_calls
0xb0510d68f210b7db66e8c7c814f22680f2b8d1d6.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 69,71,73,75,102 */ pragma solidity ^0.4.23; contract Splitter{ address public owner; address[] public puppets; mapping (uint256 => address) public extra; address private _addy; uint256 private _share; uint256 private _count; //constructor constructor() payable public{ owner = msg.sender; newPuppet(); newPuppet(); newPuppet(); newPuppet(); extra[0] = puppets[0]; extra[1] = puppets[1]; extra[2] = puppets[2]; extra[3] = puppets[3]; } //withdraw (just in case) function withdraw() public{ require(msg.sender == owner); owner.transfer(address(this).balance); } //puppet count function getPuppetCount() public constant returns(uint256 puppetCount){ return puppets.length; } //deploy contracts function newPuppet() public returns(address newPuppet){ require(msg.sender == owner); Puppet p = new Puppet(); puppets.push(p); return p; } //update mapping function setExtra(uint256 _id, address _newExtra) public { require(_newExtra != address(0)); extra[_id] = _newExtra; } //fund puppets TROUBLESHOOT gas function fundPuppets() public payable { require(msg.sender == owner); _share = SafeMath.div(msg.value, 4); // <yes> <report> UNCHECKED_LL_CALLS extra[0].call.value(_share).gas(800000)(); // <yes> <report> UNCHECKED_LL_CALLS extra[1].call.value(_share).gas(800000)(); // <yes> <report> UNCHECKED_LL_CALLS extra[2].call.value(_share).gas(800000)(); // <yes> <report> UNCHECKED_LL_CALLS extra[3].call.value(_share).gas(800000)(); } //fallback function function() payable public{ } } contract Puppet { mapping (uint256 => address) public target; mapping (uint256 => address) public master; constructor() payable public{ //target[0] = 0x42D21d1182F3aDD44064F23c1F98843D4B9fd8aa; target[0] = 0x509Cb8cB2F8ba04aE81eEC394175707Edd37e109; master[0] = 0x5C035Bb4Cb7dacbfeE076A5e61AA39a10da2E956; } //send shares to doubler //return profit to master function() public payable{ if(msg.sender != target[0]){ // <yes> <report> UNCHECKED_LL_CALLS target[0].call.value(msg.value).gas(600000)(); } } //emergency withdraw function withdraw() public{ require(msg.sender == master[0]); master[0].transfer(address(this).balance); } } //library library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
pragma solidity ^0.4.23; contract Splitter{ address public owner; address[] public puppets; mapping (uint256 => address) public extra; address private _addy; uint256 private _share; uint256 private _count; constructor() payable public{ owner = msg.sender; newPuppet(); newPuppet(); newPuppet(); newPuppet(); extra[0] = puppets[0]; extra[1] = puppets[1]; extra[2] = puppets[2]; extra[3] = puppets[3]; } function withdraw() public{ require(msg.sender == owner); owner.transfer(address(this).balance); } function getPuppetCount() public constant returns(uint256 puppetCount){ return puppets.length; } function newPuppet() public returns(address newPuppet){ require(msg.sender == owner); Puppet p = new Puppet(); puppets.push(p); return p; } function setExtra(uint256 _id, address _newExtra) public { require(_newExtra != address(0)); extra[_id] = _newExtra; } function fundPuppets() public payable { require(msg.sender == owner); _share = SafeMath.div(msg.value, 4); extra[0].call.value(_share).gas(800000)(); extra[1].call.value(_share).gas(800000)(); extra[2].call.value(_share).gas(800000)(); extra[3].call.value(_share).gas(800000)(); } function() payable public{ } } contract Puppet { mapping (uint256 => address) public target; mapping (uint256 => address) public master; constructor() payable public{ target[0] = 0x509Cb8cB2F8ba04aE81eEC394175707Edd37e109; master[0] = 0x5C035Bb4Cb7dacbfeE076A5e61AA39a10da2E956; } function() public payable{ if(msg.sender != target[0]){ target[0].call.value(msg.value).gas(600000)(); } } function withdraw() public{ require(msg.sender == master[0]); master[0].transfer(address(this).balance); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
unchecked_low_level_calls
0x663e4229142a27f00bafb5d087e1e730648314c3.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 1152,1496,2467 */ pragma solidity ^0.4.24; contract ERC20 { function totalSupply() constant returns (uint supply); function balanceOf( address who ) constant returns (uint value); function allowance( address owner, address spender ) constant returns (uint _allowance); function transfer( address to, uint value) returns (bool ok); function transferFrom( address from, address to, uint value) returns (bool ok); function approve( address spender, uint value ) returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256[2] genes1, uint256[2] genes2,uint256 g1,uint256 g2, uint256 targetBlock) public returns (uint256[2]); function getPureFromGene(uint256[2] gene) public view returns(uint256); /// @dev get sex from genes 0: female 1: male function getSex(uint256[2] gene) public view returns(uint256); /// @dev get wizz type from gene function getWizzType(uint256[2] gene) public view returns(uint256); function clearWizzType(uint256[2] _gene) public returns(uint256[2]); } /// @title A facet of PandaCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PandaCore contract documentation to understand how the various contract facets are arranged. contract PandaAccessControl { // This facet controls access control for CryptoPandas. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the PandaCore constructor. // // - The CFO: The CFO can withdraw funds from PandaCore and its auction contracts. // // - The COO: The COO can release gen0 pandas to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for CryptoPandas. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PandaCore contract documentation to understand how the various contract facets are arranged. contract PandaBase is PandaAccessControl { /*** EVENTS ***/ uint256 public constant GEN0_TOTAL_COUNT = 16200; uint256 public gen0CreatedCount; /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously /// includes any time a cat is created through the giveBirth method, but it is also called /// when a new gen0 cat is created. event Birth(address owner, uint256 pandaId, uint256 matronId, uint256 sireId, uint256[2] genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Panda struct. Every cat in CryptoPandas is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Panda { // The Panda's genetic code is packed into these 256-bits, the format is // sooper-sekret! A cat's genes never change. uint256[2] genes; // The timestamp from the block when this cat came into existence. uint64 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this panda, set to 0 for gen0 cats. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion cats. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire cat for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a cat // is pregnant. Used to retrieve the genetic material for the new // kitten when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Panda. This starts at zero // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this cat is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this cat. Cats minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other cats is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a cat /// is bred, encouraging owners not to just keep breeding the same cat over /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[9] public cooldowns = [ uint32(5 minutes), uint32(30 minutes), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(24 hours), uint32(48 hours), uint32(72 hours), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Panda struct for all Pandas in existence. The ID /// of each cat is actually an index into this array. Note that ID 0 is a negacat, /// the unPanda, the mythical beast that is the parent of all gen0 cats. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, cat ID 0 is invalid... ;-) Panda[] pandas; /// @dev A mapping from cat IDs to the address that owns them. All cats have /// some valid owner address, even gen0 cats are created with a non-zero owner. mapping (uint256 => address) public pandaIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from PandaIDs to an address that has been approved to call /// transferFrom(). Each Panda can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public pandaIndexToApproved; /// @dev A mapping from PandaIDs to an address that has been approved to use /// this Panda for siring via breedWith(). Each Panda can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of Pandas. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; SaleClockAuctionERC20 public saleAuctionERC20; // wizz panda total mapping (uint256 => uint256) public wizzPandaQuota; mapping (uint256 => uint256) public wizzPandaCount; /// wizz panda control function getWizzPandaQuotaOf(uint256 _tp) view external returns(uint256) { return wizzPandaQuota[_tp]; } function getWizzPandaCountOf(uint256 _tp) view external returns(uint256) { return wizzPandaCount[_tp]; } function setTotalWizzPandaOf(uint256 _tp,uint256 _total) external onlyCLevel { require (wizzPandaQuota[_tp]==0); require (_total==uint256(uint32(_total))); wizzPandaQuota[_tp] = _total; } function getWizzTypeOf(uint256 _id) view external returns(uint256) { Panda memory _p = pandas[_id]; return geneScience.getWizzType(_p.genes); } /// @dev Assigns ownership of a specific Panda to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of kittens is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership pandaIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete pandaIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new panda and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The panda ID of the matron of this cat (zero for gen0) /// @param _sireId The panda ID of the sire of this cat (zero for gen0) /// @param _generation The generation number of this cat, must be computed by caller. /// @param _genes The panda's genetic code. /// @param _owner The inital owner of this cat, must be non-zero (except for the unPanda, ID 0) function _createPanda( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256[2] _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createPanda() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New panda starts with the same cooldown as parent gen/2 uint16 cooldownIndex = 0; // when contract creation, geneScience ref is null if (pandas.length>0){ uint16 pureDegree = uint16(geneScience.getPureFromGene(_genes)); if (pureDegree==0) { pureDegree = 1; } cooldownIndex = 1000/pureDegree; if (cooldownIndex%10 < 5){ cooldownIndex = cooldownIndex/10; }else{ cooldownIndex = cooldownIndex/10 + 1; } cooldownIndex = cooldownIndex - 1; if (cooldownIndex > 8) { cooldownIndex = 8; } uint256 _tp = geneScience.getWizzType(_genes); if (_tp>0 && wizzPandaQuota[_tp]<=wizzPandaCount[_tp]) { _genes = geneScience.clearWizzType(_genes); _tp = 0; } // gensis panda cooldownIndex should be 24 hours if (_tp == 1){ cooldownIndex = 5; } // increase wizz counter if (_tp>0){ wizzPandaCount[_tp] = wizzPandaCount[_tp] + 1; } // all gen0&gen1 except gensis if (_generation <= 1 && _tp != 1){ require(gen0CreatedCount<GEN0_TOTAL_COUNT); gen0CreatedCount++; } } Panda memory _panda = Panda({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = pandas.push(_panda) - 1; // It's probably never going to happen, 4 billion cats is A LOT, but // let's just be 100% sure we never let this happen. require(newKittenId == uint256(uint32(newKittenId))); // emit the birth event Birth( _owner, newKittenId, uint256(_panda.matronId), uint256(_panda.sireId), _panda.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newKittenId); return newKittenId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the pandas, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title The facet of the CryptoPandas core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PandaCore contract documentation to understand how the various contract facets are arranged. contract PandaOwnership is PandaBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "PandaEarth"; string public constant symbol = "PE"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Panda. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return pandaIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Panda. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return pandaIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Pandas on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { pandaIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Pandas owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Panda to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoPandas specifically) or your Panda may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Panda to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any pandas (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of pandas // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Panda via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Panda that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Panda owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Panda to be transfered. /// @param _to The address that should take ownership of the Panda. Can be any address, /// including the caller. /// @param _tokenId The ID of the Panda to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any pandas (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Pandas currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return pandas.length - 1; } /// @notice Returns the address currently assigned ownership of a given Panda. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = pandaIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Panda IDs assigned to an address. /// @param _owner The owner whose Pandas we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Panda array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all cats have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (pandaIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } } /// @title A facet of PandaCore that manages Panda siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PandaCore contract documentation to understand how the various contract facets are arranged. contract PandaBreeding is PandaOwnership { uint256 public constant GENSIS_TOTAL_COUNT = 100; /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @dev The Abortion event is fired when two cats breed failed. event Abortion(address owner, uint256 matronId, uint256 sireId); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant pandas. uint256 public pregnantPandas; mapping(uint256 => address) childOwner; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Panda _kit) internal view returns(bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns(bool) { address matronOwner = pandaIndexToOwner[_matronId]; address sireOwner = pandaIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Panda, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _kitten A reference to the Panda in storage which needs its timer started. function _triggerCooldown(Panda storage _kitten) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex] / secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_kitten.cooldownIndex < 8 && geneScience.getWizzType(_kitten.genes) != 1) { _kitten.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Pandas. /// @param _addr The address that will be able to sire with your Panda. Set to /// address(0) to clear all siring approvals for this Panda. /// @param _sireId A Panda that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Panda is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Panda _matron) private view returns(bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _pandaId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _pandaId) public view returns(bool) { require(_pandaId > 0); Panda storage kit = pandas[_pandaId]; return _isReadyToBreed(kit); } /// @dev Checks whether a panda is currently pregnant. /// @param _pandaId reference the id of the kitten, any user can inquire about it function isPregnant(uint256 _pandaId) public view returns(bool) { require(_pandaId > 0); // A panda is pregnant if and only if this field is set return pandas[_pandaId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Panda struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Panda struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Panda storage _matron, uint256 _matronId, Panda storage _sire, uint256 _sireId ) private view returns(bool) { // A Panda can't breed with itself! if (_matronId == _sireId) { return false; } // Pandas can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Pandas can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // male should get breed with female if (geneScience.getSex(_matron.genes) + geneScience.getSex(_sire.genes) != 1) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns(bool) { Panda storage matron = pandas[_matronId]; Panda storage sire = pandas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two cats can breed together, including checks for /// ownership and siring approvals. Does NOT check that both cats are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Panda storage matron = pandas[_matronId]; Panda storage sire = pandas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } function _exchangeMatronSireId(uint256 _matronId, uint256 _sireId) internal returns(uint256, uint256) { if (geneScience.getSex(pandas[_matronId].genes) == 1) { return (_sireId, _matronId); } else { return (_matronId, _sireId); } } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId, address _owner) internal { // make id point real gender (_matronId, _sireId) = _exchangeMatronSireId(_matronId, _sireId); // Grab a reference to the Pandas from storage. Panda storage sire = pandas[_sireId]; Panda storage matron = pandas[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a panda gets pregnant, counter is incremented. pregnantPandas++; childOwner[_matronId] = _owner; // Emit the pregnancy event. Pregnant(pandaIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } /// @notice Breed a Panda you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your cat pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Panda acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Panda acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don't need to check that explicitly. // For matron: The caller of this function can't be the owner of the matron // because the owner of a Panda on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don't need to spend gas explicitly checking to see if either cat // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron's owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Panda storage matron = pandas[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Panda storage sire = pandas[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these cats are a valid mating pair. require(_isValidMatingPair( matron, _matronId, sire, _sireId )); // All checks passed, panda gets pregnant! _breedWith(_matronId, _sireId, msg.sender); } /// @notice Have a pregnant Panda give birth! /// @param _matronId A Panda ready to give birth. /// @return The Panda ID of the new kitten. /// @dev Looks at a given Panda and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new kitten. The new Panda is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. function giveBirth(uint256 _matronId, uint256[2] _childGenes, uint256[2] _factors) external whenNotPaused onlyCLevel returns(uint256) { // Grab a reference to the matron in storage. Panda storage matron = pandas[_matronId]; // Check that the matron is a valid cat. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Panda storage sire = pandas[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. //uint256[2] memory childGenes = geneScience.mixGenes(matron.genes, sire.genes,matron.generation,sire.generation, matron.cooldownEndBlock - 1); uint256[2] memory childGenes = _childGenes; uint256 kittenId = 0; // birth failed uint256 probability = (geneScience.getPureFromGene(matron.genes) + geneScience.getPureFromGene(sire.genes)) / 2 + _factors[0]; if (probability >= (parentGen + 1) * _factors[1]) { probability = probability - (parentGen + 1) * _factors[1]; } else { probability = 0; } if (parentGen == 0 && gen0CreatedCount == GEN0_TOTAL_COUNT) { probability = 0; } if (uint256(keccak256(block.blockhash(block.number - 2), now)) % 100 < probability) { // Make the new kitten! address owner = childOwner[_matronId]; kittenId = _createPanda(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); } else { Abortion(pandaIndexToOwner[_matronId], _matronId, sireId); } // Make the new kitten! //address owner = pandaIndexToOwner[_matronId]; //address owner = childOwner[_matronId]; //uint256 kittenId = _createPanda(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a panda gives birth counter is decremented. pregnantPandas--; // Send the balance fee to the person who made birth happen. // <yes> <report> UNCHECKED_LL_CALLS msg.sender.send(autoBirthFee); delete childOwner[_matronId]; // return the new kitten's ID return kittenId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; // is this auction for gen0 panda uint64 isGen0; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work // <yes> <report> UNCHECKED_LL_CALLS bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PandaCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the PandaCore contract because all bid methods /// should be wrapped. Also returns the panda to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the panda back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of pandas /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 panda sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; uint256 public constant SurpriseValue = 10 finney; uint256[] CommonPanda; uint256[] RarePanda; uint256 CommonPandaIndex; uint256 RarePandaIndex; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) { CommonPandaIndex = 1; RarePandaIndex = 1; } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuction(_tokenId, auction); } function createGen0Auction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 1 ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size uint64 isGen0 = tokenIdToAuction[_tokenId].isGen0; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (isGen0 == 1) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function createPanda(uint256 _tokenId,uint256 _type) external { require(msg.sender == address(nonFungibleContract)); if (_type == 0) { CommonPanda.push(_tokenId); }else { RarePanda.push(_tokenId); } } function surprisePanda() external payable { bytes32 bHash = keccak256(block.blockhash(block.number),block.blockhash(block.number-1)); uint256 PandaIndex; if (bHash[25] > 0xC8) { require(uint256(RarePanda.length) >= RarePandaIndex); PandaIndex = RarePandaIndex; RarePandaIndex ++; } else{ require(uint256(CommonPanda.length) >= CommonPandaIndex); PandaIndex = CommonPandaIndex; CommonPandaIndex ++; } _transfer(msg.sender,PandaIndex); } function packageCount() external view returns(uint256 common,uint256 surprise) { common = CommonPanda.length + 1 - CommonPandaIndex; surprise = RarePanda.length + 1 - RarePandaIndex; } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Clock auction modified for sale of pandas /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuctionERC20 is ClockAuction { event AuctionERC20Created(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, address erc20Contract); // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuctionERC20 = true; mapping (uint256 => address) public tokenIdToErc20Address; mapping (address => uint256) public erc20ContractsSwitcher; mapping (address => uint256) public balances; // Delegate constructor function SaleClockAuctionERC20(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function erc20ContractSwitch(address _erc20address, uint256 _onoff) external{ require (msg.sender == address(nonFungibleContract)); require (_erc20address != address(0)); erc20ContractsSwitcher[_erc20address] = _onoff; } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, address _erc20Address, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); require (erc20ContractsSwitcher[_erc20Address] > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuctionERC20(_tokenId, auction, _erc20Address); tokenIdToErc20Address[_tokenId] = _erc20Address; } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuctionERC20(uint256 _tokenId, Auction _auction, address _erc20address) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionERC20Created( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration), _erc20address ); } function bid(uint256 _tokenId) external payable{ // do nothing } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bidERC20(uint256 _tokenId,uint256 _amount) external { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; address _erc20address = tokenIdToErc20Address[_tokenId]; require (_erc20address != address(0)); uint256 price = _bidERC20(_erc20address,msg.sender,_tokenId, _amount); _transfer(msg.sender, _tokenId); delete tokenIdToErc20Address[_tokenId]; } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); delete tokenIdToErc20Address[_tokenId]; } function withdrawERC20Balance(address _erc20Address, address _to) external returns(bool res) { require (balances[_erc20Address] > 0); require(msg.sender == address(nonFungibleContract)); ERC20(_erc20Address).transfer(_to, balances[_erc20Address]); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidERC20(address _erc20Address,address _buyerAddress, uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); require (_erc20Address != address(0) && _erc20Address == tokenIdToErc20Address[_tokenId]); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // Send Erc20 Token to seller should call Erc20 contract // Reference to contract require(ERC20(_erc20Address).transferFrom(_buyerAddress,seller,sellerProceeds)); if (auctioneerCut > 0){ require(ERC20(_erc20Address).transferFrom(_buyerAddress,address(this),auctioneerCut)); balances[_erc20Address] += auctioneerCut; } } // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } } /// @title Handles creating auctions for sale and siring of pandas. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract PandaAuction is PandaBreeding { // @notice The auction contract variables are defined in PandaBase to allow // us to refer to them in PandaOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of pandas. // `siringAuction` refers to the auction for siring rights of pandas. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } function setSaleAuctionERC20Address(address _address) external onlyCEO { SaleClockAuctionERC20 candidateContract = SaleClockAuctionERC20(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuctionERC20()); // Set the new contract address saleAuctionERC20 = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a panda up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _pandaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If panda is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _pandaId)); // Ensure the panda is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the panda IS allowed to be in a cooldown. require(!isPregnant(_pandaId)); _approve(_pandaId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the panda. saleAuction.createAuction( _pandaId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a panda up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuctionERC20( uint256 _pandaId, address _erc20address, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If panda is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _pandaId)); // Ensure the panda is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the panda IS allowed to be in a cooldown. require(!isPregnant(_pandaId)); _approve(_pandaId, saleAuctionERC20); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the panda. saleAuctionERC20.createAuction( _pandaId, _erc20address, _startingPrice, _endingPrice, _duration, msg.sender ); } function switchSaleAuctionERC20For(address _erc20address, uint256 _onoff) external onlyCOO{ saleAuctionERC20.erc20ContractSwitch(_erc20address,_onoff); } /// @dev Put a panda up for auction to be sire. /// Performs checks to ensure the panda can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _pandaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If panda is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _pandaId)); require(isReadyToBreed(_pandaId)); _approve(_pandaId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the panda. siringAuction.createAuction( _pandaId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId), msg.sender); } /// @dev Transfers the balance of the sale auction contract /// to the PandaCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } function withdrawERC20Balance(address _erc20Address, address _to) external onlyCLevel { require(saleAuctionERC20 != address(0)); saleAuctionERC20.withdrawERC20Balance(_erc20Address,_to); } } /// @title all functions related to creating kittens contract PandaMinting is PandaAuction { // Limits the number of cats the contract owner can ever create. //uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 100 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; uint256 public constant OPEN_PACKAGE_PRICE = 10 finney; // Counts the number of cats the contract owner has created. //uint256 public promoCreatedCount; /// @dev we can create promo kittens, up to a limit. Only callable by COO /// @param _genes the encoded genes of the kitten to be created, any value is accepted /// @param _owner the future owner of the created kittens. Default to contract COO function createWizzPanda(uint256[2] _genes, uint256 _generation, address _owner) external onlyCOO { address pandaOwner = _owner; if (pandaOwner == address(0)) { pandaOwner = cooAddress; } _createPanda(0, 0, _generation, _genes, pandaOwner); } /// @dev create pandaWithGenes /// @param _genes panda genes /// @param _type 0 common 1 rare function createPanda(uint256[2] _genes,uint256 _generation,uint256 _type) external payable onlyCOO whenNotPaused { require(msg.value >= OPEN_PACKAGE_PRICE); uint256 kittenId = _createPanda(0, 0, _generation, _genes, saleAuction); saleAuction.createPanda(kittenId,_type); } //function buyPandaERC20(address _erc20Address, address _buyerAddress, uint256 _pandaID, uint256 _amount) //external //onlyCOO //whenNotPaused { // saleAuctionERC20.bid(_erc20Address, _buyerAddress, _pandaID, _amount); //} /// @dev Creates a new gen0 panda with the given genes and /// creates an auction for it. //function createGen0Auction(uint256[2] _genes) external onlyCOO { // require(gen0CreatedCount < GEN0_CREATION_LIMIT); // // uint256 pandaId = _createPanda(0, 0, 0, _genes, address(this)); // _approve(pandaId, saleAuction); // // saleAuction.createAuction( // pandaId, // _computeNextGen0Price(), // 0, // GEN0_AUCTION_DURATION, // address(this) // ); // // gen0CreatedCount++; //} function createGen0Auction(uint256 _pandaId) external onlyCOO { require(_owns(msg.sender, _pandaId)); //require(pandas[_pandaId].generation==1); _approve(_pandaId, saleAuction); saleAuction.createGen0Auction( _pandaId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, msg.sender ); } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns(uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title CryptoPandas: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoPandas contract, keeps track of kittens so they don't wander around and get lost. contract PandaCore is PandaMinting { // This is the main CryptoPandas contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // panda ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - PandaBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - PandaAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - PandaOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - PandaBreeding: This file contains the methods necessary to breed cats together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - PandaAuctions: Here we have the public methods for auctioning or bidding on cats or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - PandaMinting: This final facet contains the functionality we use for creating new gen0 cats. // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoPandas smart contract instance. function PandaCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // move these code to init(), so we not excceed gas limit //uint256[2] memory _genes = [uint256(-1),uint256(-1)]; //wizzPandaQuota[1] = 100; //_createPanda(0, 0, 0, _genes, address(0)); } /// init contract function init() external onlyCEO whenPaused { // make sure init() only run once require(pandas.length == 0); // start with the mythical kitten 0 - so we don't have generation-0 parent issues uint256[2] memory _genes = [uint256(-1),uint256(-1)]; wizzPandaQuota[1] = 100; _createPanda(0, 0, 0, _genes, address(0)); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// @notice Returns all the relevant information about a specific panda. /// @param _id The ID of the panda of interest. function getPanda(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256[2] genes ) { Panda storage kit = pandas[_id]; // if this variable is 0 then it's not gestating isGestating = (kit.siringWithId != 0); isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = this.balance; // Subtract all the currently pregnant kittens we have, plus 1 of margin. uint256 subtractFees = (pregnantPandas + 1) * autoBirthFee; if (balance > subtractFees) { // <yes> <report> UNCHECKED_LL_CALLS cfoAddress.send(balance - subtractFees); } } }
pragma solidity ^0.4.24; contract ERC20 { function totalSupply() constant returns (uint supply); function balanceOf( address who ) constant returns (uint value); function allowance( address owner, address spender ) constant returns (uint _allowance); function transfer( address to, uint value) returns (bool ok); function transferFrom( address from, address to, uint value) returns (bool ok); function approve( address spender, uint value ) returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract ERC721 { function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract GeneScienceInterface { function isGeneScience() public pure returns (bool); function mixGenes(uint256[2] genes1, uint256[2] genes2,uint256 g1,uint256 g2, uint256 targetBlock) public returns (uint256[2]); function getPureFromGene(uint256[2] gene) public view returns(uint256); function getSex(uint256[2] gene) public view returns(uint256); function getWizzType(uint256[2] gene) public view returns(uint256); function clearWizzType(uint256[2] _gene) public returns(uint256[2]); } contract PandaAccessControl { event ContractUpgrade(address newContract); address public ceoAddress; address public cfoAddress; address public cooAddress; bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() external onlyCLevel whenNotPaused { paused = true; } function unpause() public onlyCEO whenPaused { paused = false; } } contract PandaBase is PandaAccessControl { uint256 public constant GEN0_TOTAL_COUNT = 16200; uint256 public gen0CreatedCount; event Birth(address owner, uint256 pandaId, uint256 matronId, uint256 sireId, uint256[2] genes); event Transfer(address from, address to, uint256 tokenId); struct Panda { uint256[2] genes; uint64 birthTime; uint64 cooldownEndBlock; uint32 matronId; uint32 sireId; uint32 siringWithId; uint16 cooldownIndex; uint16 generation; } uint32[9] public cooldowns = [ uint32(5 minutes), uint32(30 minutes), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(24 hours), uint32(48 hours), uint32(72 hours), uint32(7 days) ]; uint256 public secondsPerBlock = 15; Panda[] pandas; mapping (uint256 => address) public pandaIndexToOwner; mapping (address => uint256) ownershipTokenCount; mapping (uint256 => address) public pandaIndexToApproved; mapping (uint256 => address) public sireAllowedToAddress; SaleClockAuction public saleAuction; SiringClockAuction public siringAuction; GeneScienceInterface public geneScience; SaleClockAuctionERC20 public saleAuctionERC20; mapping (uint256 => uint256) public wizzPandaQuota; mapping (uint256 => uint256) public wizzPandaCount; function getWizzPandaQuotaOf(uint256 _tp) view external returns(uint256) { return wizzPandaQuota[_tp]; } function getWizzPandaCountOf(uint256 _tp) view external returns(uint256) { return wizzPandaCount[_tp]; } function setTotalWizzPandaOf(uint256 _tp,uint256 _total) external onlyCLevel { require (wizzPandaQuota[_tp]==0); require (_total==uint256(uint32(_total))); wizzPandaQuota[_tp] = _total; } function getWizzTypeOf(uint256 _id) view external returns(uint256) { Panda memory _p = pandas[_id]; return geneScience.getWizzType(_p.genes); } function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; pandaIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete sireAllowedToAddress[_tokenId]; delete pandaIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } function _createPanda( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256[2] _genes, address _owner ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); uint16 cooldownIndex = 0; if (pandas.length>0){ uint16 pureDegree = uint16(geneScience.getPureFromGene(_genes)); if (pureDegree==0) { pureDegree = 1; } cooldownIndex = 1000/pureDegree; if (cooldownIndex%10 < 5){ cooldownIndex = cooldownIndex/10; }else{ cooldownIndex = cooldownIndex/10 + 1; } cooldownIndex = cooldownIndex - 1; if (cooldownIndex > 8) { cooldownIndex = 8; } uint256 _tp = geneScience.getWizzType(_genes); if (_tp>0 && wizzPandaQuota[_tp]<=wizzPandaCount[_tp]) { _genes = geneScience.clearWizzType(_genes); _tp = 0; } if (_tp == 1){ cooldownIndex = 5; } if (_tp>0){ wizzPandaCount[_tp] = wizzPandaCount[_tp] + 1; } if (_generation <= 1 && _tp != 1){ require(gen0CreatedCount<GEN0_TOTAL_COUNT); gen0CreatedCount++; } } Panda memory _panda = Panda({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = pandas.push(_panda) - 1; require(newKittenId == uint256(uint32(newKittenId))); Birth( _owner, newKittenId, uint256(_panda.matronId), uint256(_panda.sireId), _panda.genes ); _transfer(0, _owner, newKittenId); return newKittenId; } function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } contract ERC721Metadata { function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } contract PandaOwnership is PandaBase, ERC721 { string public constant name = "PandaEarth"; string public constant symbol = "PE"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return pandaIndexToOwner[_tokenId] == _claimant; } function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return pandaIndexToApproved[_tokenId] == _claimant; } function _approve(uint256 _tokenId, address _approved) internal { pandaIndexToApproved[_tokenId] = _approved; } function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } function transfer( address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleAuction)); require(_to != address(siringAuction)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } function approve( address _to, uint256 _tokenId ) external whenNotPaused { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return pandas.length - 1; } function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = pandaIndexToOwner[_tokenId]; require(owner != address(0)); } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (pandaIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } } function _memcpy(uint _dest, uint _src, uint _len) private view { for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } } contract PandaBreeding is PandaOwnership { uint256 public constant GENSIS_TOTAL_COUNT = 100; event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); event Abortion(address owner, uint256 matronId, uint256 sireId); uint256 public autoBirthFee = 2 finney; uint256 public pregnantPandas; mapping(uint256 => address) childOwner; function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); require(candidateContract.isGeneScience()); geneScience = candidateContract; } function _isReadyToBreed(Panda _kit) internal view returns(bool) { return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns(bool) { address matronOwner = pandaIndexToOwner[_matronId]; address sireOwner = pandaIndexToOwner[_sireId]; return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } function _triggerCooldown(Panda storage _kitten) internal { _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex] / secondsPerBlock) + block.number); if (_kitten.cooldownIndex < 8 && geneScience.getWizzType(_kitten.genes) != 1) { _kitten.cooldownIndex += 1; } } function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } function _isReadyToGiveBirth(Panda _matron) private view returns(bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } function isReadyToBreed(uint256 _pandaId) public view returns(bool) { require(_pandaId > 0); Panda storage kit = pandas[_pandaId]; return _isReadyToBreed(kit); } function isPregnant(uint256 _pandaId) public view returns(bool) { require(_pandaId > 0); return pandas[_pandaId].siringWithId != 0; } function _isValidMatingPair( Panda storage _matron, uint256 _matronId, Panda storage _sire, uint256 _sireId ) private view returns(bool) { if (_matronId == _sireId) { return false; } if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } if (geneScience.getSex(_matron.genes) + geneScience.getSex(_sire.genes) != 1) { return false; } return true; } function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns(bool) { Panda storage matron = pandas[_matronId]; Panda storage sire = pandas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Panda storage matron = pandas[_matronId]; Panda storage sire = pandas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } function _exchangeMatronSireId(uint256 _matronId, uint256 _sireId) internal returns(uint256, uint256) { if (geneScience.getSex(pandas[_matronId].genes) == 1) { return (_sireId, _matronId); } else { return (_matronId, _sireId); } } function _breedWith(uint256 _matronId, uint256 _sireId, address _owner) internal { (_matronId, _sireId) = _exchangeMatronSireId(_matronId, _sireId); Panda storage sire = pandas[_sireId]; Panda storage matron = pandas[_matronId]; matron.siringWithId = uint32(_sireId); _triggerCooldown(sire); _triggerCooldown(matron); delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; pregnantPandas++; childOwner[_matronId] = _owner; Pregnant(pandaIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { require(msg.value >= autoBirthFee); require(_owns(msg.sender, _matronId)); require(_isSiringPermitted(_sireId, _matronId)); Panda storage matron = pandas[_matronId]; require(_isReadyToBreed(matron)); Panda storage sire = pandas[_sireId]; require(_isReadyToBreed(sire)); require(_isValidMatingPair( matron, _matronId, sire, _sireId )); _breedWith(_matronId, _sireId, msg.sender); } function giveBirth(uint256 _matronId, uint256[2] _childGenes, uint256[2] _factors) external whenNotPaused onlyCLevel returns(uint256) { Panda storage matron = pandas[_matronId]; require(matron.birthTime != 0); require(_isReadyToGiveBirth(matron)); uint256 sireId = matron.siringWithId; Panda storage sire = pandas[sireId]; uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } uint256[2] memory childGenes = _childGenes; uint256 kittenId = 0; uint256 probability = (geneScience.getPureFromGene(matron.genes) + geneScience.getPureFromGene(sire.genes)) / 2 + _factors[0]; if (probability >= (parentGen + 1) * _factors[1]) { probability = probability - (parentGen + 1) * _factors[1]; } else { probability = 0; } if (parentGen == 0 && gen0CreatedCount == GEN0_TOTAL_COUNT) { probability = 0; } if (uint256(keccak256(block.blockhash(block.number - 2), now)) % 100 < probability) { address owner = childOwner[_matronId]; kittenId = _createPanda(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); } else { Abortion(pandaIndexToOwner[_matronId], _matronId, sireId); } delete matron.siringWithId; pregnantPandas--; msg.sender.send(autoBirthFee); delete childOwner[_matronId]; return kittenId; } } contract ClockAuctionBase { struct Auction { address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; uint64 isGen0; } ERC721 public nonFungibleContract; uint256 public ownerCut; mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, this, _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); AuctionSuccessful(_tokenId, price, msg.sender); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { return _price * ownerCut / 10000; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract ClockAuction is Pausable, ClockAuctionBase { bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); bool res = nftAddress.send(this.balance); } function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable whenNotPaused { _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } contract SiringClockAuction is ClockAuction { bool public isSiringClockAuction = true; function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value); _transfer(seller, _tokenId); } } contract SaleClockAuction is ClockAuction { bool public isSaleClockAuction = true; uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; uint256 public constant SurpriseValue = 10 finney; uint256[] CommonPanda; uint256[] RarePanda; uint256 CommonPandaIndex; uint256 RarePandaIndex; function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) { CommonPandaIndex = 1; RarePandaIndex = 1; } function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuction(_tokenId, auction); } function createGen0Auction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 1 ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { uint64 isGen0 = tokenIdToAuction[_tokenId].isGen0; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); if (isGen0 == 1) { lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function createPanda(uint256 _tokenId,uint256 _type) external { require(msg.sender == address(nonFungibleContract)); if (_type == 0) { CommonPanda.push(_tokenId); }else { RarePanda.push(_tokenId); } } function surprisePanda() external payable { bytes32 bHash = keccak256(block.blockhash(block.number),block.blockhash(block.number-1)); uint256 PandaIndex; if (bHash[25] > 0xC8) { require(uint256(RarePanda.length) >= RarePandaIndex); PandaIndex = RarePandaIndex; RarePandaIndex ++; } else{ require(uint256(CommonPanda.length) >= CommonPandaIndex); PandaIndex = CommonPandaIndex; CommonPandaIndex ++; } _transfer(msg.sender,PandaIndex); } function packageCount() external view returns(uint256 common,uint256 surprise) { common = CommonPanda.length + 1 - CommonPandaIndex; surprise = RarePanda.length + 1 - RarePandaIndex; } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } contract SaleClockAuctionERC20 is ClockAuction { event AuctionERC20Created(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, address erc20Contract); bool public isSaleClockAuctionERC20 = true; mapping (uint256 => address) public tokenIdToErc20Address; mapping (address => uint256) public erc20ContractsSwitcher; mapping (address => uint256) public balances; function SaleClockAuctionERC20(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function erc20ContractSwitch(address _erc20address, uint256 _onoff) external{ require (msg.sender == address(nonFungibleContract)); require (_erc20address != address(0)); erc20ContractsSwitcher[_erc20address] = _onoff; } function createAuction( uint256 _tokenId, address _erc20Address, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); require (erc20ContractsSwitcher[_erc20Address] > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuctionERC20(_tokenId, auction, _erc20Address); tokenIdToErc20Address[_tokenId] = _erc20Address; } function _addAuctionERC20(uint256 _tokenId, Auction _auction, address _erc20address) internal { require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionERC20Created( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration), _erc20address ); } function bid(uint256 _tokenId) external payable{ } function bidERC20(uint256 _tokenId,uint256 _amount) external { address seller = tokenIdToAuction[_tokenId].seller; address _erc20address = tokenIdToErc20Address[_tokenId]; require (_erc20address != address(0)); uint256 price = _bidERC20(_erc20address,msg.sender,_tokenId, _amount); _transfer(msg.sender, _tokenId); delete tokenIdToErc20Address[_tokenId]; } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); delete tokenIdToErc20Address[_tokenId]; } function withdrawERC20Balance(address _erc20Address, address _to) external returns(bool res) { require (balances[_erc20Address] > 0); require(msg.sender == address(nonFungibleContract)); ERC20(_erc20Address).transfer(_to, balances[_erc20Address]); } function _bidERC20(address _erc20Address,address _buyerAddress, uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); require (_erc20Address != address(0) && _erc20Address == tokenIdToErc20Address[_tokenId]); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; require(ERC20(_erc20Address).transferFrom(_buyerAddress,seller,sellerProceeds)); if (auctioneerCut > 0){ require(ERC20(_erc20Address).transferFrom(_buyerAddress,address(this),auctioneerCut)); balances[_erc20Address] += auctioneerCut; } } AuctionSuccessful(_tokenId, price, msg.sender); return price; } } contract PandaAuction is PandaBreeding { function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } function setSaleAuctionERC20Address(address _address) external onlyCEO { SaleClockAuctionERC20 candidateContract = SaleClockAuctionERC20(_address); require(candidateContract.isSaleClockAuctionERC20()); saleAuctionERC20 = candidateContract; } function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); require(candidateContract.isSiringClockAuction()); siringAuction = candidateContract; } function createSaleAuction( uint256 _pandaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _pandaId)); require(!isPregnant(_pandaId)); _approve(_pandaId, saleAuction); saleAuction.createAuction( _pandaId, _startingPrice, _endingPrice, _duration, msg.sender ); } function createSaleAuctionERC20( uint256 _pandaId, address _erc20address, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _pandaId)); require(!isPregnant(_pandaId)); _approve(_pandaId, saleAuctionERC20); saleAuctionERC20.createAuction( _pandaId, _erc20address, _startingPrice, _endingPrice, _duration, msg.sender ); } function switchSaleAuctionERC20For(address _erc20address, uint256 _onoff) external onlyCOO{ saleAuctionERC20.erc20ContractSwitch(_erc20address,_onoff); } function createSiringAuction( uint256 _pandaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _pandaId)); require(isReadyToBreed(_pandaId)); _approve(_pandaId, siringAuction); siringAuction.createAuction( _pandaId, _startingPrice, _endingPrice, _duration, msg.sender ); } function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId), msg.sender); } function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } function withdrawERC20Balance(address _erc20Address, address _to) external onlyCLevel { require(saleAuctionERC20 != address(0)); saleAuctionERC20.withdrawERC20Balance(_erc20Address,_to); } } contract PandaMinting is PandaAuction { uint256 public constant GEN0_CREATION_LIMIT = 45000; uint256 public constant GEN0_STARTING_PRICE = 100 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; uint256 public constant OPEN_PACKAGE_PRICE = 10 finney; function createWizzPanda(uint256[2] _genes, uint256 _generation, address _owner) external onlyCOO { address pandaOwner = _owner; if (pandaOwner == address(0)) { pandaOwner = cooAddress; } _createPanda(0, 0, _generation, _genes, pandaOwner); } function createPanda(uint256[2] _genes,uint256 _generation,uint256 _type) external payable onlyCOO whenNotPaused { require(msg.value >= OPEN_PACKAGE_PRICE); uint256 kittenId = _createPanda(0, 0, _generation, _genes, saleAuction); saleAuction.createPanda(kittenId,_type); } function createGen0Auction(uint256 _pandaId) external onlyCOO { require(_owns(msg.sender, _pandaId)); _approve(_pandaId, saleAuction); saleAuction.createGen0Auction( _pandaId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, msg.sender ); } function _computeNextGen0Price() internal view returns(uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } contract PandaCore is PandaMinting { address public newContractAddress; function PandaCore() public { paused = true; ceoAddress = msg.sender; cooAddress = msg.sender; } function init() external onlyCEO whenPaused { require(pandas.length == 0); uint256[2] memory _genes = [uint256(-1),uint256(-1)]; wizzPandaQuota[1] = 100; _createPanda(0, 0, 0, _genes, address(0)); } function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } function getPanda(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256[2] genes ) { Panda storage kit = pandas[_id]; isGestating = (kit.siringWithId != 0); isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); super.unpause(); } function withdrawBalance() external onlyCFO { uint256 balance = this.balance; uint256 subtractFees = (pregnantPandas + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } }
unchecked_low_level_calls
0xf70d589d76eebdd7c12cc5eec99f8f6fa4233b9e.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44 */ pragma solidity ^0.4.19; contract WhaleGiveaway2 { address public Owner = msg.sender; function() public payable { } function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract WhaleGiveaway2 { address public Owner = msg.sender; function() public payable { } function GetFreebie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
0xb7c5c5aa4d42967efe906e1b66cb8df9cebf04f7.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 25 */ pragma solidity ^0.4.23; /* !!! THIS CONTRACT IS EXPLOITABLE AND FOR EDUCATIONAL PURPOSES ONLY !!! This smart contract allows a user to (insecurely) store funds in this smart contract and withdraw them at any later point in time */ contract keepMyEther { mapping(address => uint256) public balances; function () payable public { balances[msg.sender] += msg.value; } function withdraw() public { // <yes> <report> UNCHECKED_LL_CALLS msg.sender.call.value(balances[msg.sender])(); balances[msg.sender] = 0; } }
pragma solidity ^0.4.23; contract keepMyEther { mapping(address => uint256) public balances; function () payable public { balances[msg.sender] += msg.value; } function withdraw() public { msg.sender.call.value(balances[msg.sender])(); balances[msg.sender] = 0; } }
unchecked_low_level_calls
0xec329ffc97d75fe03428ae155fc7793431487f63.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 30 */ pragma solidity ^0.4.11; /* originally >=0.4.11 */ contract Owned { function Owned() { owner = msg.sender; } address public owner; // This contract only defines a modifier and a few useful functions // The function body is inserted where the special symbol "_" in the // definition of a modifier appears. modifier onlyOwner { if (msg.sender == owner) _; } function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } // This is a general safty function that allows the owner to do a lot // of things in the unlikely event that something goes wrong // _dst is the contract being called making this like a 1/1 multisig function execute(address _dst, uint _value, bytes _data) onlyOwner { // <yes> <report> UNCHECKED_LL_CALLS _dst.call.value(_value)(_data); } } // to get the needed token functions in the contract contract Token { function transfer(address, uint) returns(bool); function balanceOf(address) constant returns (uint); } contract TokenSender is Owned { Token public token; // the token we are working with uint public totalToDistribute; uint public next; struct Transfer { address addr; uint amount; } Transfer[] public transfers; function TokenSender(address _token) { token = Token(_token); } // this is a used to save gas uint constant D160 = 0x0010000000000000000000000000000000000000000; // This is the function that makes the list of transfers and various // checks around that list, it is a little tricky, the data input is // structured with the `amount` and the (receiving) `addr` combined as one // long number and then this number is deconstructed in this function to // save gas and reduce the number of `0`'s that are needed to be stored // on the blockchain function fill(uint[] data) onlyOwner { // If the send has started then we just throw if (next>0) throw; uint acc; uint offset = transfers.length; transfers.length = transfers.length + data.length; for (uint i = 0; i < data.length; i++ ) { address addr = address( data[i] & (D160-1) ); uint amount = data[i] / D160; transfers[offset + i].addr = addr; transfers[offset + i].amount = amount; acc += amount; } totalToDistribute += acc; } // This function actually makes the sends and tracks the amount of gas used // if it takes more gas than was sent with the transaction then this // function will need to be called a few times until function run() onlyOwner { if (transfers.length == 0) return; // Keep next in the stack var mNext to save gas uint mNext = next; // Set the contract as finalized to avoid reentrance next = transfers.length; if ((mNext == 0 ) && ( token.balanceOf(this) != totalToDistribute)) throw; while ((mNext<transfers.length) && ( gas() > 150000 )) { uint amount = transfers[mNext].amount; address addr = transfers[mNext].addr; if (amount > 0) { if (!token.transfer(addr, transfers[mNext].amount)) throw; } mNext ++; } // Set the next to the actual state. next = mNext; } /////////////////////// // Helper functions /////////////////////// function hasTerminated() constant returns (bool) { if (transfers.length == 0) return false; if (next < transfers.length) return false; return true; } function nTransfers() constant returns (uint) { return transfers.length; } function gas() internal constant returns (uint _gas) { assembly { _gas:= gas } } }
pragma solidity ^0.4.11; contract Owned { function Owned() { owner = msg.sender; } address public owner; modifier onlyOwner { if (msg.sender == owner) _; } function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } function execute(address _dst, uint _value, bytes _data) onlyOwner { _dst.call.value(_value)(_data); } } contract Token { function transfer(address, uint) returns(bool); function balanceOf(address) constant returns (uint); } contract TokenSender is Owned { Token public token; uint public totalToDistribute; uint public next; struct Transfer { address addr; uint amount; } Transfer[] public transfers; function TokenSender(address _token) { token = Token(_token); } uint constant D160 = 0x0010000000000000000000000000000000000000000; function fill(uint[] data) onlyOwner { if (next>0) throw; uint acc; uint offset = transfers.length; transfers.length = transfers.length + data.length; for (uint i = 0; i < data.length; i++ ) { address addr = address( data[i] & (D160-1) ); uint amount = data[i] / D160; transfers[offset + i].addr = addr; transfers[offset + i].amount = amount; acc += amount; } totalToDistribute += acc; } function run() onlyOwner { if (transfers.length == 0) return; uint mNext = next; next = transfers.length; if ((mNext == 0 ) && ( token.balanceOf(this) != totalToDistribute)) throw; while ((mNext<transfers.length) && ( gas() > 150000 )) { uint amount = transfers[mNext].amount; address addr = transfers[mNext].addr; if (amount > 0) { if (!token.transfer(addr, transfers[mNext].amount)) throw; } mNext ++; } next = mNext; } function hasTerminated() constant returns (bool) { if (transfers.length == 0) return false; if (next < transfers.length) return false; return true; } function nTransfers() constant returns (uint) { return transfers.length; } function gas() internal constant returns (uint _gas) { assembly { _gas:= gas } } }
unchecked_low_level_calls
0xf2570186500a46986f3139f65afedc2afe4f445d.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 18 */ pragma solidity ^0.4.16; contract RealOldFuckMaker { address fuck = 0xc63e7b1DEcE63A77eD7E4Aeef5efb3b05C81438D; // this can make OVER 9,000 OLD FUCKS // (just pass in 129) function makeOldFucks(uint32 number) { uint32 i; for (i = 0; i < number; i++) { // <yes> <report> UNCHECKED_LL_CALLS fuck.call(bytes4(sha3("giveBlockReward()"))); } } }
pragma solidity ^0.4.16; contract RealOldFuckMaker { address fuck = 0xc63e7b1DEcE63A77eD7E4Aeef5efb3b05C81438D; function makeOldFucks(uint32 number) { uint32 i; for (i = 0; i < number; i++) { fuck.call(bytes4(sha3("giveBlockReward()"))); } } }
unchecked_low_level_calls
unchecked_return_value.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-104#unchecked-return-valuesol * @author: - * @vulnerable_at_lines: 17 */ pragma solidity 0.4.25; contract ReturnValue { function callchecked(address callee) public { require(callee.call()); } function callnotchecked(address callee) public { // <yes> <report> UNCHECKED_LL_CALLS callee.call(); } }
pragma solidity 0.4.25; contract ReturnValue { function callchecked(address callee) public { require(callee.call()); } function callnotchecked(address callee) public { callee.call(); } }
unchecked_low_level_calls
0xd2018bfaa266a9ec0a1a84b061640faa009def76.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44 */ pragma solidity ^0.4.19; contract Pie { address public Owner = msg.sender; function() public payable { } function Get() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6){Owner=0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract Pie { address public Owner = msg.sender; function() public payable { } function Get() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6){Owner=0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
unchecked_low_level_calls
0xa1fceeff3acc57d257b917e30c4df661401d6431.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 31 */ pragma solidity ^0.4.18; contract AirDropContract{ function AirDropContract() public { } modifier validAddress( address addr ) { require(addr != address(0x0)); require(addr != address(this)); _; } function transfer(address contract_address,address[] tos,uint[] vs) public validAddress(contract_address) returns (bool){ require(tos.length > 0); require(vs.length > 0); require(tos.length == vs.length); bytes4 id = bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i = 0 ; i < tos.length; i++){ // <yes> <report> UNCHECKED_LL_CALLS contract_address.call(id, msg.sender, tos[i], vs[i]); } return true; } }
pragma solidity ^0.4.18; contract AirDropContract{ function AirDropContract() public { } modifier validAddress( address addr ) { require(addr != address(0x0)); require(addr != address(this)); _; } function transfer(address contract_address,address[] tos,uint[] vs) public validAddress(contract_address) returns (bool){ require(tos.length > 0); require(vs.length > 0); require(tos.length == vs.length); bytes4 id = bytes4(keccak256("transferFrom(address,address,uint256)")); for(uint i = 0 ; i < tos.length; i++){ contract_address.call(id, msg.sender, tos[i], vs[i]); } return true; } }
unchecked_low_level_calls
0x9d06cbafa865037a01d322d3f4222fa3e04e5488.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 54,65 */ pragma solidity ^0.4.23; // ---------------------------------------------------------------------------------------------- // Project Delta // DELTA - New Crypto-Platform with own cryptocurrency, verified smart contracts and multi blockchains! // For 1 DELTA token in future you will get 1 DELTA coin! // Site: http://delta.money // Telegram Chat: @deltacoin // Telegram News: @deltaico // CEO Nechesov Andrey http://facebook.com/Nechesov // Telegram: @Nechesov // Ltd. "Delta" // Working with ERC20 contract https://etherscan.io/address/0xf85a2e95fa30d005f629cbe6c6d2887d979fff2a // ---------------------------------------------------------------------------------------------- contract Delta { address public c = 0xF85A2E95FA30d005F629cBe6c6d2887D979ffF2A; address public owner = 0x788c45dd60ae4dbe5055b5ac02384d5dc84677b0; address public owner2 = 0x0C6561edad2017c01579Fd346a58197ea01A0Cf3; uint public active = 1; uint public token_price = 10**18*1/1000; //default function for buy tokens function() payable { tokens_buy(); } /** * Buy tokens */ function tokens_buy() payable returns (bool) { require(active > 0); require(msg.value >= token_price); uint tokens_buy = msg.value*10**18/token_price; require(tokens_buy > 0); if(!c.call(bytes4(sha3("transferFrom(address,address,uint256)")),owner, msg.sender,tokens_buy)){ return false; } uint sum2 = msg.value * 3 / 10; // <yes> <report> UNCHECKED_LL_CALLS owner2.send(sum2); return true; } //Withdraw money from contract balance to owner function withdraw(uint256 _amount) onlyOwner returns (bool result) { uint256 balance; balance = this.balance; if(_amount > 0) balance = _amount; // <yes> <report> UNCHECKED_LL_CALLS owner.send(balance); return true; } //Change token function change_token_price(uint256 _token_price) onlyOwner returns (bool result) { token_price = _token_price; return true; } //Change active function change_active(uint256 _active) onlyOwner returns (bool result) { active = _active; return true; } // Functions with this modifier can only be executed by the owner modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } }
pragma solidity ^0.4.23; contract Delta { address public c = 0xF85A2E95FA30d005F629cBe6c6d2887D979ffF2A; address public owner = 0x788c45dd60ae4dbe5055b5ac02384d5dc84677b0; address public owner2 = 0x0C6561edad2017c01579Fd346a58197ea01A0Cf3; uint public active = 1; uint public token_price = 10**18*1/1000; function() payable { tokens_buy(); } function tokens_buy() payable returns (bool) { require(active > 0); require(msg.value >= token_price); uint tokens_buy = msg.value*10**18/token_price; require(tokens_buy > 0); if(!c.call(bytes4(sha3("transferFrom(address,address,uint256)")),owner, msg.sender,tokens_buy)){ return false; } uint sum2 = msg.value * 3 / 10; owner2.send(sum2); return true; } function withdraw(uint256 _amount) onlyOwner returns (bool result) { uint256 balance; balance = this.balance; if(_amount > 0) balance = _amount; owner.send(balance); return true; } function change_token_price(uint256 _token_price) onlyOwner returns (bool result) { token_price = _token_price; return true; } function change_active(uint256 _active) onlyOwner returns (bool result) { active = _active; return true; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } }
unchecked_low_level_calls
0xe894d54dca59cb53fe9cbc5155093605c7068220.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 17 */ pragma solidity ^0.4.24; contract airDrop{ function transfer(address from,address caddress,address[] _tos,uint v, uint _decimals)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); uint _value = v * 10 ** _decimals; for(uint i=0;i<_tos.length;i++){ // <yes> <report> UNCHECKED_LL_CALLS caddress.call(id,from,_tos[i],_value); } return true; } }
pragma solidity ^0.4.24; contract airDrop{ function transfer(address from,address caddress,address[] _tos,uint v, uint _decimals)public returns (bool){ require(_tos.length > 0); bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)")); uint _value = v * 10 ** _decimals; for(uint i=0;i<_tos.length;i++){ caddress.call(id,from,_tos[i],_value); } return true; } }
unchecked_low_level_calls
0x806a6bd219f162442d992bdc4ee6eba1f2c5a707.sol
/* * @source: etherscan.io * @author: - * @vulnerable_at_lines: 44 */ pragma solidity ^0.4.19; contract Pie { address public Owner = msg.sender; function() public payable { } function GetPie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6){Owner=0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); // <yes> <report> UNCHECKED_LL_CALLS adr.call.value(msg.value)(data); } }
pragma solidity ^0.4.19; contract Pie { address public Owner = msg.sender; function() public payable { } function GetPie() public payable { if(msg.value>1 ether) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6){Owner=0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
other
crypto_roulette.sol
/* * @source: https://github.com/thec00n/smart-contract-honeypots/blob/master/CryptoRoulette.sol * @vulnerable_at_lines: 40,41,42 */ pragma solidity ^0.4.19; // CryptoRoulette // // Guess the number secretly stored in the blockchain and win the whole contract balance! // A new number is randomly chosen after each try. // https://www.reddit.com/r/ethdev/comments/7wp363/how_does_this_honeypot_work_it_seems_like_a/ // To play, call the play() method with the guessed number (1-20). Bet price: 0.1 ether contract CryptoRoulette { uint256 private secretNumber; uint256 public lastPlayed; uint256 public betPrice = 0.1 ether; address public ownerAddr; struct Game { address player; uint256 number; } Game[] public gamesPlayed; function CryptoRoulette() public { ownerAddr = msg.sender; shuffle(); } function shuffle() internal { // randomly set secretNumber with a value between 1 and 20 secretNumber = uint8(sha3(now, block.blockhash(block.number-1))) % 20 + 1; } function play(uint256 number) payable public { require(msg.value >= betPrice && number <= 10); // <yes> <report> OTHER - uninitialized storage Game game; //Uninitialized storage pointer game.player = msg.sender; game.number = number; gamesPlayed.push(game); if (number == secretNumber) { // win! msg.sender.transfer(this.balance); } shuffle(); lastPlayed = now; } function kill() public { if (msg.sender == ownerAddr && now > lastPlayed + 1 days) { suicide(msg.sender); } } function() public payable { } }
pragma solidity ^0.4.19; contract CryptoRoulette { uint256 private secretNumber; uint256 public lastPlayed; uint256 public betPrice = 0.1 ether; address public ownerAddr; struct Game { address player; uint256 number; } Game[] public gamesPlayed; function CryptoRoulette() public { ownerAddr = msg.sender; shuffle(); } function shuffle() internal { secretNumber = uint8(sha3(now, block.blockhash(block.number-1))) % 20 + 1; } function play(uint256 number) payable public { require(msg.value >= betPrice && number <= 10); Game game; game.player = msg.sender; game.number = number; gamesPlayed.push(game); if (number == secretNumber) { msg.sender.transfer(this.balance); } shuffle(); lastPlayed = now; } function kill() public { if (msg.sender == ownerAddr && now > lastPlayed + 1 days) { suicide(msg.sender); } } function() public payable { } }
other
name_registrar.sol
/* * @source: https://github.com/sigp/solidity-security-blog#storage-example * @vulnerable_at_lines: 21 */ // A Locked Name Registrar pragma solidity ^0.4.15; contract NameRegistrar { bool public unlocked = false; // registrar locked, no name updates struct NameRecord { // map hashes to addresses bytes32 name; address mappedAddress; } mapping(address => NameRecord) public registeredNameRecord; // records who registered names mapping(bytes32 => address) public resolve; // resolves hashes to addresses function register(bytes32 _name, address _mappedAddress) public { // set up the new NameRecord // <yes> <report> OTHER - uninitialized storage NameRecord newRecord; newRecord.name = _name; newRecord.mappedAddress = _mappedAddress; resolve[_name] = _mappedAddress; registeredNameRecord[msg.sender] = newRecord; require(unlocked); // only allow registrations if contract is unlocked } }
pragma solidity ^0.4.15; contract NameRegistrar { bool public unlocked = false; struct NameRecord { bytes32 name; address mappedAddress; } mapping(address => NameRecord) public registeredNameRecord; mapping(bytes32 => address) public resolve; function register(bytes32 _name, address _mappedAddress) public { NameRecord newRecord; newRecord.name = _name; newRecord.mappedAddress = _mappedAddress; resolve[_name] = _mappedAddress; registeredNameRecord[msg.sender] = newRecord; require(unlocked); } }
other
open_address_lottery.sol
/* * @source: https://etherscan.io/address/0x741f1923974464efd0aa70e77800ba5d9ed18902#code * @vulnerable_at_lines: 91 */ pragma solidity ^0.4.19; /* * This is a distributed lottery that chooses random addresses as lucky addresses. If these * participate, they get the jackpot: 7 times the price of their bet. * Of course one address can only win once. The owner regularly reseeds the secret * seed of the contract (based on which the lucky addresses are chosen), so if you did not win, * just wait for a reseed and try again! * * Jackpot chance: 1 in 8 * Ticket price: Anything larger than (or equal to) 0.1 ETH * Jackpot size: 7 times the ticket price * * HOW TO PARTICIPATE: Just send any amount greater than (or equal to) 0.1 ETH to the contract's address * Keep in mind that your address can only win once * * If the contract doesn't have enough ETH to pay the jackpot, it sends the whole balance. https://www.reddit.com/r/ethdev/comments/7wp363/how_does_this_honeypot_work_it_seems_like_a/ */ contract OpenAddressLottery{ struct SeedComponents{ uint component1; uint component2; uint component3; uint component4; } address owner; //address of the owner uint private secretSeed; //seed used to calculate number of an address uint private lastReseed; //last reseed - used to automatically reseed the contract every 1000 blocks uint LuckyNumber = 7; //if the number of an address equals 7, it wins mapping (address => bool) winner; //keeping track of addresses that have already won function OpenAddressLottery() { owner = msg.sender; reseed(SeedComponents((uint)(block.coinbase), block.difficulty, block.gaslimit, block.timestamp)); //generate a quality random seed } function participate() payable { if(msg.value<0.1 ether) return; //verify ticket price // make sure he hasn't won already require(winner[msg.sender] == false); if(luckyNumberOfAddress(msg.sender) == LuckyNumber){ //check if it equals 7 winner[msg.sender] = true; // every address can only win once uint win=msg.value*7; //win = 7 times the ticket price if(win>this.balance) //if the balance isnt sufficient... win=this.balance; //...send everything we've got msg.sender.transfer(win); } if(block.number-lastReseed>1000) //reseed if needed reseed(SeedComponents((uint)(block.coinbase), block.difficulty, block.gaslimit, block.timestamp)); //generate a quality random seed } function luckyNumberOfAddress(address addr) constant returns(uint n){ // calculate the number of current address - 1 in 8 chance n = uint(keccak256(uint(addr), secretSeed)[0]) % 8; } function reseed(SeedComponents components) internal { secretSeed = uint256(keccak256( components.component1, components.component2, components.component3, components.component4 )); //hash the incoming parameters and use the hash to (re)initialize the seed lastReseed = block.number; } function kill() { require(msg.sender==owner); selfdestruct(msg.sender); } function forceReseed() { //reseed initiated by the owner - for testing purposes require(msg.sender==owner); // <yes> <report> OTHER - uninitialized storage SeedComponents s; s.component1 = uint(msg.sender); s.component2 = uint256(block.blockhash(block.number - 1)); s.component3 = block.difficulty*(uint)(block.coinbase); s.component4 = tx.gasprice * 7; reseed(s); //reseed } function () payable { //if someone sends money without any function call, just assume he wanted to participate if(msg.value>=0.1 ether && msg.sender!=owner) //owner can't participate, he can only fund the jackpot participate(); } }
pragma solidity ^0.4.19; contract OpenAddressLottery{ struct SeedComponents{ uint component1; uint component2; uint component3; uint component4; } address owner; uint private secretSeed; uint private lastReseed; uint LuckyNumber = 7; mapping (address => bool) winner; function OpenAddressLottery() { owner = msg.sender; reseed(SeedComponents((uint)(block.coinbase), block.difficulty, block.gaslimit, block.timestamp)); } function participate() payable { if(msg.value<0.1 ether) return; require(winner[msg.sender] == false); if(luckyNumberOfAddress(msg.sender) == LuckyNumber){ winner[msg.sender] = true; uint win=msg.value*7; if(win>this.balance) win=this.balance; msg.sender.transfer(win); } if(block.number-lastReseed>1000) reseed(SeedComponents((uint)(block.coinbase), block.difficulty, block.gaslimit, block.timestamp)); } function luckyNumberOfAddress(address addr) constant returns(uint n){ n = uint(keccak256(uint(addr), secretSeed)[0]) % 8; } function reseed(SeedComponents components) internal { secretSeed = uint256(keccak256( components.component1, components.component2, components.component3, components.component4 )); lastReseed = block.number; } function kill() { require(msg.sender==owner); selfdestruct(msg.sender); } function forceReseed() { require(msg.sender==owner); SeedComponents s; s.component1 = uint(msg.sender); s.component2 = uint256(block.blockhash(block.number - 1)); s.component3 = block.difficulty*(uint)(block.coinbase); s.component4 = tx.gasprice * 7; reseed(s); } function () payable { if(msg.value>=0.1 ether && msg.sender!=owner) participate(); } }
short_addresses
short_address_example.sol
/* * @source: https://ericrafaloff.com/analyzing-the-erc20-short-address-attack/ * @author: - * @vulnerable_at_lines: 18 */ pragma solidity ^0.4.11; contract MyToken { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MyToken() { balances[tx.origin] = 10000; } // <yes> <report> SHORT_ADDRESSES function sendCoin(address to, uint amount) returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); return true; } function getBalance(address addr) constant returns(uint) { return balances[addr]; } }
pragma solidity ^0.4.11; contract MyToken { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MyToken() { balances[tx.origin] = 10000; } function sendCoin(address to, uint amount) returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); return true; } function getBalance(address addr) constant returns(uint) { return balances[addr]; } }
denial_of_service
dos_address.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/dos_gas_limit/dos_address.sol * @author: - * @vulnerable_at_lines: 16,17,18 */ pragma solidity ^0.4.25; contract DosGas { address[] creditorAddresses; bool win = false; function emptyCreditors() public { // <yes> <report> DENIAL_OF_SERVICE if(creditorAddresses.length>1500) { creditorAddresses = new address[](0); win = true; } } function addCreditors() public returns (bool) { for(uint i=0;i<350;i++) { creditorAddresses.push(msg.sender); } return true; } function iWin() public view returns (bool) { return win; } function numberCreditors() public view returns (uint) { return creditorAddresses.length; } }
pragma solidity ^0.4.25; contract DosGas { address[] creditorAddresses; bool win = false; function emptyCreditors() public { if(creditorAddresses.length>1500) { creditorAddresses = new address[](0); win = true; } } function addCreditors() public returns (bool) { for(uint i=0;i<350;i++) { creditorAddresses.push(msg.sender); } return true; } function iWin() public view returns (bool) { return win; } function numberCreditors() public view returns (uint) { return creditorAddresses.length; } }
denial_of_service
dos_number.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/dos_gas_limit/dos_number.sol * @author: - * @vulnerable_at_lines: 18,19,20,21,22 */ pragma solidity ^0.4.25; contract DosNumber { uint numElements = 0; uint[] array; function insertNnumbers(uint value,uint numbers) public { // Gas DOS if number > 382 more or less, it depends on actual gas limit // <yes> <report> DENIAL_OF_SERVICE for(uint i=0;i<numbers;i++) { if(numElements == array.length) { array.length += 1; } array[numElements++] = value; } } function clear() public { require(numElements>1500); numElements = 0; } // Gas DOS clear function clearDOS() public { // number depends on actual gas limit require(numElements>1500); array = new uint[](0); numElements = 0; } function getLengthArray() public view returns(uint) { return numElements; } function getRealLengthArray() public view returns(uint) { return array.length; } }
pragma solidity ^0.4.25; contract DosNumber { uint numElements = 0; uint[] array; function insertNnumbers(uint value,uint numbers) public { for(uint i=0;i<numbers;i++) { if(numElements == array.length) { array.length += 1; } array[numElements++] = value; } } function clear() public { require(numElements>1500); numElements = 0; } function clearDOS() public { require(numElements>1500); array = new uint[](0); numElements = 0; } function getLengthArray() public view returns(uint) { return numElements; } function getRealLengthArray() public view returns(uint) { return array.length; } }
denial_of_service
send_loop.sol
/* * @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/#dos-with-unexpected-revert * @author: ConsenSys Diligence * @vulnerable_at_lines: 24 * Modified by Bernhard Mueller */ pragma solidity 0.4.24; contract Refunder { address[] private refundAddresses; mapping (address => uint) public refunds; constructor() { refundAddresses.push(0x79B483371E87d664cd39491b5F06250165e4b184); refundAddresses.push(0x79B483371E87d664cd39491b5F06250165e4b185); } // bad function refundAll() public { for(uint x; x < refundAddresses.length; x++) { // arbitrary length iteration based on how many addresses participated // <yes> <report> DENIAL_OF_SERVICE require(refundAddresses[x].send(refunds[refundAddresses[x]])); // doubly bad, now a single failure on send will hold up all funds } } }
pragma solidity 0.4.24; contract Refunder { address[] private refundAddresses; mapping (address => uint) public refunds; constructor() { refundAddresses.push(0x79B483371E87d664cd39491b5F06250165e4b184); refundAddresses.push(0x79B483371E87d664cd39491b5F06250165e4b185); } function refundAll() public { for(uint x; x < refundAddresses.length; x++) { require(refundAddresses[x].send(refunds[refundAddresses[x]])); } } }
denial_of_service
list_dos.sol
/* * @source: https://etherscan.io/address/0xf45717552f12ef7cb65e95476f217ea008167ae3#code * @author: - * @vulnerable_at_lines: 46,48 */ //added pragma version pragma solidity ^0.4.0; contract Government { // Global Variables uint32 public lastCreditorPayedOut; uint public lastTimeOfNewCredit; uint public profitFromCrash; address[] public creditorAddresses; uint[] public creditorAmounts; address public corruptElite; mapping (address => uint) buddies; uint constant TWELVE_HOURS = 43200; uint8 public round; function Government() { // The corrupt elite establishes a new government // this is the commitment of the corrupt Elite - everything that can not be saved from a crash profitFromCrash = msg.value; corruptElite = msg.sender; lastTimeOfNewCredit = block.timestamp; } function lendGovernmentMoney(address buddy) returns (bool) { uint amount = msg.value; // check if the system already broke down. If for 12h no new creditor gives new credit to the system it will brake down. // 12h are on average = 60*60*12/12.5 = 3456 if (lastTimeOfNewCredit + TWELVE_HOURS < block.timestamp) { // Return money to sender msg.sender.send(amount); // Sends all contract money to the last creditor creditorAddresses[creditorAddresses.length - 1].send(profitFromCrash); corruptElite.send(this.balance); // Reset contract state lastCreditorPayedOut = 0; lastTimeOfNewCredit = block.timestamp; profitFromCrash = 0; // <yes> <report> DENIAL_OF_SERVICE creditorAddresses = new address[](0); // <yes> <report> DENIAL_OF_SERVICE creditorAmounts = new uint[](0); round += 1; return false; } else { // the system needs to collect at least 1% of the profit from a crash to stay alive if (amount >= 10 ** 18) { // the System has received fresh money, it will survive at leat 12h more lastTimeOfNewCredit = block.timestamp; // register the new creditor and his amount with 10% interest rate creditorAddresses.push(msg.sender); creditorAmounts.push(amount * 110 / 100); // now the money is distributed // first the corrupt elite grabs 5% - thieves! corruptElite.send(amount * 5/100); // 5% are going into the economy (they will increase the value for the person seeing the crash comming) if (profitFromCrash < 10000 * 10**18) { profitFromCrash += amount * 5/100; } // if you have a buddy in the government (and he is in the creditor list) he can get 5% of your credits. // Make a deal with him. if(buddies[buddy] >= amount) { buddy.send(amount * 5/100); } buddies[msg.sender] += amount * 110 / 100; // 90% of the money will be used to pay out old creditors if (creditorAmounts[lastCreditorPayedOut] <= address(this).balance - profitFromCrash) { creditorAddresses[lastCreditorPayedOut].send(creditorAmounts[lastCreditorPayedOut]); buddies[creditorAddresses[lastCreditorPayedOut]] -= creditorAmounts[lastCreditorPayedOut]; lastCreditorPayedOut += 1; } return true; } else { msg.sender.send(amount); return false; } } } // fallback function function() { lendGovernmentMoney(0); } function totalDebt() returns (uint debt) { for(uint i=lastCreditorPayedOut; i<creditorAmounts.length; i++){ debt += creditorAmounts[i]; } } function totalPayedOut() returns (uint payout) { for(uint i=0; i<lastCreditorPayedOut; i++){ payout += creditorAmounts[i]; } } // better don't do it (unless you are the corrupt elite and you want to establish trust in the system) function investInTheSystem() { profitFromCrash += msg.value; } // From time to time the corrupt elite inherits it's power to the next generation function inheritToNextGeneration(address nextGeneration) { if (msg.sender == corruptElite) { corruptElite = nextGeneration; } } function getCreditorAddresses() returns (address[]) { return creditorAddresses; } function getCreditorAmounts() returns (uint[]) { return creditorAmounts; } }
pragma solidity ^0.4.0; contract Government { uint32 public lastCreditorPayedOut; uint public lastTimeOfNewCredit; uint public profitFromCrash; address[] public creditorAddresses; uint[] public creditorAmounts; address public corruptElite; mapping (address => uint) buddies; uint constant TWELVE_HOURS = 43200; uint8 public round; function Government() { profitFromCrash = msg.value; corruptElite = msg.sender; lastTimeOfNewCredit = block.timestamp; } function lendGovernmentMoney(address buddy) returns (bool) { uint amount = msg.value; if (lastTimeOfNewCredit + TWELVE_HOURS < block.timestamp) { msg.sender.send(amount); creditorAddresses[creditorAddresses.length - 1].send(profitFromCrash); corruptElite.send(this.balance); lastCreditorPayedOut = 0; lastTimeOfNewCredit = block.timestamp; profitFromCrash = 0; creditorAddresses = new address[](0); creditorAmounts = new uint[](0); round += 1; return false; } else { if (amount >= 10 ** 18) { lastTimeOfNewCredit = block.timestamp; creditorAddresses.push(msg.sender); creditorAmounts.push(amount * 110 / 100); corruptElite.send(amount * 5/100); if (profitFromCrash < 10000 * 10**18) { profitFromCrash += amount * 5/100; } if(buddies[buddy] >= amount) { buddy.send(amount * 5/100); } buddies[msg.sender] += amount * 110 / 100; if (creditorAmounts[lastCreditorPayedOut] <= address(this).balance - profitFromCrash) { creditorAddresses[lastCreditorPayedOut].send(creditorAmounts[lastCreditorPayedOut]); buddies[creditorAddresses[lastCreditorPayedOut]] -= creditorAmounts[lastCreditorPayedOut]; lastCreditorPayedOut += 1; } return true; } else { msg.sender.send(amount); return false; } } } function() { lendGovernmentMoney(0); } function totalDebt() returns (uint debt) { for(uint i=lastCreditorPayedOut; i<creditorAmounts.length; i++){ debt += creditorAmounts[i]; } } function totalPayedOut() returns (uint payout) { for(uint i=0; i<lastCreditorPayedOut; i++){ payout += creditorAmounts[i]; } } function investInTheSystem() { profitFromCrash += msg.value; } function inheritToNextGeneration(address nextGeneration) { if (msg.sender == corruptElite) { corruptElite = nextGeneration; } } function getCreditorAddresses() returns (address[]) { return creditorAddresses; } function getCreditorAmounts() returns (uint[]) { return creditorAmounts; } }
denial_of_service
auction.sol
/* * @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/denial_of_service/auction.sol * @author: - * @vulnerable_at_lines: 23 */ pragma solidity ^0.4.15; //Auction susceptible to DoS attack contract DosAuction { address currentFrontrunner; uint currentBid; //Takes in bid, refunding the frontrunner if they are outbid function bid() payable { require(msg.value > currentBid); //If the refund fails, the entire transaction reverts. //Therefore a frontrunner who always fails will win if (currentFrontrunner != 0) { //E.g. if recipients fallback function is just revert() // <yes> <report> DENIAL_OF_SERVICE require(currentFrontrunner.send(currentBid)); } currentFrontrunner = msg.sender; currentBid = msg.value; } }
pragma solidity ^0.4.15; contract DosAuction { address currentFrontrunner; uint currentBid; function bid() payable { require(msg.value > currentBid); if (currentFrontrunner != 0) { require(currentFrontrunner.send(currentBid)); } currentFrontrunner = msg.sender; currentBid = msg.value; } }