童俊維
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 區塊鏈基礎 : 視覺化 區塊鏈 ## 視覺化 區塊鏈 首先先來看最後呈現效果 ![](https://hackmd.io/_uploads/S1aoOuVy6.png) 成果網址 : https://block-chain-simulation.onrender.com/ GitHub專案 : https://github.com/weiawesome/block_chain_simulation (如果還喜歡可以在 GitHub 給我個 Star ★ ) 其實也費我不小功夫,接下來就以下幾點開始專案 1. UI 規劃 與 系統架構設計 2. 區塊 物件設計 3. 相關加密函式撰寫 4. 網站使用教學 ## UI 規劃 與 專案架構設計 **UI 規劃上** ![](https://hackmd.io/_uploads/BJWp_YVya.png) * 藍色區域放區塊鏈的 "區塊" * 紅色永遠在最後一個 作用是 增加區塊 * 區塊上 橫行最多3個 依序增加 多的換行 * 綠色區塊則放置 設定與說明 **專案架構上** 語言與框架 就採用 React.js 加上 TypeScript 專案架構的組織上 : ``` ├── src │ ├── App.tsx │ ├── App.css │ │ │ ├── models │ │ ├── block.ts │ │ │ ├── utils │ ├── encrypt.ts │ ├── other files ``` * App.tsx 與 App.css 處理頁面呈現 * models/block.ts 作為 區塊物件 * utils/encrypt.ts 處理加密相關業務 接下來重點 去實踐以上設計 ## 區塊 物件設計 **檔案位置存放在 "src/models/block.ts"** 首先 從 UML 文件 設計開始 ![](https://hackmd.io/_uploads/SyFpDqE1T.png) (此份UML圖檔由 [PlantUML](http://www.plantuml.com/plantuml/uml/SyfFKj2rKt3CoKnELR1Io4ZDoSa70000) 所生成) * Block(區塊) 與 BlockTop(區塊標頭) 為 一對一關係 * Block(區塊) 與 Transaction(交易內容) 為 一對多關係 **Block(區塊) 物件:** | 屬性名稱 | 屬性作用 |方法名稱 | 方法作用 | | -------- | -------- |-------- | -------- | | block_top | 區塊標頭|setMarkleRoot | 計算區塊哈希 | |transaction|所有交易內容|checkDifficulty|檢查 區塊哈希 是否符合 區塊難度| |block_hash|區塊哈希值|addTransaction|增加交易| |status|是否已完成挖掘| **BlockTop(區塊標頭) 物件:** | 屬性名稱 | 屬性作用 | 方法名稱 | 方法作用 | | -------- | -------- | -------- | -------- | |version|版本號|setBlockHash| 計算 Markle根 | |previous_hash|前一區塊哈希值|toString|物件轉字串方法| |time_stamp|時間戳記| |difficulty|區塊難度| |nonce|隨機數| |markle_root|Markle根| **Transaction(交易) 物件:** | 屬性名稱 | 屬性作用 | 方法名稱 | 方法作用 | | -------- | -------- | -------- | -------- | |id|交易哈希值| signature | 為此筆交易簽名 | |from|交易發起者(地址)|verify|驗證此筆交易的簽名| |to|交易接收者(地址)| |amount|交易金額| |fees|給予礦工手續費| ### 詳細程式碼環節 **Block 物件** ```typescript export class Block { // 當前是否已完成挖掘 true->已挖掘完成 false->未挖掘 status:boolean; // 區塊標頭 block_top: BlockTop; // 所有交易內容 transaction:Transaction[]; // 區塊哈希值 block_hash:string; // 建構子 (透過傳遞 前區塊哈希值 初始化 Block 物件) constructor(hash:string) { this.status=false; this.block_top=new BlockTop(hash); this.transaction=[]; this.block_top.setMarkleRoot(this.transaction); this.block_hash="" this.setBlockHash(); } // 檢查 區塊哈希值 是否符合 區塊難度 checkDifficulty(){ for (let i=0;i<this.block_top.difficulty;i++){ if(this.block_hash[i]!=="0"){ this.status=false; return false; } } this.status=true; return true; } // 計算 區塊哈希值 setBlockHash(){ this.block_hash=Hash_SHA256(Hash_SHA256(this.block_top.toString())); } // 增加交易 addTransaction(transaction:Transaction):boolean{ for (let i=0;i<this.transaction.length;i++){ if(this.transaction[i].id===transaction.id){ return false; } } this.transaction.push(transaction); this.block_top.setMarkleRoot(this.transaction); this.setBlockHash(); this.status=false; return true; } } ``` **BlockTop 物件** ```typescript export class BlockTop{ // 版本號 version:string; // 前一區塊哈希值 previous_hash:string; // 時間戳記 time_stamp:string; // 區塊難度 difficulty:number; // 隨機數 nonce:bigint; // Markle根 markle_root:string; // 建構子 (透過 前區塊哈希值 進行初始化 BlockTop 物件) constructor(hash:string) { this.version="v1"; this.previous_hash=hash; let time=new Date(); this.time_stamp=time.toLocaleString(); this.difficulty=1; this.nonce= BigInt(0); this.markle_root=""; } // 物件轉為字串方法 toString(){ return this.version.toString()+this.previous_hash.toString()+this.time_stamp+this.difficulty+this.nonce+this.markle_root; } // 計算 Markle根 setMarkleRoot(transactions:Transaction[]){ if (transactions.length===0){ this.markle_root=Hash_SHA256(""); return } let tmpRoots:string[]=[]; for (let i=0;i<transactions.length;i++){ tmpRoots.push(Hash_SHA256(transactions[i].toString())); } while (tmpRoots.length>1){ for (let i=0; i<tmpRoots.length; i++){ if (i%2===0){ if(i+1<tmpRoots.length){ tmpRoots[i/2]=Hash_SHA256(tmpRoots[i]+tmpRoots[i+1]); } else{ tmpRoots[i/2]=Hash_SHA256(tmpRoots[i]); } } } if (tmpRoots.length%2===0){ tmpRoots=tmpRoots.slice(0,tmpRoots.length/2) } else{ tmpRoots=tmpRoots.slice(0,tmpRoots.length/2+1) } } this.markle_root=tmpRoots[0]; } } ``` **Transaction 物件** ```typescript export class Transaction{ // 交易哈希值 id:string; // 交易發起者 from: string; // 交易接收者 to:string; // 交易金額 amount:number; // 給予礦工的手續費 fees:number; // 建構子 constructor(from:string,to:string,amount:number,fees:number) { this.from=from; this.to=to; this.amount=amount; this.fees=fees; this.id=Hash_SHA256(this.toString()); } // 物件轉為字串方法 toString(){ return this.to+this.from+this.amount+this.amount; } // 交易簽名 signature(){ const { public_key, private_key } = GenerateRSAKeyPair(); let signature=Signature(this.toString(),private_key) return {signature,public_key} } // 驗證簽名 verify(signature:string,publicKey:string){ return VerifySignature(this.toString(),signature,publicKey); } } ``` ## 相關加密函式撰寫 **檔案位置設計於 "src/utils/encrypt.ts"** 從加密學應用於區塊鏈的兩大領域 討論 * 哈希函式 * SHA256 哈希函式的計算 * 非對稱式加密 * 透過RSA算法 產生公鑰與私鑰 * 透過RSA算法 進行簽名 * 透過RSA算法 驗證簽名 ### 詳細程式碼環節 **哈希函式** ```typescript // 引入相關套件 import * as CryptoJS from 'crypto-js' // 對於傳進來的字串進行 SHA256 的哈希處理 export function Hash_SHA256(value:string) { return CryptoJS.SHA256(value).toString(); } ``` **非對稱式加密** ```typescript // 引入相關套件 import * as forge from 'node-forge'; // 產生 公鑰與私鑰 對 export function GenerateRSAKeyPair() { const keys = forge.pki.rsa.generateKeyPair(2048); const publicKeyPem = forge.pki.publicKeyToPem(keys.publicKey); const privateKeyPem = forge.pki.privateKeyToPem(keys.privateKey); return { public_key: publicKeyPem, private_key: privateKeyPem }; } // 對於資料內容進行簽名 export function Signature(data: string, privateKeyPem: string): string{ try { const privateKey = forge.pki.privateKeyFromPem(privateKeyPem); const md = forge.md.sha256.create(); md.update(data, 'utf8'); const signature = privateKey.sign(md); return forge.util.encode64(signature); } catch (error) { console.error('簽名出錯:', error); return "Error to signature"; } } // 驗證簽名 export function VerifySignature(data: string, signature: string, publicKeyPem: string): boolean { try { const publicKey = forge.pki.publicKeyFromPem(publicKeyPem); const md = forge.md.sha256.create(); md.update(data, 'utf8'); const signatureBytes = forge.util.decode64(signature); return publicKey.verify(md.digest().getBytes(), signatureBytes); } catch (error) { console.error('驗證簽名錯誤:', error); return false; } } ``` ## 網站使用教學 詳細影片教學: ### 設置功能 ![](https://hackmd.io/_uploads/BJ1BFHS1a.png) * 選擇是否逐步觀察挖礦過程 ```如果選擇是 可以看到 隨機數 與 區塊哈希 一同不斷變化``` ```直到 區塊哈希值 符合區塊難度``` * 拉桿調整 區塊難度 ```代表 區塊哈希值 前方最少多少位為0``` * 簽署 ```填寫完上方資訊 按簽署 即能根據交易內容生成 交易簽名 與 公鑰``` * 提交 ```當簽署完畢時 按提交 驗證後 即能增加交易至最新區塊``` ```備註: 可以觀察到 當交易變化 -> Markle根變化 -> 區塊哈希值變化 ``` ### 區塊功能 ![](https://hackmd.io/_uploads/S1aoOuVy6.png) * 第一個區塊 名稱為 創世區塊(前一區塊哈希值為0) * 綠色代表已完成挖礦 紅色代表未完成挖礦 * 當未完成挖礦則無法增加新區塊 * 每個區塊標頭(前一塊哈希值) 都與 前一區塊 區塊哈希值相同 * 按挖礦 即可開始計算 直到 區塊哈希值 符合 區塊難度 ## 結言 透過整個實作 對於區塊鏈的運行應該有更深層次的理解 儘管沒有實際去打過一次程式碼 透過網站的 Demo 應該也能理解 ``` 真心話: 坦白說 一開始在打這篇時很猶豫 要不要把code全部放上來 感覺超佔篇幅(體驗感不佳) 但分兩天有感覺又太水 所以最後我還是沒有把前端code塞進來 (畢竟前端僅是呈現的部分 與區塊鏈運行關係不大) 因此期望能夠實踐的讀者可以自行去GitHub專案上 仔細專研 ``` 最後希望閱讀完這篇文章你能夠理解 1. 區塊內部資訊都有哪些 2. 區塊如何連接 3. 區塊內部資訊如何計算 4. 實際運作的算法實現 ## 下回預告 透過以上的介紹 我想對於區塊鏈的運行 已經相當透徹。 不過現在的區塊鏈還有一個 令人著迷的變化功能 透過區塊鏈特性 安全 不可竄改 公開 去中心化等特性 所延伸的功能 "智能合約"!!! ### 下回 "區塊鏈基礎 : 區塊鏈中 區塊的智能合約"

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully