Easy learning block chain 2 - simple block chain

MiniBC block chain V001 - simple block chain

Source Address: [ https://github.com/wangshizebin/minibc]

Blocks

We started from the "block chain" and "block" section. Block chain block is the most basic data structure in a block chain, valuable information stored in the block. For example, credits bit data block stores the transaction, in addition, also contain other block information: version number, the current time and the previous hash value of a block and the like. We define slightly simplified bitcoin block, the block is defined as MiniBC:

type Block struct {
	Version       int32  //协议版本号
	HashPrevBlock []byte //上一个区块的hash值,长度为32个字节
	Time          int32  //时间戳,从1970.01.01 00:00:00到当前时间的秒数
	Bits          int32  //工作量证明(POW)的难度
	Nonce         int32  //要找的符合POW要求的的随机数

	Data []byte //区块存储的内容,在虚拟币中用来存储交易信息
}

Wherein: Version is the version number, 32-bit integer type. Time is the current time stamp, that is, create time blocks, Bits and Nonce temporarily do not consider, do explain in detail later in the workload of proof (pow). Data is the most valuable information contains the actual block, the block chain all the contents to be stored all included in it. PrevBlockHash a block before stored hash value (Hash). In the actual program block chain, such as Bitcoin (bits currency), and a block comprising a block header area two body portions, Data block data stored in the body to the other information contained in the header area. We sake of simplicity, the zone header and block body combined.

So how do we calculate the hash? Hashing method is a very important feature block chain, and it is this characteristic becomes the block chain security. Hashing time consuming process like Bitcoin mining is the process of computing the hash
, which is people buy a more powerful GPU computing capabilities to tap reason Bitcoin, a bit like the mainland chip and designed a special machine to mine improve the ability of the hash calculation. About the purpose of introducing hash calculation, it will be discussed in detail later.

A value obtained Hashi block is very simple, that is, the data header area connected together, the call golang "crypto / sha256" function package to give a 32-byte (256-bit) binary data length, which is the area the hash value for the block.

Working procedure: First, the header area an integer number of items processed by the method IntToByte [] byte, then call a method bytes.Join connecting together all the data of the header area, the last call for the input sha256.Sum256 Law Act [] byte data generating 32 byte [] byte hash value.

func (block *Block) GetHash() []byte {

	version := IntToByte(block.Version)
	time := IntToByte(block.Time)
	bits := IntToByte(block.Bits)
	nonce := IntToByte(block.Nonce)

	data := bytes.Join([][]byte{version, block.HashPrevBlock, time, bits, nonce, block.Data}, []byte{})
	hash := sha256.Sum256(data)
	return hash[:]
}  

In order to simplify the creation of our block, it provides function blocks to create:

func NewBlock(data string, prevHash []byte) *Block {
	block := Block{
		Version:       VERSION,
		HashPrevBlock: prevHash,
		Time:          int32(time.Now().Unix()),
		Bits:          0,
		Nonce:         0,
		Data:          []byte(data),
	}
	return &block
}

Since the block chain before the first block is not a block, the block structure required HashPrevBlock as null data [] byte {}. Block chain in the first block commonly referred to as "Genesis block", we provide a single method for creating a block of Genesis:

func NewGenesisBlock() *Block {
	return NewBlock("Genesis Block", []byte{})
}

Block It's that simple!

Block chain

Block chain structure of the data itself is not complicated, it is a chain connecting together the block Block. So we first work to be done is to block chain is defined as a linked list, list the contents of each node is the block Block. List for software developers, is the most familiar with the basic data structure, usually defined as follows:

type Object interface{} //节点中存储的数据的类型

type Node struct {
	Data Object //节点存储的数据
	Next *Node //指向下一个节点的指针
}

type List struct {
	HeadNode *Node //头节点
}

The students are not familiar with the list can go back to the list Bubu knowledge, including the definition of a linked list traversal, our project yet less than, but follow-up work will be used. For simplicity, we first define a simplified block chain BlockChain will block Block provisional organization slices (arrays), both have the ability to slice data storage, and the ability to organize the order of the data.

type Blockchain struct {
	blocks []*Block
}

This is our first block chain! This is too simple, right, in fact the real block chain from the overall point of view, that is so simple, but to be safe careful, a lot of work needs to be done.

Now you can always add a block in the block chain we created:

func (bc *BlockChain) AddBlock(data string) {
	if (bc.Blocks == nil || len(bc.Blocks) < 1) {
		return
	}

	//取出当前区块链的最后一个区块
	prevBlock := bc.Blocks[len(bc.Blocks)-1]

	//传入区块数据和最后一个区块的hash,建新的区块
	block := NewBlock(data, prevBlock.GetHash())
	bc.Blocks = append(bc.Blocks, block)
}

In order to simplify the process of creating our block chain, providing the creation of a function block chain:

func NewBlockChain() *BlockChain {
	//预先创建一个创世纪区块
	blockChain := BlockChain{Blocks: []*Block{NewGenesisBlock()}}
	return &blockChain
}

The new block chain to create a pre-Genesis blocks.

Done ~~~~~~~~~~~~~~~~~~~~

run

Let's see MiniBC is working:

func main() {
	//新建一条区块链,里面隐含着创建了一个创世纪区块(初始区块)
	bc := NewBlockChain()

	//添加3个区块
	bc.AddBlock("Mini block 01")
	bc.AddBlock("Mini block 02")
	bc.AddBlock("Mini block 03")

	//区块链中应该有4个区块:1个创世纪区块,还有3个添加的区块
	for _, block := range bc.Blocks {
		fmt.Println("前一区块哈希值:", BytesToHex(block.HashPrevBlock))
		fmt.Println("当前区块内容为:", string(block.Data))
		fmt.Println("当前区块哈希值:", BytesToHex(block.GetHash()))
		fmt.Println("=============================================")
	}
}  

After running output:

前一区块哈希值: 
当前区块内容为: Genesis Block
当前区块哈希值: 0e902e4108dfc0fb14b094ce3a130734bc5ef76f5aa58bc56a3635e031947e1e
=============================================
前一区块哈希值: 0e902e4108dfc0fb14b094ce3a130734bc5ef76f5aa58bc56a3635e031947e1e
当前区块内容为: Mini block 01
当前区块哈希值: 3a567c6151181dd88b6f1aa134e0b81151280c15d585df51898aa9fb5f37cd8b
=============================================
前一区块哈希值: 3a567c6151181dd88b6f1aa134e0b81151280c15d585df51898aa9fb5f37cd8b
当前区块内容为: Mini block 02
当前区块哈希值: c4145bc199da2d24d2b9d7390b8ae4b3cee3eb001b2dd57538b3142af8604fca
=============================================
前一区块哈希值: c4145bc199da2d24d2b9d7390b8ae4b3cee3eb001b2dd57538b3142af8604fca
当前区块内容为: Mini block 03
当前区块哈希值: 8cd906d8084fa2b2e83b4c3788d0b49dbd625e66268c3319c830282fcdaa5c05
=============================================

It seems to run pretty good.

We achieved and will be achieved

We have constructed a very simple block chain: just a block chain block array, but the current block HashPrevBlock already point before a block, you can use this field in the block of backlinks. Of course, the actual block chain is much more complicated. Data block chain needs to be saved, we usually stored data, either in the database or in the file, we MiniBC tentatively stored in the database. In fact bitcoin block data is saved into the file, other information stored in the database leveldb. The next section, our goal is to build a simple database and persistence KV block chain.

Exchanges and questions

We can begin to gradually in-depth research study from v001, each source file has full instructions and comments. If you have questions, suggestions, and do not understand the question, you can contact me.

MiniBC block chain can join the exchange qq group: 777 804 802 , Go developers paradise
of my micro letter: bkra50
GitHub addr: https://github.com/wangshizebin/minibc

In addition, the recruitment of a group of like-minded, common maintenance items, to jointly promote the project, contribute to the open source world, welcome hooked.

Let’s go~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Guess you like

Origin blog.csdn.net/wanghao72214/article/details/90291186