引用

译者注:随着比特币的不断发展,它的底层技术区块链也逐步走进公众视野,引起大众注意。本文用不到50行的Python代码构建最小的数据区块链,简单介绍了区块链去中心化的结构与其实现原理。

尽管一些人认为区块链是一个等待问题的解决方案,但毫无疑问,这种新技术是计算机的奇迹。但是,区块链到底是什么呢?

区块链

它是比特币或其他加密货币进行交易的数字账本,账本按时间顺序记录并对外公开。

在更一般的术语中,它是一个公共数据库,新数据存储在一个名为块的容器中,并被添加到一个不可变链(后来的区块链)中添加了过去的数据。在比特币和其他加密货币的情况下,这些数据是一组交易记录。当然,数据可以是任何类型的。

区块链技术已经催生了新的、完全数字化的货币,如比特币和莱特币,这些货币并不是由中央政府发行或管理的。因此为那些认为今天的银行系统是骗局或终将失败的人带来了新的自由。区块链所包含的以太坊技术对分布式计算进行了变革创新,它引入了一些有趣的概念,比如智能合约。

在本文中,我将用不到50行的Python2代码来做一个简单的区块链。我称它为SnakeCoin。

首先将定义块将是什么样子。在区块链中,每个块都存储一个时间戳和一个索引。在SnakeCoin中,需要把两者都存储起来。为了确保整个区块链的完整性,每个块都有一个自动识别散列。与比特币一样,每个块的散列将是块索引、时间戳、数据和前块哈希的加密哈希。数据可以是你想要的任何东西。

import hashlib as hasher

class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.hash_block() def hash_block(self):
sha = hasher.sha256()
sha.update(str(self.index) +
str(self.timestamp) +
str(self.data) +
str(self.previous_hash))
return sha.hexdigest()
 
1
2
3
4
5
6
7
89
10
11
12114151617
import hashlib as hasher
 
class Block:
  def __init__(self, index, timestamp, data, previous_hash):
    self.index = index
    self.timestamp = timestamp
    self.data = data
    self.previous_hash = previous_hash
    self.hash = self.hash_block()
 
  def hash_block(self):
    sha = hasher.sha256()
    sha.update(str(self.index) +
               str(self.timestamp) +
               str(self.data) +
               str(self.previous_hash))
    return sha.hexdigest()

这一步后有块结构,但现在是创建区块链,所以需要向实际的链中添加块。如前所述,每个块都需要上一个块的信息。但是按照这个说法就有一个问题,区块链的第一个区块是如何到达那里的呢?不得不说,第一个块,或者说是起源块,它是一个特殊的块。在很多情况下,它是手动添加的,或者有独特的逻辑允许添加。

下面将创建一个函数简单地返回一个起源块以便产生第一个区块。这个块是索引0,它具有任意的数据值和“前一个哈希”参数中的任意值。

import datetime as date

def create_genesis_block():
# Manually construct a block with
# index zero and arbitrary previous hash
return Block(0, date.datetime.now(), "Genesis Block", "")
1
256
import datetime as date
 
def create_genesis_block():
  # Manually construct a block with
  # index zero and arbitrary previous hash
  return Block(0, date.datetime.now(), "Genesis Block", "0")

