언어/python

블록체인 코드

파아랑새 2018. 3. 13. 18:09
https://bigishdata.com/2017/10/17/write-your-own-blockchain-part-1-creating-storing-syncing-displaying-mining-and-proving-work/
import datetime as d
import hashlib as hash
import os
import pymysql
class Block(object):
def __init__(self, dictionaryV):
"""
index
timestamp : 생성된 시간
data
prev_hash
nonce
hash
"""
for k, v in dictionaryV.items():
setattr(self, k, v)

if not hasattr(self, 'hash'):
print ("test")
self.hash = self.create_self_hash()
# Block Hash generator
def create_self_hash(self):
sha = hash.sha256()
sha.update(self.index +
self.timestamp + # 블록이 생성된 시간
self.data +
self.prev_hash) # 이전 블록의 해쉬값
return sha.hexdigest()

def __dict__(self):
information = {} # type of dictionary
information['index'] = str(self.index)
information['timestamp'] = str(self.timestamp)
information['data'] = str(self.data)
information['prev_hash'] = str(self.prev_hash)
information['hash'] = str(self.hash)
return information

def __str__(self):
return "Block<prev_hash: %s, hash: %s>>" %(self.prev_hash, self.hash)

def blockInformation(self):
print ("==============================================================")
print ("Block-index : {}".format(self.index))
print ("Block-timestamp : {}".format(self.timestamp))
print ("Block-data : {}".format(self.data))
print ("Block-prev_hash : {}".format(self.prev_hash))
print ("Block-hash : {}".format(self.hash))
print ("==============================================================")

def create_first_block():
# index zero and arbitrary previous hash
# dictionary
block_data = {}
block_data['index'] = str(0).encode(encoding='utf-8')
block_data['timestamp'] = str(d.datetime.now()).encode(encoding='utf-8')
block_data['data'] = "Genesis block".encode(encoding='utf-8')
block_data['prev_hash'] = "".encode(encoding='utf-8')
block = Block(block_data)
return block

def generate_header(index, prev_hash, data, timestamp):
retS = str(index) + prev_hash + data + str(timestamp)
retS = retS.encode(encoding='utf-8')
return retS

def calculate_hash(index, prev_hash, data, timestamp):
header_string = generate_header(index, prev_hash, data, timestamp)
sha = hash.sha256() # hash.sha256 객체 생성
sha.update(header_string)
return sha.hexdigest()

def mine(last_block):
index = int(last_block.index) + 1 # 몇 번째 블록인지
timestamp = d.datetime.now() # 생성된 시간
data = "I block #{indx}".format(indx = index)
prev_hash = last_block.hash # 이전 블록의 해쉬
block_hash=calculate_hash(index, prev_hash, data, timestamp)
#--------------------------------------------------
block_data = {} # type of dictionary
block_data['index'] = index
block_data['timestamp'] = timestamp
block_data['data'] = data
block_data['prev_hash'] = prev_hash
block_data['hash'] = block_hash
return Block(block_data)
# --------------------------------------------------

def main():
G = create_first_block()
print (G)
G.blockInformation()
ch1 = mine(G)
ch1.blockInformation()

ch2 = mine(ch1)
ch2.blockInformation()
# 디렉토리 생성 부분____________________________
# chaindata_dir = "chaindata"
# if not os.path.exists(chaindata_dir):
# # make chaindata dir
# os.mkdir(path=chaindata_dir)
# # check if dir is empty from just creation, or empty before
# if os.listdir(chaindata_dir) == []: # 만약 비어 있다면
# # create first block
# first_block = create_first_block()
# #first_block.self_save()
if __name__ == "__main__":
main()