1. 程式人生 > >區塊鏈公鏈程式碼

區塊鏈公鏈程式碼

區塊鏈公鏈

 type Block struct {
	Index  int64
	TimeStamp int64
	Data  []byte
	PrevBlockHash []byte
	Hash []byte
}

新的block

func  NewBlock(index int64,data ,prevBlockHash []byte) *Block  {
	block :=&Block{index,time.Now().Unix(),data,prevBlockHash,[]byte{}}
	block.setHash() //設定當前區塊Hash
	return  block
}

hash計算

func (b *Block)setHash()  {
	timestamp :=[]byte(strconv.FormatInt(b.TimeStamp,10))
	index := []byte(strconv.FormatInt(b.Index,10))
	headers :=bytes.Join([][]byte{timestamp,index,b.PrevBlockHash},[]byte{})
	hash:=sha256.Sum256(headers)
	b.Hash =hash[:]  //儲存Hash結果在當前塊的Hash中
}

創世紀塊

func NewGenesisBlock() *Block  {
	return  NewBlock(0,[]byte("first block"),[]byte{})
}

定義區塊鏈

type Blockchain struct {
  blocks []*Block
}

新增區塊

func  NewBlockchain()*Blockchain  {
	return &Blockchain{[]*Block{NewGenesisBlock()}}
}

建立新區塊

func (bc *Blockchain)AddBlock(data string)  {
	prevBlock :=bc.blocks[len(bc.blocks)-1]
	newBlock :=NewBlock(prevBlock.Index+1,[]byte(data),prevBlock.Hash)
	bc.blocks =append(bc.blocks,newBlock)
}

主函式

func main(){
	bc :=NewBlockchain()
	bc.AddBlock("Joy send 1 BTC to Jay")
	bc.AddBlock("Jakc sent 2 BTC to Jay")

	for  _,block := range bc.blocks{
		fmt.Printf("Index :%d\n" ,block.Index)
		fmt.Printf("TimeStamp: %d\n",block.TimeStamp)
		fmt.Printf("Data: %s\n",block.Data)
		fmt.Printf("PrevHash: %x\n",block.PrevBlockHash)
		fmt.Printf("Hash: %x\n",block.Hash)
		fmt.Println("_____________________________")
	}

}