现在已经创建好了起源块,接下来需要一个函数,以便在区块链中生成后续的块。这个函数将把链中的前一个块作为参数,创建要生成的块的数据,并使用适当的数据返回新块。当新的块哈希信息来自前面的块时,区块链的完整性会随着每个新块而增加。如果不这样做,外部组织就更容易“改变过去”,用全新的方式取代已有的链条。这一系列的散列可以作为加密的证据,有助于确保一旦将块添加到区块链,它就不能被替换或删除。

 
def next_block(last_block):
this_index = last_block.index + 1
this_timestamp = date.datetime.now()
this_data = "Hey! I'm block " + str(this_index)
this_hash = last_block.hash
return Block(this_index, this_timestamp, this_data, this_has
1
2
3
4
5
6
 def next_block(last_block):
this_index = last_block.index + 1
this_timestamp = date.datetime.now()
this_data = "Hey! I'm block " + str(this_index)
this_hash = last_block.hash
return Block(this_index, this_timestamp, this_data, this_hash)

大部分的工作已经完成,现在可以创建区块链了。在这次的示例中,区块链本身是一个简单的Python列表。列表的第一个元素是起源块。当然,还需要添加后续的块,因为SnakeCoin是最小的区块链,这里只添加20个新的块。可以用for循环来生成新块。

 
# Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# How many blocks should we add to the chain
# after the genesis block
num_of_blocks_to_add = 20

# Add blocks to the chain
for i in range(0, num_of_blocks_to_add):
block_to_add = next_block(previous_block)
blockchain.append(block_to_add)
previous_block = block_to_add
# Tell everyone about it!
print "Block #{} has been added to the blockchain!".format(block_to_add.index)
print "Hash: {}\n".format(block_to_add.hash)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 # Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0] # How many blocks should we add to the chain
# after the genesis block
num_of_blocks_to_add = 20 # Add blocks to the chain
for i in range(0, num_of_blocks_to_add):
block_to_add = next_block(previous_block)
blockchain.append(block_to_add)
previous_block = block_to_add
# Tell everyone about it!
print "Block #{} has been added to the blockchain!".format(block_to_add.index)
print "Hash: {}\n".format(block_to_add.hash)

下面来测试一下目前产生的区块链。

看到了吧,这就是区块链。如果希望在控制台中查看更多信息,可以编辑完整的源文件并打印每个块的时间戳或数据。

这就是SnakeCoin要提供的所有东西。为了使SnakeCoin规模达到今天生产区块链的规模,必须添加更多的功能,比如服务器层,以跟踪多台机器上的链变化,以及在给定的时间段内限制添加的块数量的工作算法。

原文出处: Gerald Nash   译文出处:黑色巧克力

用不到 50 行的 Python 代码构建最小的区块链的更多相关文章

  1. 50行Python代码构建小型区块链

    本文介绍了如何使用python构建一个小型的区块链技术,使用Python2实现,代码不到50行. Although some think blockchain is a solution waitin ...

  2. 孤荷凌寒自学python第103天认识区块链017

    [主要内容] 今天继续分析从github上获取的开源代码怎么实现简单区块链的入门知识,共用时间25分钟. (此外整理作笔记花费了约34分钟) 详细学习过程见文末学习过程屏幕录像. 今天所作的工作是进一 ...

  3. 【转载】PDB命令行调试Python代码

    转载自这里. (博主按:PDB调试python代码和用GDB调试c++代码很类似) 你有多少次陷入不得不更改别人代码的境地?如果你是一个开发团队的一员,那么你遇到上述境地的次数比你想要的还要多.然而, ...

  4. shell脚本命令 运行python文件&python命令行运行python代码

    单独的python文件运行的时候 报错: 在shell脚本中,运行shell脚本命令:在Python命令行中,运行Python代码.然而,“python hello.py”是一个脚本命令,不是pyth ...

  5. 200行Go代码实现自己的区块链——区块生成与网络通信

    go启动后,可以用telnet登录访问. 注意端口配置写在.env里面. 源码:https://github.com/mycoralhealth/blockchain-tutorial/tree/ma ...

  6. python代码 构建验证码

    1.python代码编写 (随机验证码): #coding: utf-8 import Image, ImageDraw, ImageFont, ImageFilter import string, ...

  7. [C#]200 行代码使用 C# 实现区块链

    文章原文来自:Code your own blockchain in less than 200 lines of Go!,原始文章是通过 Go 语言来实现自己的区块链的,这里我们参照该文章来使用 C ...

  8. 200 行代码使用 C# 实现区块链

    文章原文来自:Code your own blockchain in less than 200 lines of Go!,原始文章是通过 Go 语言来实现自己的区块链的,这里我们参照该文章来使用 C ...

  9. Python创建一个简单的区块链

    区块链(Blockchain)是一种分布式账本(listributed ledger),它是一种仅供增加(append-only),内容不可变(immutable)的有序(ordered)链式数据结构 ...

随机推荐

  1. select简单循环嵌套

    访问学生的物理最高成绩,并且打印出来,单个要打印出所有的信息 在添加几个 and 就可以啦. select  student.gender,student.sname from student whe ...

  2. <a>超链接用作下载

    在a标签里添加  download=""  ,“ ”里面的内容可随意写,比如文件名. <a href="/download/武林秘籍.pdf" downl ...

  3. bind和on的区别

    bind方法与on方法都是事件绑定,但是两者却又有着一个大区别:事件委托 jquery文档中bind和on函数绑定事件的用法: .bind(events [,eventData], handler) ...

  4. Hadoop环境搭建--Docker完全分布式部署Hadoop环境(菜鸟采坑吐血整理)

    系统:Centos 7,内核版本3.10 本文介绍如何从0利用Docker搭建Hadoop环境,制作的镜像文件已经分享,也可以直接使用制作好的镜像文件. 一.宿主机准备工作 0.宿主机(Centos7 ...

  5. Vue的从入门到放弃

    此贴仅记录vue学习路程中遇见的大大小小,形形色色的问题 1.  vue自动打开浏览器配置: 当使用vue 脚手架搭建项目后启动npm run dev,会出现 但是不会自动打开浏览器的,这时候去con ...

  6. exl表格找两个字符间的数据

    例子找的是]XXX,中间的内容 =MID(B2,FIND("]",B2)+1,FIND(",",B2)-FIND("]",B2)-1)   ...

  7. 网址导航18A

    [导航] hao268 百度导航 泡泡导航 35Q网址导航 [名站] 百度 网易 腾讯 新华 中新 凤凰 [邮箱] 163邮箱 126邮箱 Yeah邮箱 QQ邮箱 阿里邮箱 189邮箱 [新闻] 联合 ...

  8. oracle 数据库去重复数据

    delete from 表名 a where rowid !=(select max(rowid) from 表名 b where a.ORDER_ID=b.ORDER_ID) 例:如果重复的数据表是 ...

  9. 干货 | 10分钟玩转PWA

    关于PWA PWA(Progressive Web App), 即渐进式web应用.PWA本质上是web应用,目的是通过多项新技术,在安全.性能.体验等方面给用户原生应用的体验.而且无需像原生应用那样 ...

  10. union: git command

    # switch one tag # warning: if do that, can't commit any change git clone $project_path git checkout ...