2.1 产生区块
-
定义区块结构体
type Block struct { Index int // 高度 TimeStamp string // 时间戳 BPM int // 交易信息 HashCode string // 哈希 PrevHash string // 上一节点哈希 Validator string // 区块验证者:保存的是哪个节点对当前区块进行了挖矿 }
-
产生首个区块
func GenerateFirstBlock() Block { var firstBlock Block firstBlock.BPM = 100 firstBlock.PrevHash = "0" firstBlock.TimeStamp = time.Now().String() firstBlock.Validator = "创世区块" firstBlock.Index = 1 firstBlock.HashCode = GenerateHashValue(firstBlock) return firstBlock }
-
产生新区块
func GenerateNextBlock(oldBlock Block, BPM int, address string) Block { var newBlock Block newBlock.Index = oldBlock.Index + 1 newBlock.TimeStamp = time.Now().String() newBlock.PrevHash = oldBlock.HashCode newBlock.Validator = address newBlock.BPM = BPM newBlock.HashCode = GenerateHashValue(newBlock) return newBlock } // 计算区块哈希值 func GenerateHashValue(block Block) string { var hashCode = block.PrevHash + block.HashCode + block.TimeStamp + block.Validator + strconv.Itoa(block.BPM) + strconv.Itoa(block.Index) sha := sha256.New() sha.Write([]byte(hashCode)) hashed := sha.Sum(nil) return hex.EncodeToString(hashed) }
2.2 产生区块链
-
通过数组的形式,维护区块链业务
-
创建链
var BlockChain []Block
-
定义网络中的节点结构体
type Node struct { tokens int // 记录有多少币 address string // 节点地址 }
-
模拟权益比例1:2的两个用户挖矿
// 创建创世区块 firstBlock := GenerateFirstBlock() // 将创世区块添加到区块链中 BlockChain = append(BlockChain, firstBlock) // 存放两个炒币者:权益比例1:2 n[0] = Node{1000, "炒币者1"} n[1] = Node{2000, "炒币者2"} // 循环完成,addr前1000为炒币者1,后2000为炒币者2 count := 0 for i := 0; i < len(n); i++ { for j := 0; j < n[i].tokens; j++ { addr[count] = n[i].address count++ } } // 随机选一个矿工 rand.Seed(time.Now().Unix()) rd := rand.Intn(3000) var addr = addr[rd] // 挖矿:挖矿节点就是随机选出的矿工节点 secondBlock := GenerateNextBlock(firstBlock, 200, addr) BlockChain = append(BlockChain, secondBlock) fmt.Println(BlockChain)