blockchain3

package module
v0.0.0-...-c09ee95 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2020 License: GPL-3.0 Imports: 13 Imported by: 0

README

blockchain3

增加序列化功能,将区块链存储到数据库中。 源码对应的文档:https://www.kancloud.cn/daleboy/blockchain/1971570

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IntToHex

func IntToHex(num int64) []byte

IntToHex 将整型转为二进制数组

Types

type Block

type Block struct {
	Timestamp     int64
	Data          []byte
	PrevBlockHash []byte
	Nonce         int
	Hash          []byte
}

Block 区块结构新版,增加了计数器nonce,主要目的是为了校验区块是否合法 即挖出的区块是否满足工作量证明要求的条件

func DeserializeBlock

func DeserializeBlock(d []byte) *Block

DeserializeBlock 反序列化,注意返回的是Block的指针(引用)

func NewBlock

func NewBlock(data string, prevBlockHash []byte) *Block

NewBlock 创建普通区块

func NewGenesisBlock

func NewGenesisBlock() *Block

NewGenesisBlock 创建创始区块。注意,创建创始区块也需要挖矿。

func (*Block) Serialize

func (b *Block) Serialize() []byte

Serialize Block序列化

type Blockchain

type Blockchain struct {
	Tip []byte   //区块链最后一块的哈希值
	Db  *bolt.DB //数据库
}

Blockchain 区块链结构 我们不在里面存储所有的区块了,而是仅存储区块链的 tip。 另外,我们存储了一个数据库连接。因为我们想要一旦打开它的话,就让它一直运行,直到程序运行结束。

func NewBlockchain

func NewBlockchain() *Blockchain

NewBlockchain 创建初始区块链

func (*Blockchain) AddBlock

func (bc *Blockchain) AddBlock(data string)

AddBlock 挖出普通区块并将新区块加入到区块链中 此方法通过区块链的指针调用,将修改区块链bc的内容

func (*Blockchain) Iterator

func (bc *Blockchain) Iterator() *BlockchainIterator

Iterator 每当需要对链中的区块进行迭代时候,我们就通过Blockchain创建迭代器 注意,迭代器初始状态为链中的tip,因此迭代是从最新到最旧的进行获取

type BlockchainIterator

type BlockchainIterator struct {
	// contains filtered or unexported fields
}

BlockchainIterator 区块链迭代器,用于对区块链中的区块进行迭代

func (*BlockchainIterator) Next

func (i *BlockchainIterator) Next() *Block

Next 区块链迭代,返回当前区块,并更新迭代器的currentHash为当前区块的PrevBlockHash

type CLI

type CLI struct {
	BC *Blockchain
}

CLI 响应处理命令行参数

func (*CLI) Run

func (cli *CLI) Run()

Run 读取命令行参数,执行相应的命令 使用标准库里面的 flag 包来解析命令行参数:

type ProofOfWork

type ProofOfWork struct {
	// contains filtered or unexported fields
}

ProofOfWork POW结构体 可以看出,每一个pow实例与具体的block相关 但在确定好挖矿难度系数后,所有区块的pow的target是相同的, 除非挖矿系数随着时间推移,挖矿难度系数不断增加

func NewProofOfWork

func NewProofOfWork(b *Block) *ProofOfWork

NewProofOfWork 初始化创建一个POW的函数,以block指针为参数(将修改该block) 主要目的是确定target

func (*ProofOfWork) Run

func (pow *ProofOfWork) Run() (int, []byte)

Run POW挖矿核心算法实现,注意,这是一个方法,不是函数, 因为挖矿的完整描述是:挖出包含某个实际交易信息(或数据)的区块 挖矿是为交易上链提供服务,矿工拿到交易信息后进行挖矿,挖出的有效区块将包含交易信息 有可能挖不出符合条件的区块,所以将区块上链之前,需要对挖出的区块进行验证(验证是否符合条件)

func (*ProofOfWork) Validate

func (pow *ProofOfWork) Validate() bool

Validate 验证工作量证明POW

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL