Blockchain その1

こちらのコードを分解していきます。

import hashlib
import json
import datetime

class Block:
	def __init__(self, index, timestamp, transaction, previous_hash):
		self.index = index 
		self.timestamp = timestamp 
		self.transaction = transaction 
		self.previous_hash = previous_hash 
		self.property_dict = {str(i): j for i, j in self.__dict__.items()}
		self.now_hash = self.calc_hash()

	def calc_hash(self):
		block_string = json.dumps(self.property_dict, sort_keys=True).encode('ascii')
		return hashlib.sha256(block_string).hexdigest()

def new_transaction(sender, recipient, amount):
	transaction = {
		"差出人": sender,
		"宛先": recipient,
		"金額": amount,
	}
	return transaction

block_chain = []
genesis_block = Block(0, 0, 0, "-")
block_chain.append(genesis_block)

transaction = new_transaction("タロウ", "花子", 100)
new_block = Block(1, str(datetime.datetime.now()), transaction, block_chain[0].now_hash)
block_chain.append(new_block)

for key, value in genesis_block.__dict__.items():
	print(key, ':', value)

print("")

for key, value in new_block.__dict__.items():
	print(key, ':', value)

[vagrant@localhost python]$ python app.py
property_dict : {‘transaction’: 0, ‘index’: 0, ‘previous_hash’: ‘-‘, ‘timestamp’: 0}
now_hash : 49f3a23af19229c5a1a12611bdb590f742154a5d11b5018f3f01b740800a5c20
transaction : 0
index : 0
previous_hash : –
timestamp : 0

property_dict : {‘transaction’: {‘宛先’: ‘花子’, ‘差出人’: ‘タロウ’, ‘金額’: 100}, ‘index’: 1, ‘previous_hash’: ’49f3a23af19229c5a1a12611bdb590f742154a5d11b5018f3f01b740800a5c20′, ‘timestamp’: ‘2019-10-18 10:55:22.499513’}
now_hash : b9b57282d7387add7e66d6209f06e4c132ec01cfece9615067bdffeb7b8f4c30
transaction : {‘宛先’: ‘花子’, ‘差出人’: ‘タロウ’, ‘金額’: 100}
index : 1
previous_hash : 49f3a23af19229c5a1a12611bdb590f742154a5d11b5018f3f01b740800a5c20
timestamp : 2019-10-18 10:55:22.499513