输出结果
代码设计
Created on 2018年3月11日
@author: Jason niu
'''
import hashlib #该模块实现了诸多安全哈希和消息摘要算法的通用接口,包括 FIPS 安全哈希算法: SHA1、SHA224、 SHA256、SHA384、RSA的 MD5 等等算法
import uuid #通用唯一标识符 ( Universally Unique Identifier ), 对于所有的UUID它可以保证在空间和时间上的唯一性. 它是通过MAC地址, 时间戳, 命名空间, 随机数, 伪随机数来保证生成ID的唯一性, 有着固定的大小( 128 bit ). 它的唯一性和一致性特点使得可以无需注册过程就能够产生一个新的UUID. UUID可以被用作多种用途, 既可以用来短时间内标记一个对象, 也可以可靠的辨别网络中的持久性对象.
#该类实现简化版的区块包:一个唯一标识符、父节点的哈希值、nonce值、该区块的内容字段。
class Block(object):
def __init__(self, data=None, previous_hash=None):
self.identifier = uuid.uuid4().hex # uuid产生唯一标示
self.nonce = None
self.data = data
self.previous_hash = previous_hash
def hash(self, nonce=None): #利用sha256算法计算区块的哈希值
message = hashlib.sha256()
message.update(self.identifier.encode('utf-8')) #以utf-8格式对identifier进行编码,二进制从低位往高位取出二进制数字
message.update(str(nonce).encode('utf-8'))
message.update(str(self.data).encode('utf-8'))
message.update(str(self.previous_hash).encode('utf-8'))
return message.hexdigest() #hexdigest函数计算整个文件的hash code,返回摘要作为十六进制数据字符串值
def hash_is_valid(self, the_hash):
return the_hash.startswith('0000')
def __repr__(self):
return 'Block<Hash: {}, Nonce: {}>'.format(self.hash(self.nonce), self.nonce)
def mine(self):
cur_nonce = self.nonce or 0
while True:
the_hash = self.hash(nonce=cur_nonce)
if self.hash_is_valid(the_hash):
self.nonce = cur_nonce
break
else:
cur_nonce += 1
# 创建创世区块
block = Block('Hello World')
block.mine()
print(block)
class BlockChain(object):
def __init__(self):
self.head = None
self.blocks = {}
def add_block(self, new_block):
previous_hash = self.head.hash(self.head.nonce) if self.head else None
new_block.previous_hash = previous_hash
self.blocks[new_block.identifier] = {
'block': new_block,'previous_hash': previous_hash,'previous': self.head,
}
self.head = new_block
def __repr__(self):
num_existing_blocks = len(self.blocks)
return 'Blockchain<{} Blocks, Head: {}>'.format(
num_existing_blocks,
self.head.identifier if self.head else None
)
#定义好区块链结构后,下面就开始初始化一条区块链。
chain = BlockChain()
print(chain)
chain.add_block(block)
print(chain)
#for循环,添加更多的区块
for i in range(6):
new_block = Block(i)
new_block.mine()
chain.add_block(new_block)
print(chain)
from datetime import datetime #导入时间日期模块
#该类实现基于Block实现一个支持收支记录格式
class AccountBill(Block):
def __init__(self, content, amount):
t = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data = "{}|{}|{}".format(t, content, amount)
return super(AccountBill, self).__init__(data)
def get_amount(self):
amount = 0
if self.data:
amount = int(self.data.split('|')[2])
return amount
def get_content(self):
content = ''
if self.data:
content = self.data.split('|')[1]
return content
def __repr__(self):
return 'Bill: {}>'.format(
self.data
)
AccountBill('测试', 100)
from collections import OrderedDict
class AccountBook(BlockChain):
def __init__(self):
self.head = None
self.blocks = OrderedDict()
def add_block(self, new_bill):
new_bill.mine()
super(AccountBook, self).add_block(new_bill)
def balance(self):
balance = 0
if self.blocks:
for k, v in self.blocks.items():
balance += v['block'].get_amount()
return balance
def __repr__(self):
num_existing_blocks = len(self.blocks)
return 'AccountBook<{} Bills, Head: {}>'.format(
num_existing_blocks,
self.head.identifier if self.head else None
)
book = AccountBook()
b1 = AccountBill('月薪', 23000)
book.add_block(b1)
b2 = AccountBill('房租消费', -3000)
book.add_block(b2)
b3 = AccountBill('饮食消费', -1200)
book.add_block(b3)
b4 = AccountBill('娱乐消费', -1200)
book.add_block(b4)
b5 = AccountBill('token收入', 1000)
book.add_block(b5)
b6 = AccountBill('搬砖收入', 400)
book.add_block(b6)
b7 = AccountBill('扛水泥收入', 500)
book.add_block(b7)
b8 = AccountBill('学习AI', -1000)
book.add_block(b8)
b9 = AccountBill('学习BlockChain', -800)
book.add_block(b9)
b10 = AccountBill('学习ICO', -10)
book.add_block(b10)
print(book.balance())
for k,v in book.blocks.items():
print(v['block'].data)
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
x_data = []
y_data = []
colors = []
for k,v in book.blocks.items():
bill = v['block']
y_data.append(bill.get_content())
amount = bill.get_amount()
if amount > 0:
x_data.append(amount)
colors.append('blue')
else:
x_data.append(-amount)
colors.append('red')
y_pos = np.arange(len(y_data))
plt.bar(y_pos, x_data, align='center', alpha=0.5, color=colors)
plt.xticks(y_pos, y_data)
plt.ylabel('金额')
plt.title('BlockChain:程序猿记录在区块里的收支记录图——Jason niu')
plt.show()