Py学习  »  区块链

深入浅出区块链基本原理

谢权Spark • 6 年前 • 243 次点击  
维基百科:区块链(英语:blockchain 或 block chain)[1]是用 分布式数据库识别、传播和记载信息的智能化 对等网络, 也称为价值互联网。[2] [3]  中本聪在2008年,于《比特币白皮书》 [4]中提出“区块链”概念,并在2009年创立了 比特币社会网络,开发出第一个区块,即“创世区块”。 [5]区块链是 21 世纪最具革命性的技术之一,但是它仍然处于不断成长的阶段!从技术角度来说区块链不是一种新的技术,而是一种新的协作方式!但与加密解密技术、P2P网络等组合在一起,就诞生了比特币。

区块链作为比特币背后的技术,无需中心服务器,可实现各类存储数据公开、透明、可追溯。原本是比特币等加密货币存储数据的一种独特方式,是一种自引用的数据结构,用来存储大量交易信息,每条记录从后向前有序链接起来,具备公开透明、无法篡改、方便追溯的特点。实际上,这种特性也直接体现了整个比特币的特点。

所以,目前当大家单独说到区块链的时候,就是指的区块链技术,是实现了数据公开、透明、可追溯的产品的架构设计方法,算作广义的区块链。下图就是广义区块链架构图

当然今天这篇文章肯定不会讲广义区块链因为涉及的内容太多了,今天主要是给大家讲讲如何自己动手实现一个简单的区块链,在网上搜区块链架构图的时候搜到这张图片,作者给他取名Naivechain,我觉得蛮好的 Too young Too naive!!! 这也是我目前对区块链的了解程度!

Talk is cheap show me the code !

作为一名专业摄影业余的程序员,当然得用浅显易懂代码来解释什么是NaiveChain!从上面的图我们可以看出一个区块包含了以下内容:

  • index                :区块在链中的位置
  • previousHash  : 前一区块的hash值
  • tiemestamp     : 时间间戳
  • data                  : 存储内容
  • hash                 : 当前区块的hash

package main
 
import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"time"
	"fmt"
)
type Block struct {
	Index     int
	Timestamp string
	Data       string
	Hash      string
	PrevHash  string
}
var Blockchain []*Block
 
func calculateHash(block *Block) string {
	record := strconv.Itoa(block.Index) + block.Timestamp + block.Data + block.PrevHash
	h := sha256.New()
	h.Write([]byte(record))
	hashed := h.Sum(nil)
	return hex.EncodeToString(hashed)
}
 
func generateBlock(oldBlock *Block, data string) *Block {
	newBlock:=&Block{}
	t := time.Now()
	newBlock.Index = oldBlock.Index + 1
	newBlock.Timestamp = t.String()
	newBlock.Data = data
	newBlock.PrevHash = oldBlock.Hash
	newBlock.Hash = calculateHash(newBlock)
	return newBlock
}
 
func main() {
	t := time.Now()
	newBlock := &Block{}
	genesisBlock := &Block{}
	datas:=[]string{"btc","etc","key","eos","bihu","xiequan.info"}
	for k,v:=range datas{
		if k>=1{
			newBlock = generateBlock(Blockchain[len(Blockchain)-1],v)
			Blockchain = append(Blockchain, newBlock)
		}else{
			genesisBlock = &Block{0, t.String(), "创世块", calculateHash(genesisBlock), ""}
			Blockchain = append(Blockchain, genesisBlock)
		}
	}
	for _,v:=range Blockchain{
		fmt.Printf("index: %d\n",v.Index)
		fmt.Printf("data: %s\n",v.Data)
		fmt.Printf("timestamp: %s\n",v.Timestamp)
		fmt.Printf("hash: %s\n",v.Hash)
		fmt.Printf("prevHash: %s\n",v.PrevHash)
	}
}

运行的结果:

好啦,一个简单的NavieChain实现啦,当然真正的区块链并不是这么简单的!但是生成区块的原理是差不多的!如果有什么问题欢迎留言!!!


今天看啥 - 高品质阅读平台
本文地址:http://www.jintiankansha.me/t/mgjCypN8oV
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/9282
 
243 次点击