一条完整的区块链,是由众多分布式账本集合而成的一种数据链。那么随着其中某个账本的记录完成,区块也就随之生成。区块的生成过程也就可以理解为是交易的一个记账过程。但光有区块还是不够的,还得需要“链”将所有已有区块都连起来。那么所谓的“链”,就是时间戳技术以及某种智能合约。
所谓的区块链,就是由众多的数据区块,按照一定规律顺序所组成的链条。
package main
import(
"crypto/sha256"
"encoding/hex"
"time"
)
//区块结构体
type Block struct{
//区块头
Version int64//版本号
PreviousHash string//前一区块哈希值
MerkleRoot string//Merkle根哈希值
Timestamp int64//时间戳
Difficulty int64//难度目标
Nonce int64//随机数
//区块体
Transactions[]*Transaction//交易信息
TransactionNum int64//交易数量
}
//交易结构体
type Transaction struct{
From string//发送方地址
To string//接收方地址
Amount int64//交易金额
Time int64//交易时间
}
//计算区块哈希值
func(b*Block)calculateHash()string{
blockData:=string(b.Version)+b.PreviousHash+b.MerkleRoot+string(b.Timestamp)+string(b.Difficulty)+string(b.Nonce)
hash:=sha256.Sum256([]byte(blockData))
return hex.EncodeToString(hash[:])
}
//创建新区块
func newBlock(previousBlockBlock,transactions[]Transaction)*Block{
block:=&Block{
Version:1,
PreviousHash:previousBlock.calculateHash(),
MerkleRoot:"merkle_root",
Timestamp:time.Now().UnixNano(),
Difficulty:1,
Nonce:0,
Transactions:transactions,
TransactionNum:int64(len(transactions)),
}
return block
}
//测试代码
func main(){
//创建创世区块
genesisBlock:=&Block{
Version:1,
PreviousHash:"",
MerkleRoot:"merkle_root",
Timestamp:time.Now().UnixNano(),
Difficulty:1,
Nonce:0,
Transactions:[]*Transaction{},
TransactionNum:0,
}
//创建新区块
transactions:=[]*Transaction{
{From:"alice",To:"bob",Amount:10,Time:time.Now().UnixNano()},
{From:"bob",To:"charlie",Amount:5,Time:time.Now().UnixNano()},
}
newBlock:=newBlock(genesisBlock,transactions)
//输出新区块信息
println("Block Version:",newBlock.Version)
println("Previous Block Hash:",newBlock.PreviousHash)
println("Merkle Root Hash:",newBlock.MerkleRoot)
println("Timestamp:",newBlock.Timestamp)
println("Difficulty Target:",newBlock.Difficulty)
println("Nonce:",newBlock.Nonce)
println("Transactions:",newBlock.Transactions)
println("Transaction Number:",newBlock.TransactionNum)
println("Block Hash:",newBlock.calculateHash())
}