Blockchain その2

– blockchainでは、ジェネシスブロックを含め、一つ前のハッシュを保持して、新しいトランザクションを作る
– 一つのブロックのハッシュ計算に時間がかかるようにすれば、新しく作られるまでに、それまでのハッシュ計算を書き換えられるリスクが減る、
– ブロックを改良する(適当な数字を加えるなど)

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.difficulty = 4
		self.property_dict = {str(i): j for i, j in self.__dict__.items()}
		self.now_hash = self.calc_hash()
		self.proof = None 
		self.proof_hash = None 

	def check_proof(self, nonce):
		proof_string = self.now_hash + str(nonce)
		calced = hashlib.sha256(proof_string.encode("ascii")).hexdigest()
		if calced[:self.difficulty:].count('0') == self.difficulty:
			self.proof_hash = calced 
			return True
		else:
			return False

	def mining(self):
		proof = 0
		while True:
			if self.check_proof(proof):
				break
			else:
				proof += 1
		return proof  


	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 = []
block = Block(0, 0, [], "-")
block.proof = block.mining()
block_chain.append(block)

for i in range(5):
 
    block = Block(i+1, str(datetime.datetime.now()), ["適当なトランザクション"], block_chain[i].now_hash)
    block.proof = block.mining()
    block_chain.append(block)
 
for block in block_chain:
    for key, value in block.__dict__.items():
        print(key, ':', value)
    print("")

[vagrant@localhost python]$ python app.py
previous_hash : –
timestamp : 0
index : 0
proof_hash : 0000a63ece63ab6bc14791cf8bb4930b57f3e102c97040c1ac94c01c7a7bcb4c
property_dict : {‘previous_hash’: ‘-‘, ‘timestamp’: 0, ‘index’: 0, ‘difficulty’: 4, ‘transaction’: []}
difficulty : 4
transaction : []
now_hash : d1f0dc2f2526d9873c958cac696cd4f64b230ebcfcc8537a0bf94645cc2760de
proof : 30621

previous_hash : d1f0dc2f2526d9873c958cac696cd4f64b230ebcfcc8537a0bf94645cc2760de
timestamp : 2019-10-19 14:58:19.290332
index : 1
proof_hash : 0000f827f0eb3f6445cfcdad5ad49f70ad1a3a5821664a003dbcc79b89312acf
property_dict : {‘previous_hash’: ‘d1f0dc2f2526d9873c958cac696cd4f64b230ebcfcc8537a0bf94645cc2760de’, ‘timestamp’: ‘2019-10-19 14:58:19.290332’, ‘index’: 1, ‘difficulty’: 4, ‘transaction’: [‘適当なトランザクション’]}
difficulty : 4
transaction : [‘適当なトランザクション’]
now_hash : a325c83c16377f143b2c18f5658dc3e4963e9c48cfc823641160ff02fe2e285a
proof : 59756

previous_hash : a325c83c16377f143b2c18f5658dc3e4963e9c48cfc823641160ff02fe2e285a
timestamp : 2019-10-19 14:58:19.677796
index : 2
proof_hash : 0000e93839e2be3b31a26ede35f120605d32923f870aab38a7a2593d43e76377
property_dict : {‘previous_hash’: ‘a325c83c16377f143b2c18f5658dc3e4963e9c48cfc823641160ff02fe2e285a’, ‘timestamp’: ‘2019-10-19 14:58:19.677796’, ‘index’: 2, ‘difficulty’: 4, ‘transaction’: [‘適当なトランザクション’]}
difficulty : 4
transaction : [‘適当なトランザクション’]
now_hash : 003c134be0ba4b6118ad86e9914c266980546bd6379a7a2bf94c6cbd3acf1285
proof : 54445

previous_hash : 003c134be0ba4b6118ad86e9914c266980546bd6379a7a2bf94c6cbd3acf1285
timestamp : 2019-10-19 14:58:20.040778
index : 3
proof_hash : 0000f10e20ef472e1c37ed8cd666f25f5483f0f5e5b97a7cc93823f4a82b3a56
property_dict : {‘previous_hash’: ‘003c134be0ba4b6118ad86e9914c266980546bd6379a7a2bf94c6cbd3acf1285’, ‘timestamp’: ‘2019-10-19 14:58:20.040778’, ‘index’: 3, ‘difficulty’: 4, ‘transaction’: [‘適当なトランザクション’]}
difficulty : 4
transaction : [‘適当なトランザクション’]
now_hash : 07ed3179113ea8b90f71189df0a5fe14d86640899b50c2682b7cd0a6259e5d1c
proof : 9815

previous_hash : 07ed3179113ea8b90f71189df0a5fe14d86640899b50c2682b7cd0a6259e5d1c
timestamp : 2019-10-19 14:58:20.096824
index : 4
proof_hash : 0000e2f39590f8aca4422e913d174dbb4ffe3ce94ecb75648e6681627d317a4b
property_dict : {‘previous_hash’: ’07ed3179113ea8b90f71189df0a5fe14d86640899b50c2682b7cd0a6259e5d1c’, ‘timestamp’: ‘2019-10-19 14:58:20.096824’, ‘index’: 4, ‘difficulty’: 4, ‘transaction’: [‘適当なトランザクション’]}
difficulty : 4
transaction : [‘適当なトランザクション’]
now_hash : 85bf9eab363c3f0c0e6fec320e19699a64d760a7fd8bea992e07b3bb62348d64
proof : 72875

previous_hash : 85bf9eab363c3f0c0e6fec320e19699a64d760a7fd8bea992e07b3bb62348d64
timestamp : 2019-10-19 14:58:20.540764
index : 5
proof_hash : 0000da7db9dc07627d53e6c4f9eba2e76f3c7f3bb7cdd1bdb32c4f3242918397
property_dict : {‘previous_hash’: ’85bf9eab363c3f0c0e6fec320e19699a64d760a7fd8bea992e07b3bb62348d64′, ‘timestamp’: ‘2019-10-19 14:58:20.540764’, ‘index’: 5, ‘difficulty’: 4, ‘transaction’: [‘適当なトランザクション’]}
difficulty : 4
transaction : [‘適当なトランザクション’]
now_hash : 131259e11a3679e3f06612e06ea80d13f8bc2b82478a9408a0ad142692ab6fe4
proof : 14094

Python hashlib

hashlib: セキュアハッシュやメッセージダイジェスト用の様々なアルゴリズムを実装。sha256は有名ですよね。
e.x. sha1, sha224, sha256, sha384, sha512, RSA md5

コンストラクタがあり、ハッシュオブジェクトを返す

import hashlib 
m = hashlib.sha256()
m.update(b"National Security Agency")
print(m.digest())

print(m.digest_size)
print(m.block_size)

[vagrant@localhost python]$ python main.py
b’t\xc6!\xc4\xd2\xd3W&r4\xa2\xe2\xa9\x1f\x15k\xb9\xf1\x08\xa9\x10\xb6\xd2\xb5\xe6\x05|\xe2d\x81\xc8\xe6′
32
64

sha224で実行すると
b’\xe9\xf0\xee\xd4F\xd0;-MM\xa1\xc9\x8cY\x05\x1c\x81H\xde8\x95\x94\x0f\xcb\x13he\x89′

hash.update()でオブジェクトを更新
“b”でエンコード
よく使われるのは、md5とsha256

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