def new_data(data):
# 这里传入字典数据或json数据都可以
required_fields = ["source", "recorder"]
for field in required_fields:
if not data.get(field):
return "Invlaid data"
data["timestamp"] = time.time()
bc.add_new_data(data)
return "Success"
bc = Blockchain()
a = new_data({"source": "香肠加工", "recorder": "小詹"})
print(a)
添加成功:
F:\push\20191027>python block.py
Success
现在数据是在 unconfirmed_data 中,我们需要挖矿,让它成功添加到区块链上:
def new_data(data):
# 这里传入字典数据或json数据都可以
required_fields = ["source", "recorder"]
for field in required_fields:
if not data.get(field):
return "Invlaid data"
data["timestamp"] = time.time()
bc.add_new_data(data)
return "Success"
def get_chain(blockchain):
chain_data = []
for block in blockchain.chain:
chain_data.append(block.__dict__)
return json.dumps({"length": len(chain_data),
"chain": chain_data})
def mine_unconfirmed_transactions(blockchain):
result = blockchain.mine()
if not result:
print("No data need to mine")
print("Block #{} is mined.".format(result))
bc = Blockchain()
a = new_data({"source": "香肠加工", "recorder": "小詹"})
print(a)
mine_unconfirmed_transactions(bc)
输出结果:
F:\push\20191027>python block.py
Success
Block #1 is mined.
现在来看看区块链上是不是有两个区块了(一个创始块,一个我们新增的区块)显示数据:
def get_chain(blockchain):
chain_data = []
for block in blockchain.chain:
chain_data.append(block.__dict__)
return json.dumps({"length": len(chain_data),
"chain": chain_data})
print(get_chain(bc))
class Point:
__slots__ = 'x', 'y', 'z'
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
>>> ob = Point(1,2,3)
>>> print(sys.getsizeof(ob))
64