1. 程式人生 > 實用技巧 >區塊鏈V4版本實現之一

區塊鏈V4版本實現之一

部分程式碼(transaction.go檔案中定義交易結構):

 1 type TXInput struct {
 2    TXID []byte //交易id
 3    Index int64 //output的索引
 4    Address string //解鎖指令碼,先使用地址來模擬
 5 }
 6 
 7 type TXOutput struct {
 8    Value float64 //轉賬金額
 9    Address string //鎖定指令碼
10 }
11 
12 type Transaction struct {
13    Txid []byte //交易id
14    TXInputs []TXInput //
所有的inputs 15 TXOutputs []TXOutput //所有的outputs 16 }

部分程式碼(transaction.go檔案中SetTXID函式實現):

 1 func (tx *Transaction) SetTXID() {
 2    var buffer bytes.Buffer
 3    encoder := gob.NewEncoder(&buffer)
 4 
 5    err := encoder.Encode(tx)
 6    if err != nil {
 7       log.Panic(err)
 8    }
 9 
10
hash := sha256.Sum256(buffer.Bytes()) 11 tx.Txid = hash[:] 12 }

部分程式碼(transaction.go檔案中挖礦交易實現):

 1 //實現挖礦交易
 2 //特點:只有輸出,沒有有效的輸入(不需要引用id,不需要索引,不需要簽名)
 3 
 4 //把挖礦的人傳進來,因為有獎勵
 5 func NewCoinbaseTX(miner string) *Transaction{
 6 
 7    //後面的程式需要去識別一個交易是否為coinbase,所以需要設定一些特殊的值,用於判斷
 8    inputs := []TXInput{{nil,-1
,genesisInfo}} 9 outputs := []TXOutput{{12.5,miner}} 10 11 tx := Transaction{nil,inputs,outputs} 12 tx.SetTXID() 13 14 return &tx 15 }

使用Transaction改寫程式

  1. 改寫block結構
  2. 根據提示修改:逐個檔案修改,直至編譯成功(將Data修改為Transaction)
  3. 得出創世塊挖礦成功

顯示效果: