Go语言实现一个简单的区块链

Go语言实现一个简单的区块链

2023年7月27日发(作者:)

Go语⾔实现⼀个简单的区块链Go语⾔实现⼀个简单的区块链创建区块package coreimport ( "time")type Block struct { Timestamp int64 //时间戳 Data []byte //区块信息 PrevBlockHash []byte //前⼀个区块哈希值 Hash []byte //⾃⾝哈希值 Nonce int //⼯作量证明}//创建新区块(传⼊data信息以及上⼀个区块的哈希值)func Newblocks (Data string,PrevBlockHash []byte) *Block{ block := &Block{().Unix(),[]byte(Data),PrevBlockHash,[]byte{},0}

pow := NewProfowork(block)

n,h := () //⼯作量证明run⽅法 = h

= n return block}//创世纪块(第⼀个块)func NewGenesisBlock() (*Block) { return Newblocks("Genesis Block",[]byte{})}⽣成区块链package coretype BlockChain struct{ Blocks []*Block}//新区块加⼊区块链func (b *BlockChain) AddBlock(data string){ preB := [len()-1] newB := Newblocks(data,) = append(,newB)}//创世区块链(唯创世块的区块链)func NewBlockChain() *BlockChain{ Newb := NewGenesisBlock() a := []*Block{Newb} return &BlockChain{a}}⼯作量证明package coreimport( "crypto/sha256" //哈希算法包 "log"

"bytes" "math"

"math/big" //⼤整数(哈希值很⼤) "encoding/binary")var MaxNonce = 64 //最多挖矿64 次const Targetbits = 20 //挖矿难度系数 越⼤越难//⼯作量结构体type Profofwork struct{ Block *Block Target *}// 区块以及⽬标值func NewProfowork(b *Block) *Profofwork{ target := (1) (target,uint(256-Targetbits)) //移位运算(256-20)位 pow := &Profofwork{b,target}

return pow}// 数据整合成字节换算哈希值func (p *Profofwork)prepareDate(n int) []byte{ data := ([][]byte{ ockHash, , IntToHex(amp), IntToHex(int64(Targetbits)), IntToHex(int64(n)), },[]byte{},) return data}// 寻找有效的哈希值(挖矿)// 寻找有效的哈希值(挖矿)func (p *Profofwork) Run() (int,[]byte){ var Hashbig var hash [32]byte var nonce = 0 for nonce < MaxNonce{ data := eDate(nonce) hash = 256(data) //哈希算法⽣成哈希 es(hash[:]) //哈希值转为⼤整数//与所移位运算后的⼤整数⽐较 ⼩于才算有效哈希 返回哈希值以及循环次数 退出“挖矿” if () == -1{

break }else{ nonce++ } } return nonce,hash[:]

}// 校验区块有效与否func (p *Profofwork) Isvalidata() bool{ var Hashbig //把记录的循环次数传参 data := eDate() hash := 256(data) es(hash[:]) is := ()== -1 return is

}//将⼀个 int64 转化为⼀个字节数组(byte array)func IntToHex(num int64) []byte { buff:=new() err:=(buff, ian, num) if err !=nil{ (err) } return ()

}age mainimport ( "core" "fmt")func main() {//⽣成创世纪区块链 bc := ckChain()//

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1690463948a353122.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信