区块链初探

2018-12-21  本文已影响27人  拾丨玖

最近懒到不想写字

package block

import (
    "strconv"
    "bytes"
    "crypto/sha256"
    "time"
)

// 区块结构
type Block struct {
    Timestamp     int64  // 时间戳
    Data          []byte // 当前区块 存放的信息
    PrevBlockHash []byte // 上一个区块的 加密hash
    Hash          []byte // 当前区块的Hash
}

// 计算hash值
func (self *Block) SetHash() {
    // 将本区块的timestamp, data, preBlockHash -----> hash
    timestamp := []byte(strconv.FormatInt(self.Timestamp, 10))
    // 拼接
    headers := bytes.Join([][]byte{self.PrevBlockHash, self.Data, timestamp}, []byte{})
    // SHA256加密
    hash := sha256.Sum256(headers)
    self.Hash = hash[:]
}

// 新建区块API
func NewBlock(data string, prevBlockHash []byte) *Block {
    // 生成一个区块
    block := Block{}
    block.Timestamp = time.Now().Unix()
    block.Data = []byte(data)
    block.PrevBlockHash = prevBlockHash
    block.SetHash()
    return &block
}

// 创建区块链结构体
type BlockChain struct {
    Blocks []*Block // 有序的区块链
}

// 将区块添加到区块链中
func (self *BlockChain) AddBlock(data string) {
    // 获得当前 前驱区块
    prevBlock := self.Blocks[len(self.Blocks)-1]
    // 创建新区块
    newBlock := NewBlock(data, prevBlock.Hash)
    // 添加到blocks
    self.Blocks = append(self.Blocks, newBlock)
}

// 区块链=创世块+区块。。。。。+区块

// 创建创世块
func NewGenesisBlock() *Block {
    genesisBlock := Block{}
    genesisBlock.Data = []byte("GenesisBlock")
    genesisBlock.PrevBlockHash = []byte{}
    return &genesisBlock
}

// 新建区块链
func NewBlockChain() *BlockChain {
    blockChain := BlockChain{}
    blockChain.Blocks = append(blockChain.Blocks, NewGenesisBlock())
    return &blockChain
}

package main

import (
    "block"
    "fmt"
    "os"
)

func main() {
    // 创建区块链
    bc := block.NewBlockChain()
    var cmd string
    for {
        fmt.Println("1: 添加")
        fmt.Println("2: 遍历")
        fmt.Println("3: 退出")
        fmt.Scanf("%s", &cmd)

        switch cmd {
        case "1":
            // 添加
            fmt.Println("输入数据")
            input := make([]byte, 1024)
            os.Stdin.Read(input)

            bc.AddBlock(string(input))

        case "2":
            // 遍历
            for i, value := range bc.Blocks {
                fmt.Println("+++++++++++++++++++")
                fmt.Println("第 ", i, "个 区块信息:")
                fmt.Printf("prevBlockHash: %x\n", value.PrevBlockHash)
                fmt.Printf("Data: %s\n", value.Data)
                fmt.Printf("Hash %x\n", value.Hash)
                fmt.Println("+++++++++++++++++++")
            }

        default:
            // 退出
            return
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读