Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: P15 ETH Accounts & P21 Proof of Stake (POS) & P23 The DAO Incident #48

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ This course focuses on the fundamental concepts and implementation principles of

### Ethereum
14. **[Overview](./ETH/Overview.md)**
15. **Accounts**
15. **[Accounts](./src/ETH/Accounts.md)**
16. **State Trees**
17. **Transaction and Receipt Trees**
18. **GHOST Protocol**
19. **Mining Algorithms**
20. **[Difficulty Adjustment](./src/ETH/difficulty-adjustment.md)**
21. **Proof of Stake (PoS)**
21. **[Proof of Stake (PoS)](./src/ETH/proof-of-stake(pos).md)**
22. **Smart Contracts**
23. **The DAO Incident**
23. **[The DAO Incident](./src/ETH/the-dao-incident.md)**
24. **Reflections on Ethereum**
25. **Ethereum Classic (ETC)**

Expand Down
59 changes: 59 additions & 0 deletions src/ETH/Accounts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# P15 - Accounts

## Account-Based Ledger
Comparing Bitcoin and Ethereum:
- Bitcoin uses a **transaction-based ledger**, where account balances are inferred through `UTXO`.
- Ethereum uses an **account-based ledger**, similar to a banking system, where accounts directly store `balance` states.

Differences in transfer mechanisms:
- Bitcoin: When transferring from account B to C, the source of coins must be specified, and every `UTXO` must be entirely spent at once, so any remaining coins should be transferred back to another self-owned account.
- Ethereum: The source of coins during a transfer is the `balance` state of the account, as the account includes the `balance` state, so it does not need to be entirely spent at once.

```txt
Transaction-based Ledger Account-Based Ledger
┌────────────────────────────────────────┐ ┌───────────────────────────────────┐
│ ┌──────────────────┐ │ │ │
│ │ │ │ │ │
│┌─────▼───────┐ ┌┼─────────────┐│ │┌─────────────┐ ┌─────────────┐ │
││A───►B(10BTC)│ │B─┬──►C(3BTC) ││ ││A───►B(10ETH)│ │B───►C(3ETH) │ │
││ │ │ │ ││ ││ │ │ │ │
││ │ │ └──►B'(7BTC)││ ││ │ │ │ │
│└─────────────┘ └──────────────┘│ │└─────────────┘ └─────────────┘ │
└────────────────────────────────────────┘ └───────────────────────────────────┘
Comment on lines +14 to +22

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you sure?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for sure. The arrow from B to A indicates the source of the coin, which is feature of the UTXO model but unnecessary for the account-based model.

```
**Advantages** of the account-based model: No need to consider the source of coins, inherently preventing double-spending attacks.

## Replay Attack
Although the **account-based ledger** avoids double-spending attack, there is still a risk of **replay attack**.

**Replay Attack**: After transferring from account B to C, C maliciously broadcasts B's transaction later, resulting in B being debited twice.

**How to prevent Replay Attack?**

1. Add a `nonce` state to the account as a transaction counter, recording the number of transactions posted by the account, the `nonce` becomes part of the transaction and is signed during transfers.
2. Transactions with a `nonce` less than or equal to the account's current `nonce` are rejected.

```txt
┌─────────────────┐
│ B -> C(10ETH) │
│ │
│ nonce = 21 │
│ │
│ signed by A │
└─────────────────┘
```

## Smart Contract Accounts

Two types of accounts exist in the Ethereum system:
1. Externally Owned Accounts: Controlled by user's public-private key pairs, these accounts have a `balance` and a `nonce`.
2. **Smart Contract Accounts**: In addition to `balance` and `nonce`, these accounts include `code` and `storage`.
- When a contract is created, it returns an address that can be used to make calls to the contract. During these calls, the `code`remains unchanged.
- Contract Accounts can't initiate a transaction on their own, all transactions must be initiated by external accounts.
- Contract Accounts also have a `nonce`, which records the number of times the contract has been invoked.
- A contract can call another contract.

