1.创建一条公链
本部分内容我们会使用Go语言去做代码实现,我们先在Go文件夹下的src目录下创建一个文件夹publicChain,用于存放所有代码文件
1.1 区块结构
通常意义上区块内容主要包含五个部分:区块高度、前一个区块的哈希、交易数据、时间戳以及本区块的哈希。使用Go语言中的Struct即可定义一个区块
/Users/go/src/publicChain/part1-Basic-Prototype/BLC/Block.go文章来源地址https://www.toymoban.com/news/detail-450038.html
package BLC
import (
"bytes"
"crypto/sha256"
"fmt"
"strconv"
"time"
)
//the structure of a block
//five elements of a block
type Block struct {
//1.block height
Height int64
//2.the last block's hash
PreBlockHash []byte
//3.transaction data
Data []byte
//4.timestamp
Timestamp int64
//5.block's hash
Hash []byte
}
注意:这里区块哈希值和交易数据类型都使用了[]byte类型,这是因为[]byte更加灵活和易操作
1.2 生成新区块
我们都知道,在区块链中新区块的生成依赖于上一个区块的信息,我们现在来创建一个函数专门用来生成新的区块
/Users/go/src/publicChain/part1-Basic-Prototype/BLC/Block.go
//a function to crate a new block
//use the "Block" defined above to crate a new block
func Newblock(height int64, preBlockHash []byte, data string) *Block {
//1.crate a new block
block := &Block{height, preBlockHash, []byte(data), time.Now().Unix(), nil}
//2.set Hash
block.SetHash()
return block
}
在创建第一个区块的时候,需要我们提供区块的五要素,现在我们将提供前三个作为新函数的参数,时间戳直接调用系统即可,而本区块的哈希是由其它信息通过加密算法产生
我们先定义了一个block变量,实际上是上面Block的引用(直接传数据量太大了),这里的本区块哈希值我们暂且填充为nil
//1.crate a new block
block := &Block{height, preBlockHash, []byte(data), time.Now().Unix(), nil}
这里我们用上面这个变量调用了一个新的函数专门用来生成本区块的哈希值
//2.set Hash
block.SetHash()
如下函数把int64类型的数据转化为了[]byte,并将其连起来用于生成哈希值文章来源:https://www.toymoban.com/news/detail-450038.html
/Users/go/src/publicChain/part1-Basic-Prototype/BLC/Block.go
// a method to set the hash of the current block
// the hash of the current block is related to the rest data of current block
func (block *Block) SetHash() {
//1.Convert int64 to byte slice
heightBytes := IntToHex(block.Height)
//2.Convert int64 to byte slice
timeString := strconv.FormatInt(block.Timestamp, 2)
timeBytes := []byte(timeString)
//3.concatenate all properties
blockBytes := bytes.Join([][]byte{heightBytes, bloc
到了这里,关于区块链项目 - 1 创建一条公链的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!