Skip to content

Instantly share code, notes, and snippets.

@Seregamil
Last active November 20, 2019 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Seregamil/a65ec8b87d7c6b0d61e50d867361f81f to your computer and use it in GitHub Desktop.
Save Seregamil/a65ec8b87d7c6b0d61e50d867361f81f to your computer and use it in GitHub Desktop.
import os
import hashlib
import time
import json
class Blockchain(object):
def __init__(self):
self._chain_list = [] # initialize empty list
def add_block_to_chain(self, block):
self._chain_list.append(block)
#self.check_chain_validity()
def add_genesis_block(self, block):
self._chain_list.append(block)
def get_latest_block(self):
return self._chain_list[-1]
def get_total_blocks(self):
return len(self._chain_list)
def check_chain_validity(self):
previous_hash = "0"
for block in self._chain_list:
if str(previous_hash) != str(block.prev_hash):
print("Block #" + str(block.index - 1) + " in not valid")
previous_hash = block.calculate_block_hash()
def load(self):
for _, _, files in os.walk("chain/"):
for file in files:
with open("chain/" + file, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
book = Book(data['book_info']['name'],
data['book_info']['author'],
data['book_info']['publishing_company'],
data['book_info']['rent_owner'],
data['book_info']['rent_timestamp'])
block = Block(data['index'], data['timestamp'], book)
block.prev_hash = data['prev_hash']
self.add_block_to_chain(block)
class Block(object):
def __init__(self, index, timestamp, book_info):
self.index = index
self.prev_hash = "0"
if chain.get_total_blocks() != 0:
self.prev_hash = chain.get_latest_block().calculate_block_hash()
self.timestamp = timestamp or time.time()
self.book_info = book_info
self.data = {
'index': self.index,
'timestamp': self.timestamp,
'block_hash': self.calculate_block_hash(),
'prev_hash': self.prev_hash,
'book_info': self.book_info.get_data()
}
file_path = "chain/" + str(self.index) + '.txt'
if not os.path.isfile(file_path):
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(self.data, file, indent=3, ensure_ascii=False)
print("Block " + str(self.index) + " saved")
def calculate_block_hash(self):
return hashlib.sha256(bytearray(str(self.index) + str(self.timestamp) + str(self.prev_hash) + self.book_info.get_hash(), "utf-8")).hexdigest()
class Book(object):
def __init__(self, name, author, publishing_company, rent_owner, rent_timestamp=0):
self.name = name
self.author = author
self.publishing_company = publishing_company
self.rent_owner = rent_owner
self.rent_timestamp = rent_timestamp or time.time()
def get_hash(self):
return hashlib.sha256(bytearray(str(self.name)
+ str(self.author)
+ str(self.publishing_company)
+ str(self.rent_owner)
+ str(self.rent_timestamp), "utf-8")).hexdigest()
def get_data(self):
return {
'name': self.name,
'author': self.author,
'publishing_company': self.publishing_company,
'rent_owner': self.rent_owner,
'rent_timestamp': self.rent_timestamp,
}
if __name__ == "__main__":
print('Initializing blockchain')
chain = Blockchain()
if len(os.listdir("chain/")) == 0:
print('Generate new blocks')
genesis_book = Book("Два капитана", "Каверин", "ХЗ", "None")
genesis_block = Block(chain.get_total_blocks(), time.time(), genesis_book)
chain.add_genesis_block(genesis_block)
books = {
Book("Бойцовский клуб", "Чак Паланик", "АСТ", "None"),
Book("Дневник памяти", "Николас Спаркс", "АСТ", "None"),
Book("Поющие в терновнике", "Маккалоу Колин", "АСТ", "None"),
Book("Зеленая миля", "Кинг Стивен", "АСТ", "None"),
Book("Крутой поворот", "Спаркс Николас", "АСТ", "None"),
}
for book in books:
block = Block(chain.get_total_blocks(), time.time(), book)
chain.add_block_to_chain(block)
else:
print('Loading exist\'s block\'s')
chain.load()
print('Total blocks: ' + str(chain.get_total_blocks()))
chain.check_chain_validity()
import os
import hashlib
import time
import json
class Blockchain(object):
def __init__(self):
self._chain_list = [] # initialize empty list
def add_block_to_chain(self, block):
self._chain_list.append(block)
#self.check_chain_validity()
def add_genesis_block(self, block):
self._chain_list.append(block)
def get_latest_block(self):
return self._chain_list[-1]
def get_total_blocks(self):
return len(self._chain_list)
def check_chain_validity(self):
previous_hash = "0"
for block in self._chain_list:
if str(previous_hash) != str(block.prev_hash):
print("Block #" + str(block.index - 1) + " in not valid")
previous_hash = block.calculate_block_hash()
def load(self):
for _, _, files in os.walk("chain/"):
for file in files:
with open("chain/" + file, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
book = Book(data['book_info']['name'],
data['book_info']['author'],
data['book_info']['publishing_company'],
data['book_info']['rent_owner'],
data['book_info']['rent_timestamp'])
block = Block(data['index'], data['timestamp'], book)
block.prev_hash = data['prev_hash']
self.add_block_to_chain(block)
class Block(object):
def __init__(self, index, timestamp, book_info):
self.index = index
self.prev_hash = "0"
if chain.get_total_blocks() != 0:
self.prev_hash = chain.get_latest_block().calculate_block_hash()
self.timestamp = timestamp or time.time()
self.book_info = book_info
self.data = {
'index': self.index,
'timestamp': self.timestamp,
'block_hash': self.calculate_block_hash(),
'prev_hash': self.prev_hash,
'book_info': self.book_info.get_data()
}
file_path = "chain/" + str(self.index) + '.txt'
if not os.path.isfile(file_path):
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(self.data, file, indent=3, ensure_ascii=False)
print("Block " + str(self.index) + " saved")
def calculate_block_hash(self):
return hashlib.sha256(bytearray(str(self.index) + str(self.timestamp) + str(self.prev_hash) + self.book_info.get_hash(), "utf-8")).hexdigest()
class Book(object):
def __init__(self, name, author, publishing_company, rent_owner, rent_timestamp=0):
self.name = name
self.author = author
self.publishing_company = publishing_company
self.rent_owner = rent_owner
self.rent_timestamp = rent_timestamp or time.time()
def get_hash(self):
return hashlib.sha256(bytearray(str(self.name)
+ str(self.author)
+ str(self.publishing_company)
+ str(self.rent_owner)
+ str(self.rent_timestamp), "utf-8")).hexdigest()
def get_data(self):
return {
'name': self.name,
'author': self.author,
'publishing_company': self.publishing_company,
'rent_owner': self.rent_owner,
'rent_timestamp': self.rent_timestamp,
}
if __name__ == "__main__":
print('Initializing blockchain')
chain = Blockchain()
if len(os.listdir("chain/")) == 0:
print('Generate new blocks')
genesis_book = Book("Два капитана", "Каверин", "ХЗ", "None")
genesis_block = Block(chain.get_total_blocks(), time.time(), genesis_book)
chain.add_genesis_block(genesis_block)
books = {
Book("Бойцовский клуб", "Чак Паланик", "АСТ", "None"),
Book("Дневник памяти", "Николас Спаркс", "АСТ", "None"),
Book("Поющие в терновнике", "Маккалоу Колин", "АСТ", "None"),
Book("Зеленая миля", "Кинг Стивен", "АСТ", "None"),
Book("Крутой поворот", "Спаркс Николас", "АСТ", "None"),
}
for book in books:
block = Block(chain.get_total_blocks(), time.time(), book)
chain.add_block_to_chain(block)
else:
print('Loading exist\'s block\'s')
chain.load()
print('Total blocks: ' + str(chain.get_total_blocks()))
chain.check_chain_validity()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment