# OH Week1 Overview

### HomeWork 架設私有區塊鏈發送第一筆交易

#### Overview

| Name                  | Statement                                                 |
| --------------------- | --------------------------------------------------------- |
| Private Network       | 私有網路會獨立於其他以太坊網路                                           |
| Node                  | 區塊鏈網路的參與者                                                 |
| Bootnode              | 幫助節點尋找 P2P 網路中的其他節點                                       |
| Miner                 | 於區塊裡打包交易的礦工                                               |
| Account               | 使用公私鑰與區塊鏈網路進行互動                                           |
| Genesis Configuration | 是 Geth 工具用來創建創世區塊以及區塊鏈的配置文件，要注意的是 genesis.json 並不是創世區塊本身。 |

#### 1 Install Geth

Windows 在這裡下載並選擇相對應的版本。 <https://geth.ethereum.org/downloads/#>

使用以下指令測試是否安裝成功。

```
geth -h
```

MacOSX 也可以直接使用：

```
brew tap ethereum/ethereum
brew install ethereum

geth --help
```

#### 2 Create Directory Structure

隨意建立一個資料夾，假設叫做「myPrivateChain」，進入該資料夾當作我們目前的專案位置。

#### 3 Create a Genesis Configuration

建立創世區塊的參數用檔案，將其命名為 `genesis.json`。

```
{
    "config": {
        "chainID": 123456,
        "homesteadBlock": 0,
        "eip150Block": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
    "nonce": "0x0000000000000042",
    "difficulty": "0x020",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0x0000000000000000000000000000000000000000",
    "timestamp": "0x00",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "gasLimit": "0x2fefd8",
    "alloc": {
        "0x0000000000000000000000000000000000000001": {
            "balance": "11111111111"
        },
        "0x0000000000000000000000000000000000000002": {
            "balance": "22222222222"
        }
    }
}
```

| 參數             | 介紹                                                                                                             |
| -------------- | -------------------------------------------------------------------------------------------------------------- |
| chainID        | 這裡和等下的 networkid 一樣由 EIP 155 提供 chainid values 的建議來代稱不同網路。只有當 network、chainID、創世區塊配置都相同時，才是同一條鏈。               |
| homesteadBlock | 0 為使用 ethereum homestead 版本。Homestead 是以太坊的第二個主要版本。和 2017 以太坊的拜占庭硬分叉有關                                         |
| eip150Block    | 設為 0 表示私有鏈不會因為 EIP-150 這個提議而分岔                                                                                 |
| eip155Block    | 設為 0 表示私有鏈不會因為 EIP-155 這個提議而分岔                                                                                 |
| eip158Block    | 設為 0 表示私有鏈不會因為 EIP-158 這個提議而分岔                                                                                 |
| nonce          | 用於挖礦的 64bits 隨機數，是與 PoW 機制有關的值                                                                                 |
| difficulty     | 定義了每次挖礦時，最終確定nonce 的難度。詳細內容可見 `Ethash(PoW)` 方法                                                                 |
| mixhash        | 與 nonce 配合用於挖礦，由上一個區塊的部分產生雜湊值                                                                                  |
| coinbase       | 預設為第一個建立挖礦的礦工                                                                                                  |
| timestamp      | 創世區塊的時間戳                                                                                                       |
| parentHash     | 指定了本區塊的上一個區塊Hash，因此創世區塊的 parentHash 是 0                                                                        |
| extraData      | 附加訊息。若是在 Clique(PoA) 機制下，新區塊只能被簽名人（singers）挖掘，區塊鏈生長過程中，可以通過投票來選舉或者免除簽名人。在區塊鏈開始運行時，需要定義一個初始 singer。 詳見 EIP-225。 |
| gasLimit       | 規定該區塊鏈中，交易使用的 gas 的總量上限。某種程度上是規定區塊中能包含的交易信息量總和。                                                                |
| alloc          | 可以從創世區塊預置帳號及其帳號內的金額，單位是 wei 不是 eth                                                                             |

> EIPs 是以太坊中的一套標準，內容會包含 core protocol specifications、用戶 API、和合約標準。

> gas 是一個在與合約進行交易時的內部價格，當我們傳送一些指令給 Ethereum Virtual Machine (EVM) 來進行交易或與合約互動時就會消耗一定量的 gas。

#### 4 Initialize the genesis.json

初始化，輸入以下指令來建立初始區塊。

```javascript
$ geth --datadir <path-to-data-directory> init <path-to-genesis-block>
```

`--datadir data` : 使區塊儲存於 data 資料夾中。

#### 5 Start!

**啟動私有鏈**

```javascript
geth --datadir data --networkid 123456 console
```

networkid 選項後面跟一個數字，指定這個私有鏈的網絡 ID 為 123456。

| 測試網                        | Network |
| -------------------------- | ------- |
| Olympic testnet            | 0       |
| Ethereum Mainnet(frontier) | 1       |
| Ethereum’s Morden testnet  | 2       |
| Ropsten testnet            | 3       |
| Rinkeby testnet            | 4       |
| Rootstock Mainnet          | 30      |
| Rootstock testnet          | 31      |
| Kovan                      | 42      |
| Ethereum Classic Mainnet   | 61      |
| Ethereum Classic testnet   | 62      |

**更多參數（查看 go 之後有些已不能使用）**

```javascript
$ geth --datadir <path-to-data-directory> --networkid 123456  --nodiscover console
```

| 參數            | 介紹                                                                           |
| ------------- | ---------------------------------------------------------------------------- |
| networkid     | 同見上文的 ChainID 部分以及 EIP-155。這邊要注意的是 networkid 與創世區塊的 chainID 必須相等，否則交易時會出現錯誤。 |
| mine          | 啟動挖礦功能                                                                       |
| rpc           | 啟用 HTTP-RPC 通訊協定功能，如此錢包應用程式就可以藉由 http 來連動這個挖礦節點。如果需要佈署智慧合約就需要將其加入。           |
| rpcaddr       | 指定 HTTP-RPC 的 listening interface，預設為 “localhost”                            |
| rpcport       | 指定 HTTP-RPC 的 listening port（網絡監聽連接埠），預設為 8545                               |
| rpcapi        | 指定透過 HTTP-RPC interface 可以適用的 API，預設為 “eth,net,web3”                         |
| rpccorsdomain | 允許跨網域的存取調用，`*`代表來自任何網段。 當使用瀏覽器的錢包或 Solidity 編輯器（Remix）來部署智能合約時，就會需要注意這個部分    |
| nodiscover    | 不搜尋其他網段上的節點。會停止端點搜尋機制，也就是說沒有其他 local 網路裏的節點可以發現我們的節點。                        |
| console       | 這是一個交互式的 Javascript 執行環境，可以在裡面執行 Javascript 的相關程式碼和可以在Geth中執行命令              |

如果要查看更多的參數可以參閱 [Management-APIs](https://geth.ethereum.org/docs/rpc/server)

#### 6 Attach Javascript Console

在這個交互式的 Javascript 執行環境中，`>` 是命令提示符。在這個環境裡也內置了一些用來操作以太坊的 Javascript 對象，可以直接使用這些對象：

| 對象       | 功能               |
| -------- | ---------------- |
| eth      | 操作區塊鏈            |
| net      | 查看 P2P 網路狀態      |
| admin    | 管理節點             |
| miner    | 啟動 & 停止挖礦        |
| personal | 管理帳戶             |
| txpool   | 查看交易內存池          |
| web3     | 包含以上對象，以及單位換算的方法 |

也可以在 GO-Ethereum 的[官方文件](https://geth.ethereum.org/docs/)找到一些指令！

#### 7 Management the Private Chain

查看所有帳號還有帳號存款，accounts 是一個陣列所以也可以使用`[] 陣列取值運算子來取用`，也可以使用新變數來表示帳號字串:

```javascript
> eth.accounts
> eth.getBalance("0x748Cf24cc44Cc20239662eb04dF48ce7Aa019E16")
> myEthereumAddress = eth.accounts[0]
```

查看節點資訊（如果要使用更多 admin 指令可以參閱在 go-ethereum 的 Wiki）：

```javascript
> admin.nodeInfo
```

建立新帳戶，其中的字串為預設密碼：

```javascript
> personal.newAccount("88888888")
```

查看礦工帳號，系統預設礦工帳號會是第一個帳號：

```javascript
> eth.coinbase
```

#### 8 Transfer Ether

解鎖帳號。每次進行交易都需要解鎖帳號，這邊的 `myEthereumAddress` 要填入想要交易的帳號，也可以使用 `eth.accounts[1]` 取用所有帳號裡面的任一個：

```javascript
personal.unlockAccount(eth.accounts[1])
```

之後出現的 `Passphrase` 就是輸入密碼的意思，輸入創建晃時的密碼就可以成功解鎖！

發送交易，我們想要將 `eth.accounts[1]`的錢錢匯給 `myEthereumAddress`：

```javascript
> amount = web3.toWei(10,'ether')
"10000000000000000000"
> eth.sendTransaction({from:eth.accounts[1],to:myEthereumAddress,value:amount})
```

這裡需要注意的是如果匯出帳戶沒錢也會出現錯誤！

此時來查看 `myEthereumAddress` 的餘額：

```javascript
> eth.getBalance(myEthereumAddress)
0
```

發現沒有被處理，此時我們可以查看 txpool 來驗證，發現其中有一條 pending 的交易，pending 就表示已提交但還未被處理的交易。

```javascript
> txpool.status
{
  pending: 1,
  queued: 0
}
```

要使交易被處理就需要挖礦啦，詳情請看下個章節！

#### 9 Mining Time

我們可以使用以下指令來更改礦工帳號，這樣挖礦時錢就會轉到對應的帳號。

```javascript
> miner.setEtherbase(eth.accounts[1])
```

我們可以執行以下步驟，首先語法 `miner.start(1)` 會開始挖礦，最後 `miner.stop()` 就是停止挖礦。

```javascript
> miner.start(1)
> miner.stop()
```

其中 `miner.start(1)` 的參數為 CPU 使用數。

挖礦結束後再回來查看一次 txpool，發現 pending 的交易數量為 0。

```javascript
> txpool.status
{
  pending: 0,
  queued: 0
}
```

再查看一次接受轉帳的帳戶是否有收到匯款了！

```javascript
> web3.fromWei(eth.getBalance(myEthereumAddress),'ether')
```

同時我們也可以使用以下指令來查看區塊數量。

```javascript
eth.blockNumber
```

***

### MetaMask & Other Wallets

* 以太坊上我們可以將加密資產流動分散式帳本運作的過程
* 有別於直接把資產儲存在交易所內
* 以太坊錢包用途

疑問：

* 私鑰安全性
* 某天網站或 APP 關閉

常見的以太坊錢包如下：

* MyEtherWallet
* TrustWallet
* MyCrypto
* Opera
* Jaxx
* MetaMask

***

### NFT Website

NFT 的詳細內容跟原理下禮拜會介紹。這邊主要聚焦在 NFT 網站架設計畫，了解這些網站的設計想法對未來發行 NFT 以及建置 DApp 有很大的幫助，同時也是很好的練習方法！

#### Marketing and Social Media

* 社群媒體連結按鈕
  * Twitter 塑造社群形象，華人常用 Facebook 粉絲專頁。
  * Discord 營造社群氛圍和向心力，以及辦理小型活動。
  * Instagram 提供社群速食內容。
* Roadmap 和 Timeline
  * Interaction VIP/Owners Area
  * 空投
  * 發行實體或虛擬的周邊
  * 下一波或新產品 Mint 的優先權
* 團隊介紹
* Email 訂閱
* 商品輪播 [Example](https://satoshibles.com/) [Example](https://www.fanggang.io/)

#### NFT DataBase

* Gallery or Information DB [Example](https://www.grouchytigersocialclub.com/hunt)
* Leader Board or Rank List

#### dAPP

* Mint Button [Example](https://www.basedfishmafia.com/)
* Login System
* Interaction VIP Area [Example](https://boredapeyachtclub.com/#/)

#### Implement

> 「在 NFT 商品網站中與以太坊錢包 - MetaMask 連動，並且認證錢包登入者是否持有我們發行的 NFT。後讓登入者進入 NFT holders 的專屬 VIP 區域進行互動。」以及「產品上鏈工程 & 實作 Minting dAPP」

```flow
login=>start: Login Flow (Login System)
verify=>operation: Tokens Owner Check Flow  (Verify System)
produce=>operation: Produce NFT Flow
deploy=>operation: Deploy NFT Flow
dApp=>end: Minting dAPP Flow

login->verify->produce->deploy->dApp
```

1. Login Flow (Login System) *（react.js, MetaMask\@onboarding, web3.js）*
2. Tokens Owner Check Flow (Verify System) *（react.js, web3.js, ethers.js, opensea.js）*
3. Produce NFT Flow *（python, JavaScript）*
4. Deploy NFT Flow *（Solidity, Etherscan）*
5. Minting dAPP Flow *（react.js, web3.js, ethers.js, Solidity）*

***

### Reference and Some Resources

論壇、群組或者是學習資源

#### Metamask

* [Introduction | MetaMask Docs](https://docs.metamask.io/guide/)
* [metamask github](https://metamask.github.io/api-playground/api-documentation/#wallet_requestPermissions)

#### JSON RPC

* [JSON RPC · ethereum/wiki Wiki](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction)
* [json-rpc](https://eth.wiki/json-rpc/API)

#### Injecting Web3

* [Breaking Change: No Longer Injecting Web3](https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8)
* [One-click Login with Blockchain: A MetaMask Tutorial](https://www.toptal.com/ethereum/one-click-login-flows-a-metamask-tutorial#the-metamask-browser-extension)

#### Chain Types

* <https://www.abmedia.io/consortium-blockchain>
* <https://www.potatomedia.co/post/34cd8fac-94d7-44bf-b532-3426b79f31a7>

#### PoS, PoW, PoA

* <https://www.itread01.com/content/1547701572.html>
* <https://matters.news/@BitGinko/po-w-po-s-po-a-po-xxx-%E5%85%B1%E8%AD%98%E6%A9%9F%E5%88%B6%E7%9A%84%E6%B7%B1%E5%85%A5%E6%8E%A2%E8%A8%8E-%E4%BA%8C-bafyreidounsizvez6wwr244tkwzixponesv4qroskpfbqhrd4b4l6phpzu>
* <https://ictjournal.itri.org.tw/Content/Messagess/contents.aspx?MSID=744257557510131250\\&MmmID=654304432061644411>
* <https://0xzx.com/zh-tw/201911202124375577.html>
* <http://blog.udn.com/oec1020/134016099>

***

#### 論壇

* <https://ethereum.stackexchange.com/>
* Quora
* Chainlink
* StackOverflow
* programmerall.com
* programmer.help
* <https://news.ycombinator.com/news>

***

#### HW Reference:

* <http://netkiller.sourceforge.net/blockchain/ethereum/genesis.json.html>
* <https://dotblogs.com.tw/explooosion/2018/07/29/172031>
* <https://medium.facilelogin.com/build-your-own-blockchain-b8eaeea2f891>

***

* <https://www.books.com.tw/products/0010798325>
* <https://learnblockchain.cn/2018/03/18/create\\_private\\_blockchain/>
* <https://medium.com/samumu-clan/%E7%94%A8-geth-%E6%9E%B6%E8%A8%AD%E7%A7%81%E6%9C%89%E9%8F%88-41a2baa0efd8>
* <https://medium.com/swlh/how-to-set-up-a-private-ethereum-blockchain-c0e74260492c>
* <https://www.cnblogs.com/soowin/p/14328195.html>

***

* <https://ithelp.ithome.com.tw/2020ironman/articles/2255?page=1>
* <https://medium.com/swlh/how-to-set-up-a-private-ethereum-blockchain-c0e74260492c>
* <https://www.section.io/engineering-education/how-to-build-your-own-private-blockchain/>
* <https://medium.com/samumu-clan/%E7%94%A8-geth-%E6%9E%B6%E8%A8%AD%E7%A7%81%E6%9C%89%E9%8F%88-41a2baa0efd8>
* <https://medium.facilelogin.com/build-your-own-blockchain-b8eaeea2f891>
* <https://souptacular.gitbooks.io/ethereum-tutorials-and-tips-by-hudson/content/private-chain.html>
* <https://www.antiersolutions.com/>

***

**Windows**

* <https://medium.com/%E4%B8%80%E5%80%8B%E5%AE%B9%E6%98%93%E5%81%A5%E5%BF%98%E7%9A%84%E5%A4%A7%E5%AD%B8%E7%94%9F/5%E5%88%86%E9%90%98%E5%BB%BA%E7%AB%8B%E4%BB%A5%E5%A4%AA%E5%9D%8A%E7%A7%81%E6%9C%89%E9%8F%88-%E4%BB%A5poa%E5%85%B1%E8%AD%98%E7%82%BA%E4%BE%8B-part-1-c6e9daad71a7>
* <https://merehead.com/blog/how-to-create-private-ethereum-blockchain/>
* <https://programmer.help/blogs/build-ethereum-private-chain-windows.html>

**Mac OS X**

* <https://learnblockchain.cn/2018/03/18/create\\_private\\_blockchain/>
* <https://notes.andywu.tw/2018/%E5%BB%BA%E7%AB%8B%E4%BB%A5%E5%A4%AA%E5%9D%8A%E7%A7%81%E6%9C%89%E9%8F%88%E4%B8%80/>
* <https://programmerall.com/article/3909456580/>
* <https://github.com/chafey/ethereum-private-network>

**UNIX - GNU/Linux, Ubuntu**

* <https://medium.com/@pradeep\\_thomas/how-to-setup-your-own-private-ethereum-network-f80bc6aea088>
* <https://ithelp.ithome.com.tw/articles/10203475>
* <https://arctouch.com/blog/how-to-set-up-ethereum-blockchain/>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chihaolu.gitbook.io/kryptocamp-office-hour/season-1-2022-1/oh-week1-overview.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
