2021年618京享红包 - 618大促主会场
九阳 Joyoung电磁炉 电陶炉 2200W大功率 家用火锅套装 旋转控温 红外光波加热 H22-x3 赠烤盘
凯迪仕电子锁618狂欢购
有健康 更热爱
美丽雅品牌会员周

区块链开发(一) 原

梨袅 1年前   阅读数 75 0

比特币是由C++开发,其他的以太坊、hyperledger等都是用go开发,除了并发优势,在运维上也很方便。下面也是用go作为开发语言。

先实现一个最简单的区块链,其块只包含时间戳、前一个块的HASH,当前块的HASH以及数据。其中HASH由Timestamp +PrevBlockHash +Data 再用SHA-256计算得来。代码如下:

package main
	import (
		"fmt"
		"strconv"
		"time"
		"bytes"
		"crypto/sha256"
	)

	type Block struct {
	    Timestamp     int64
	    Data          []byte
	    PrevBlockHash []byte
	    Hash          []byte
	}

    type Blockchain struct {
	    blocks []*Block
	}

	func (b *Block) SetHash() {
	    timestamp := []byte(strconv.FormatInt(b.Timestamp, 10))
	    headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})
	    hash := sha256.Sum256(headers)

	    b.Hash = hash[:]
	}

	func NewBlock(data string, prevBlockHash []byte) *Block {
	    block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}}
	    block.SetHash()
	    return block
	}

	func NewGenesisBlock() *Block {
	    return NewBlock("Genesis Block", []byte{})
	}

	func NewBlockchain() *Blockchain {
	    return &Blockchain{[]*Block{NewGenesisBlock()}}
	}

	func (bc *Blockchain) AddBlock(data string) {
	    prevBlock := bc.blocks[len(bc.blocks)-1]
	    newBlock := NewBlock(data, prevBlock.Hash)
	    bc.blocks = append(bc.blocks, newBlock)
	}

	func main() {
	    bc := NewBlockchain()

	    bc.AddBlock("Send 1 BTC to Ivan")
	    bc.AddBlock("Send 2 more BTC to Ivan")

	    for _, block := range bc.blocks {
	        fmt.Printf("Prev. hash: %x\n", block.PrevBlockHash)
	        fmt.Printf("Data: %s\n", block.Data)
	        fmt.Printf("Timestamp: %x\n", block.Timestamp)
	        fmt.Printf("Hash: %x\n", block.Hash)
	        fmt.Println()
	    }
	}

编译执行后,输出结果如下:

Prev. hash: 
Data: Genesis Block
Timestamp: 5a6016f6
Hash: 9ba83b854bdbdb06887b0d070a33d722603c17d4193d28d669ecc0a765ac8d31

Prev. hash: 9ba83b854bdbdb06887b0d070a33d722603c17d4193d28d669ecc0a765ac8d31
Data: Send 1 BTC to Ivan
Timestamp: 5a6016f6
Hash: 6e54323bea1f195df2d7932d6aab12db43925cbc09efe8fd17f059cae74205a7

Prev. hash: 6e54323bea1f195df2d7932d6aab12db43925cbc09efe8fd17f059cae74205a7
Data: Send 2 more BTC to Ivan
Timestamp: 5a6016f6
Hash: 7d3c48b31fb01fd56b64edaa0abec3b48dfc6b920fffac4c5ba49bae4b9d1159

 

 


注意:本文归作者所有,未经作者允许,不得转载

全部评论: 0

    我有话说: