欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

使用go实现简易比特币区块链公链功能

程序员文章站 2022-06-18 19:13:08
使用go语言实现具备以下功能的简易区块链 区块与区块链 共识机制 数据库 cli命令行操作 交易管理 密码学 数字签名 交易缓存池 p2p网络管理由于平时还要进行论文工作,项目不定时...

使用go语言实现具备以下功能的简易区块链

  • 区块与区块链
  • 共识机制
  • 数据库
  • cli命令行操作
  • 交易管理
  • 密码学
  • 数字签名
  • 交易缓存池
  • p2p网络管理

由于平时还要进行论文工作,项目不定时更新

2021.1.1实现了区块结构、区块链结构、工作量证明pow,剩下部分陆续更新

1.实现区块结构

package blc

import (
	"bytes"
	"crypto/sha256"
	"time"
)

//实现一个最基本的区块结构
type block struct {
	timestamp int64 //时间戳,区块产生的时间
	heigth int64//区块高度(索引、号码)代表当前区块的高度
	preblockhash []byte//前一个区块(父区块)的哈希
	hash []byte//当前区块的哈希
	data []byte//交易数据
}
//创建一个新的区块
func newblock(height int64,preblockhash []byte,data []byte) *block {
	var block block
	block=block{heigth: height,preblockhash: preblockhash,data: data,timestamp: time.now().unix()}
	block.sethash()
	return &block
}
//计算区块哈希
func (b *block)sethash() { 
	//int64转换成字节数组
	//高度转换
	heightbytes:=inttohex(b.heigth)
	//时间转换
	timestampbytes:=inttohex(b.timestamp)
//拼接所有属性进行hash
	blockbytes:=bytes.join([][]byte{heightbytes,timestampbytes,b.preblockhash,b.data},[]byte{})
	hash:=sha256.sum256(blockbytes)
	b.hash=hash[:]
}

2.实现区块链结构

package blc

type blockchain struct {
	blocks []*block //存储有序的区块
}
//初始化区块链
func createblockchainwithgenesisblock() *blockchain {
	//添加创世区块
	genesisblock:=creategenesisblock("the init of blockchain")

	return &blockchain{[]*block{genesisblock}}
}
//添加新的区块到区块链中
func (bc *blockchain)addblock(height int64,data []byte,prevblockhash []byte){
	newblock := newblock(height,prevblockhash,data)
	bc.blocks=append(bc.blocks,newblock)
}

3.实现工作量证明

package blc

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"math/big"
)

//目标难度值,生成的hash前 targetbit 位为0才满足条件
const targetbit =16
//工作量证明
type proofofwork struct {
	block *block //对指定的区块进行验证
	target *big.int //大数据存储
}
//创建新的pow对象
func newproofofwork(block *block) *proofofwork {
	target:=big.newint(1)
	target=target.lsh(target,256-targetbit)
	return &proofofwork{block,target}
}
//开始工作量证明
func (proofofwork *proofofwork)run() ([]byte,int64) {
	//数据拼接
	var nonce=0 //碰撞次数
	var hash [32]byte //生成的hash
	var hashint big.int //存储转换后的hash
	for {
		databytes:=proofofwork.preparedata(nonce)
		hash=sha256.sum256(databytes)
		hashint.setbytes(hash[:])
		fmt.printf("hash:\r%x",hash)
		//难度比较
		if proofofwork.target.cmp(&hashint)==1{
			break
		}
		nonce++
	}
	fmt.printf("碰撞次数:%d\n",nonce)
	return hash[:],int64(nonce)
}
//准备数据,将区块属性拼接起来,返回字节数组
func (pow *proofofwork)preparedata(nonce int) []byte {
	data:=bytes.join([][]byte{
		pow.block.preblockhash,
		pow.block.data,
		inttohex(pow.block.timestamp),
		inttohex(pow.block.heigth),
		inttohex(int64(nonce)),
		inttohex(targetbit),
	},[]byte{})
	return data
}

4.当前运行结果

使用go实现简易比特币区块链公链功能

到此这篇关于使用go实现简易比特币区块链公链功能的文章就介绍到这了,更多相关go实现比特币区块链公链内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!