## Why Ethereum use Account-Based Ledger?
Ethereum is designed to support smart contracts, which require stable account addresses for execution.

Therefore, the account-based ledger is more suitable than the transaction-based ledger.
135 changes: 135 additions & 0 deletions src/ETH/proof-of-stake(pos).md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# P21 Proof Of Stake (POS)

## Electrical Energy of Pow

1. [Bitcoin Electrical Energy Consumption:](https://digiconomist.net/bitcoin-energy-consumption): 172 terawatt-hours (TWh) per year, equivalent to Poland’s annual electricity consumption.
2. [Bitcoin Electrical Energy Consumption:](https://digiconomist.net/ethereum-energy-consumption): 93 TWh per year when using **proof-of-work**(POW) before switching to **proof-of-stake**(POS).

> 1Twh = 10^9 Kwh

## Description of Proof of stake

In POW, mining equipment is purchased with external currency, and the miner's computational power is essentially determined by how much money they spend. In contrast, **proof-of-stake** skips mining equipment and directly stakes tokens for voting to reach consensus, which is sometimes referred to as **virtual mining**.

Coin distribution with proof-of-stake involves:
1. Reserving some coins for developers.
2. Selling some coins to fund development.

Once the system reaches a stable state, individuals can stake and vote according to the amount of coins they hold.

Advantages of POS over POW:
1. Energy efficiency leading to reduced greenhouse gas emissions.
2. Small computational power in POW is susceptible to malicious attacks (AltCoin Infanticide), where POW attacks rely on external computational resources; however, POS attacks can only be sourced from within the cryptographic system.

### Hybrid of Pos and Pow

POW and POS can be used in combination. The more coins you hold, the easier it is to mine a block with POW. However, its disadvantage is that it is easiest for people who hold the most coins to mine.

To avoid this, **Proof of Deposit** needs to be used for optimization: the pledged currency has a certain lock-up period and cannot be reused. For example, when mining the current block, a certain amount of coins is invested to reduce the difficulty, but when mining the next block, the coins invested in the previous block cannot be used and need to wait for a certain period of time before they can be used again.

### Nothing At Stake
A major challenge in the design of proof-of-stake systems: Nothing At Stake.

In proof-of-work(PoW) system, miners must select only one chain for mining during a fork due to the computational demands of mining. However, in proof-of-stake system, validators can stake on multiple forked chains without incurring computational costs. Consequently, validators can earn rewards regardless of which chain ultimately becomes the longest and valid one, but it will be harmful to the system and not conducive to reaching consensus.

```txt

┌──┐ ┌──┐
┌──┐◄──┬──┐◄──┬──┐◄─┴──┘◄┴──┘
└──┘ └──┘ └──┘◄─┬──┐ ▲
└──┘ │
▲ │
└─stake
```

## Casper
The Proof of Stake protocol that Ethereum is planning to adopt is `Casper the Friendly Finality Gadget (FFG)`, which will be initially hybrid with POW to provide Finality to POW.


### Finality
`Finality` is the property that there are blocks in the chain that are guaranteed never to be reverted: they will be part of the chain forever.

In Ethereum’s system, Casper FFG achieves the `Finality`.

### Validator
Casper introduces `Validator`, users who must deposit a certain amount of Ether as bonds to become `Validator`; this bond is locked by the system. The amount of the bond determines the weight of their vote.

A Validator’s responsibility is to facilitate consensus within the system by voting for the longest valid chain.

### Epochs and checkpoints

1. Epochs: While still using POW, mining will occur, and every 100 blocks will form an `epoch`.
2. Checkpoint: To ensure `Validator` vote on the same block, a checkpoint is used as a reference point; it occurs at the first slot of every epoch.

### Two-phase commit

The voting process utilizes the two-phase commit concept:
1. Prepare message
2. Commit message

In the original Casper version, both rounds of voting were on the same `checkpoint`, requiring over two-thirds of Validators to agree in each round for consensus to be reached.

```txt
│◄─── epoch ──────►│
│ │
│ │
┌──┐◄┬──◄┼┬──◄── ◄─┬──◄──┬──◄┼┬──◄──┬──┐◄┬──┐
└──┘ └──┘│└──┘ ... └──┘ └──┘│└──┘ └──┘ └──┘
│ │
│ │prepare 2/3
│ │commit 2/3
```

In the actual system, the distinction between these two messages is not made, and the epoch has been reduced from one hundred blocks to fifty blocks.

Each epoch requires only one round of voting; this round serves as the `commit message` for the previous epoch and the `prepare message` for the next epoch.

After two consecutive epochs of voting, with both receiving more than 2/3 majority, the transactions of the first epoch are considered valid, achieving `Finality`.

```txt
epoch │◄───epoch────►│◄────epoch────►│
│ │ │
│ │ │
│ │ │
┌───┐◄─┼┬──◄── ◄─┬──◄─┼─┬──◄── ◄─┬──┐◄┼┬──┐
└───┘ │└──┘ ... └──┘ │ └──┘ ... └──┘ │└──┘
│ │ │
│ │ │
│ │ │
2/3 2/3 2/3
```

### Validator Rewards and Penalties
What are the benefits for `Validator` participating in this voting process?

Validators are rewarded for fulfilling their responsibilities.

However, if a Validator:

1. Fails to vote when required, a portion of the bond will be deducted.
2. Votes incorrectly for conflicting chains, all the bonded funds will be seized, and the seized funds will be destroyed.

Each Validator has a specific term limit; upon expiry, they enter a waiting period. During this period, other nodes can report and reveal any misconduct. If no misconduct is found during this waiting period, the Validator can retrieve their bond and rewards.


### Security
The Casper protocol can set a `checkpoint` for a certain state of a blockchain that is mined. Is this `checkpoint` absolutely secure? In other words, can the `Finality` achieved through validator votes be overturned?

If the malicious attacker is just a miner, they cannot overturn it; however, if there are a large number of `Validators` conducting a `Nothing At Stake attack`, it could lead to the system being tampered with.

Ethereum envisions that, over time, mining rewards will gradually decrease while proof of stake rewards will gradually increase, thus achieving the transition from POW to PoS, ultimately eliminating the need for mining of pow.

## Delegated Proof of Stake

Another consensus mechanism is `DPOS`: **Delegated Proof of Stake**.

For instance, in EOS, 21 super nodes are selected first by a voting mechanism, and then these super nodes generate blocks.

## Is Mining Energy Consumption Bad?

Is the high electricity consumption associated with mining necessarily a negative aspect? Some argue otherwise.

1. Electricity is challenging to store and transport; mining provides a means to convert electricity into currency.
2. Unused clean energy is difficult to return to the main grid: mining with clean energy effectively helps utilize surplus electricity.

Mining’s environmental impact is limited and can drive local economic development.
81 changes: 81 additions & 0 deletions src/ETH/the-dao-incident.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# P23 The DAO Incident

## DAO
In the previous section, we discussed the principles of **reentrancy attacks**. In this section, we will explore a real-world case that is famous in Ethereum's history and led to a split in the Ethereum network.

Bitcoin introduced the concept of decentralized currency, while Ethereum brought forth decentralized contracts. This gave rise to the idea of **Decentralized Everything**, The concept of `DAO` emerged in this context.

`DAO` stands for **Decentralized Autonomous Organization**. In the blockchain world, the rules and regulations of an organization are written in code and maintained through the consensus protocol of the blockchain.

## The DAO

In May 2016, a crowdfunding investment project known as `The DAO` was launched.

`The DAO` is a decentralized crowdfunding investment fund, which should not be confused with the general concept of `DAO`.

Unlike traditional venture capital funds, `The DAO` operated as a democratic investment fund. Within a month, it raised $150 million worth of Ether, achieving a rare speed and scale in crowdfunding.

## How The DAO Works

Here’s how `The DAO` works:

1. **Mechanism**: It is a crowdfunding investment fund where the invested money is raised through crowdfunding on the blockchain. Essentially, It runs as a smart contract on Ethereum.
2. **Investment Decisions**: To participate in investments, sending `ETH` to the smart contract in exchange for `The DAO` tokens, then investment decisions are made through voting using these tokens.
3. **Profit Distribution**: Profits are distributed according to the rules set in the smart contract.

## SplitDAO

The purpose of `SplitDAO`:

1. **Establishing `ChildDAO`**: Some investors believed certain projects were worth funding but lacked majority support. In such cases, they could split off from `The DAO` to form their own `Child DAO`. After this split, their tokens would be converted into `ETH` and remain in the `Child DAO`. There was a 28-day lock-up period after the split, which provided a buffer time to address potential future attacks.

2. **Retrieving Investment Returns**: `The DAO` did not have a direct function to convert tokens back to Ether. However, investors could retrieve their funds through the `ChildDAO` created via `SplitDAO` .

## The Hacker Attack

Unfortunately, `The DAO` only survived for three months due to the hacker attack.

The hacker exploited a vulnerability in the implementation of `SplitDAO`.

Here’s a snippet of the relevant code:

```solidity
function splitDAO(
uint _proposalID,
address _newCurator
) noEther onlyTokenholders returns (bool _success) {
...
// Burn DAO Tokens
Transfer(msg.sender, 0, balances[msg.sender]);
withdrawRewardFor(msg.sender);
totalSupply -= balances[msg.sender];
balances[msg.sender] = 0;
paidOut[msg.sender] = 0;
return true;
}
```

In the `SplitDAO` code, the transfer occurs before the account balance is reset to zero. This is the **reentrancy attack vulnerability** discussed in the previous section, and hackers exploited this vulnerability to carry out the reentrancy attack.

> The correct approach would have been to zero out the account balance first and then perform the transfer.

## Remedial Measures

The Ethereum community was divided into two camps:

1. **Rollback Transactions**: From the perspective of protecting investors' interests, the Ethereum team supported remedial measures.

2. **Maintain the status**: Some argued that blockchains are immutable; the issue lay with the smart contract, not Ethereum itself.

Ultimately, the Ethereum community chose to rollback transactions. The remedy involved first prohibiting related transactions through a soft fork, then executing a hard fork to rollback the transactions.

1. **Soft Fork**: A rule has been added through software upgrade, disallowing any transactions involving accounts related to the `The DAO` fund. However, this upgrade contained a bug: it did not charge `gas fees` for illegal transactions, leading to low-cost attacks. Consequently, the version was rolled back, and the soft fork was deemed a failure.

2. **Hard Fork**: The tokens of `The DAO` were transferred to a new smart contract, which had the sole function of converting tokens to `ETH`. This transfer was automatically executed upon mining the 1,920,000th block.

A vote was held between supporters and opponents of the hard fork, ultimately favoring the hard fork. However, those against it chose to continue mining on the old chain.

After the hard fork, the new chain retained the Ether (ETH) symbol, while the old chain's Ether became known as Ethereum Classic (ETC).

Because both chains shared the same historical ledger and private keys, replay attacks were possible. To prevent this, a unique `chainID` was introduced to differentiate between the new and old chains.

2 changes: 1 addition & 1 deletion src/Introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ This course focuses on the fundamental concepts and implementation principles of

### Ethereum
14. **Overview**
15. **Accounts**
15. **[Accounts](./ETH/Accounts.md)**
16. **State Trees**
17. **Transaction and Receipt Trees**
18. **GHOST Protocol**
Expand Down
3 changes: 3 additions & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@
# ETH

- [Difficulty Adjustment](ETH/difficulty-adjustment.md)
- [Accounts](ETH/Accounts.md)
- [Proof Of Stake](ETH/proof-of-stake(pos).md)
- [The DAO Incident](ETH/the-dao-incident.md)