区块链公链代码

区块链公链

 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("_____________________________")
	}

}

猜你喜欢

转载自blog.csdn.net/qq_30505673/article/details/83688787