用Go語言打造區塊鏈[1]
阿新 • • 發佈:2018-12-22
學好Go語言走遍天下都不怕。以下程式碼建立了一個非常原始的電子賬本:
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"strconv"
"time"
)
type Block struct {
Timestamp int64
Data []byte
PrevBlockHash []byte
Hash []byte
}
func (b *Block) SetHash() {
timestamp := []byte (strconv.FormatInt(b.Timestamp, 10))
headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})
hash := sha256.Sum256(headers)
b.Hash = hash[:]
}
/*
初始化第一個塊
*/
func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{time.Now().Unix(), []byte (data), prevBlockHash, []byte{}}
block.SetHash()
return block
}
type Blockchain struct {
blocks []*Block
}
/*
新增 區塊
*/
func (bc *Blockchain) AddBlock(data string) {
prevBlock := bc.blocks[len(bc.blocks)-1]
newBlock := NewBlock(data, prevBlock.Hash)
bc.blocks = append(bc.blocks, newBlock)
}
func NewGenesisBlock() *Block {
return NewBlock("Genesis Block創始塊", []byte{})
}
/*
用創始塊建立一個區塊鏈的函式
*/
func NewBlockchain() *Blockchain {
return &Blockchain{[]*Block{NewGenesisBlock()}} /*我不太理解這種語法,層層深入?
YuloYu 在評論中說:這個地方是,把[]*Block{NewGenesisBlock() 生成的塊,把塊放到這個數組裡面。*/
}
func main() {
/*
初始化
*/
bc := NewBlockchain()
/*
新增記錄
*/
bc.AddBlock("Send 1 BTC TO L")
bc.AddBlock("Send 2 BTC to R")
/*
檢視我們最終儲存結果
*/
for _, block := range bc.blocks {
fmt.Printf("Prev: hash:%x\n", block.PrevBlockHash)
fmt.Printf("Data: %s\n", block.Data)
fmt.Printf("Hash: %x\n", block.Hash)
fmt.Println()
}
}