构建命令行式交易区块链应用

构建一个通过命令终端创建创世区块、转账交易以及查询等功能的区块链应用

几个数据结构

区块结构:

type Block struct {
	//时间戳,创建区块的时间
	TimeStamp int64
	//上个区块的hash
	PrevBlockHash []byte
	//Data 交易数据
	Transaction []*Transaction
	// Hash 当前区块的hash
	Hash []byte
	// Nonce随机数
	Nonce int
}

CLI交互结构

type CLI struct {
	BC *BlockChain
}
type BlockChain struct {
	Tip []byte   //区块链里最后一个区块的hash
	DB  *bolt.DB //数据库
}

查询暂存结构

//迭代器
func (blockchain *BlockChain) Iterator() *BlockchainIterator {
	return &BlockchainIterator{blockchain.Tip, blockchain.DB}
}

交易结构:

type Transaction struct {
	// 1、交易ID
	ID []byte
	// 2、交易输入
	Vin []TXInput
	// 3、交易输出
	Vout []TXOutput
}
// 交易输入
type TXInput struct {
	// 1、交易ID 上个区块的
	Txid []byte
	// 2、存储TXoutput在Vout里面的索引
	Vout int
	// 3、用户名 签名
	ScriptSig string
}

// 交易输出
type TXOutput struct {
	Value        int    //分
	ScriptPubKey string //
}

创建创世区块时序图

交易时序图

效果

帮助界面

查询效果图
1)某个账号的余额:(账号:maobuyi)

2)查询整个区块中的交易信息

转账

注: 执行转账命令如:./main send -from '["maobuyi"]' -to '["zhangjie"]' -amount '["4"]'

详细代码:https://github.com/NGLHarry/Blockchainer/tree/main/part16-addTransition2

原文地址:https://www.cnblogs.com/whiteBear/p/15640630.html