前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2.2 实现区块类结构,实现交易方法

2.2 实现区块类结构,实现交易方法

作者头像
Meet相识
发布2018-09-12 17:07:56
3890
发布2018-09-12 17:07:56
举报
文章被收录于专栏:技术专栏

2.2 实现区块类结构,实现交易方法

代码语言:javascript
复制
"""
create by gaowenfeng on 2018/8/25
"""
import hashlib
import json

__author__ = "gaowenfeng"

from time import time

"""
区块的结构
{
"index": 0, 索引
"timestamp": "", 时间戳
"transactions": [
{
"sender": "",
"recipient": "",
"amount": 5
}
],
"proof": "", # 工作量证明
"previous_hash": "" # 上一个区块的hash
}
"""


class Blockchain:

def __init__(self):
self.chain = []
self.current_transactions = []

# 创始区块 工作量证明随意,上一个区块hash值随意
self.new_block(proof=100, previous_hash=1)

def new_block(self, proof, previous_hash=None):

block = {
'index': len(self.chain) + 1, # 链的长度+1
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.last_block)
}

self.current_transactions = []
self.chain.append(block)

return block

def new_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount
})

# 返回上一个区块的索引
return self.last_block['index']+1

@staticmethod
def hash(block):

block_string = json.dumps(block, sort_keys=True)

# hexdigest 是hash过后的摘要信息
return hashlib.sha256(block_string).hexdigest

@property
def last_block(self):
return self.chain(-1) # -1 数组里的最后一个元素
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.08.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 2.2 实现区块类结构,实现交易方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档