实现一个最简单的区块链结构
1. 定义区块结构
每个区块包含:
- Index:区块的编号
- Timestamp:区块创建的时间
- Data:区块的数据(在这个示例中,我们将它简化为一个字符串)
- PreviousHash:前一个区块的哈希值
- Hash:当前区块的哈希值(通过计算所有区块信息来生成)
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
)
// Block 结构体表示一个区块
type Block struct {
Index int
Timestamp string
Data string
PreviousHash string
Hash string
}
// CreateBlock 创建一个新的区块
func CreateBlock(index int, timestamp, data, previousHash string) Block {
block := Block{
Index: index,
Timestamp: timestamp,
Data: data,
PreviousHash: previousHash,
}
// 计算当前区块的哈希值
block.Hash = calculateHash(block)
return block
}
// calculateHash 计算区块的哈希值
func calculateHash(block Block) string {
record := fmt.Sprintf("%d%s%s%s", block.Index, block.Timestamp, block.Data, block.Pre

最低0.47元/天 解锁文章
8464

被折叠的 条评论
为什么被折叠?



