01区块链go语言学习笔记:简单区块链

原文档:https://blog.csdn.net/wangqianqianya/article/details/86436026

block.go

package core

import (
	"crypto/sha256"
	"encoding/hex"
	"time"
)

//区块结构
type Block struct {
	Index         int64  //区块下标,从0开始
	Timestap      int64  //时间戳
	PrevBlockHash string //前一个区块的哈希值
	Hash          string //该区块的哈希值
	Data          string
}

//计算哈希值
func calculateHash(b Block) string {
	blockData := string(b.Index) + string(b.Timestap) + b.PrevBlockHash + b.Data //这几个数字任何一个都是不可更改的
	hashInBytes := sha256.Sum256([]byte(blockData))
	return hex.EncodeToString(hashInBytes[:])
}

//生成新的区块
func generateNewBlock(preBlock Block, data string) Block {
	newBlock := Block{}
	newBlock.Index = preBlock.Index + 1
	newBlock.Timestap = time.Now().Unix()
	newBlock.PrevBlockHash = preBlock.Hash
	newBlock.Hash = calculateHash(newBlock)
	newBlock.Data = data
	return newBlock
}

//生成第一个区块
func generateGenesisBlock() Block {
	preBlock := Block{}
	preBlock.Index = -1
	preBlock.Hash = ""
	return generateNewBlock(preBlock, "genesis block")
}

blockChain.go

package core

import "fmt"

type BlockChain struct {
	blocks []*Block
}

//新建一条区块链
func NewBlockChain() *BlockChain {
	genesisBlock := generateGenesisBlock()
	blockChain := BlockChain{}
	blockChain.AppendBlock(&genesisBlock)
	return &blockChain
}

//发送一条数据即新增一个区块
func (bc *BlockChain) SentData(data string) {
	preBlock := bc.blocks[len(bc.blocks)-1]
	newBlock := generateNewBlock(*preBlock, data)
	bc.AppendBlock(&newBlock)
}

//增加区块
func (bc *BlockChain) AppendBlock(block *Block) {
	if len(bc.blocks) == 0 {
		bc.blocks = append(bc.blocks, block)
		return
	}
	if bc.isValid(*block, *bc.blocks[len(bc.blocks)-1]) {
		bc.blocks = append(bc.blocks, block)
	}
}

//打印区块信息
func (bc *BlockChain) Print() {
	for _, block := range bc.blocks {
		fmt.Printf("Index: %d\n", block.Index)
		fmt.Printf("pre.Hash: %d\n", block.PrevBlockHash)
		fmt.Printf("Hash: %d\n", block.Hash)
		fmt.Printf("data: %d\n", block.Data)
	}
}

//判断区块是否有效
func (bc *BlockChain) isValid(newblock Block, oldBlock Block) bool {
	if (oldBlock.Index + 1) != newblock.Index {
		return false
	}
	if (oldBlock.Hash) != newblock.PrevBlockHash {
		return false
	}
	fmt.Println(calculateHash(newblock))
	fmt.Println(newblock.Hash)
	return true
}

main.go

package main

import "core"

func main() {
	bc := core.NewBlockChain()
	bc.SentData("sent 1$ to 1")
	bc.SentData("sent 2$ to 2")
	bc.Print()
}

其中block.go和blockChain.go要放在一个包内
在这里插入图片描述

发布了2 篇原创文章 · 获赞 0 · 访问量 31

猜你喜欢

转载自blog.csdn.net/qq_39148787/article/details/104494822