一、引言
區塊鏈技術作為一種去中心化的分佈式帳本技術,自2008年比特幣誕生以來,迅速成為了數位貨幣、供應鏈管理、數據隱私保護等領域的關鍵技術。區塊鏈技術的核心優勢在於其不可篡改、透明且具備高度安全性,這使得其應用範疇日益擴展。本文將探討區塊鏈技術的基本原理,並介紹如何實作一個簡單的區塊鏈應用。
區塊鏈(Blockchain)作為Web3.0的基礎技術,其實就是hash加密技術的加強版,也可視為電子病歷等簽章技術的延伸,本文將經由實作來了解其運作原理。
二、區塊鏈技術的基本原理
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum
```
2. 初始化區塊鏈:使用Geth創建一個新的區塊鏈。
geth --datadir ./blockchain init genesis.json
```
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 data;
function set(uint256 x) public {
data = x;
}
function get() public view returns (uint256) {
return data;
}
}
在Remix IDE中編譯合約並部署到以太坊區塊鏈上。成功部署後,可以通過合約地址與其互動,執行set和get操作來存儲和檢索數據。
3. 測試區塊鏈應用
部署完成後,可以使用Truffle框架來進行測試。Truffle是一個開發環境和測試框架,用於建立區塊鏈應用。
步驟:
1. 安裝Truffle:
npm install -g truffle
```
2. 初始化項目:
truffle init
```
3. 撰寫測試代碼: 創建一個測試腳本,檢查合約功能是否如預期運行。
const SimpleStorage = artifacts.require("SimpleStorage");
contract("SimpleStorage", () => {
it("should store the value 89", async () => {
const simpleStorage = await SimpleStorage.deployed();
await simpleStorage.set(89);
const result = await simpleStorage.get();
assert(result.toString() === '89');
});
});
```
4. 運行測試:
truffle test
```
四、區塊鏈應用案例
😱附件.以B4X的B4J實作「區塊鏈(Blockchain)實作」
(https://www.b4x.com/android/forum/threads/b4x-blockchain-example-create-your-own-cryptocurrency-part-1-2.87237/#content)
Sub Process_Globals
End Sub
Sub AppStart (Args() As String)
'Create a Blockchain of 10 blocks
Blockchain.Create
For i = 0 To 10
Blockchain.AddBlock
Next
'Integrity Check vs block tampering
Dim b = Blockchain.GetBlock(4) As Block
Log("Before tampering : " & b.Data)
Blockchain.VerifyBlockIntegrity(4)
b.Data = "Hi! I'm block 23! ;)"
Log("After tampering : " & b.Data)
Blockchain.VerifyBlockIntegrity(4)
End Sub
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub
模組Block.bas
Private Sub Class_Globals
Dim Index As Int
Dim Timestamp As Long
Dim Data As String
Dim Previous_Hash As String
End Sub
Public Sub Initialize(blockIndex As Int, blockTimestamp As Long, blockData As String, previousBlock_hash As String)
Index = blockIndex
Timestamp = blockTimestamp
Data = blockData
Previous_Hash = previousBlock_hash
End Sub
Sub getHash As String
Return HashLib.Sha256( _
Index & _
Timestamp & _
Data & _
Previous_Hash _
)
End Sub
模組HashLib.bas
Private Sub Process_Globals
Private md As MessageDigest
Private bc As ByteConverter
End Sub
Public Sub Sha256(data As String) As String
Dim hash() = md.GetMessageDigest(data.GetBytes("UTF8"),"SHA-256") As Byte
Return bc.HexFromBytes(hash).ToLowerCase
End Sub
模組BlockGen.bas
Private Sub Process_Globals
End Sub
'Generate genesis block
Sub Genesis_Block As Block
'Manually construct a block with
'index zero and arbitrary previous hash
Dim genesisBlock As Block
genesisBlock.Initialize(0, DateTime.now, "Genesis Block", "0")
Return genesisBlock
End Sub
'Generate all later blocks in the blockchain
Sub Next_Block(previousBlock As Block) As Block
Dim index = previousBlock.Index + 1 As Int
Dim nextBlock As Block
nextBlock.Initialize( _
index, _
DateTime.Now, _
"Hi! I'm block " & index & ".", _
previousBlock.Hash )
Return nextBlock
End Sub
模組Blockchain.bas
#IgnoreWarnings: 12
Private Sub Process_Globals
Private bc As List
End Sub
Sub Create
bc.Initialize
bc.Add(BlockGen.Genesis_Block)
End Sub
Sub LastBlock As Block
If bc.Size == 0 Then Return Null
'-------------------------------
Return bc.Get(bc.Size - 1)
End Sub
Sub AddBlock As Boolean
Dim b = LastBlock As Block
If b == Null Then Return False
'-----------------------------
bc.Add(BlockGen.Next_Block(b))
'Tell everyone about it!
Log("Block #" & b.Index & " has been added to the blockchain!")
Log("Hash: " & b.Hash & "=>" & b.Hash.Length)
Log("bc: " & bc)
Log("----------------------------------------------------------------------")
Return True
End Sub
Sub GetBlock(index As Int) As Block
Return bc.Get(index)
End Sub
Sub VerifyBlockIntegrity(index As Int) As Boolean
If index >= bc.Size - 1 Then
Log("This block cannot be verified.")
End If
Dim thisBlock = bc.Get(index ) As Block
Dim nextBlock = bc.Get(index + 1) As Block
If thisBlock.Hash == nextBlock.Previous_Hash Then
Log("Block #" & index & ": OK")
Return True
End If
Log("Block #" & index & ": CORRUPT")
Return False
End Sub
參考網址
•[B4X] 區塊鏈範例 - 創建您自己的加密貨幣(https://www.b4x.com/android/forum/threads/b4x-blockchain-example-create-your-own-cryptocurrency-part-1-2.87237/#content)
• 以太坊官方網站(https://ethereum.org/)
• Truffle 框架(https://archive.trufflesuite.com/)
• Solidity 智能合約編程(https://soliditylang.org/)