From 359ebf613e12dd51b63751a4948f135f81263ce6 Mon Sep 17 00:00:00 2001 From: Daxeel Soni Date: Fri, 2 Feb 2018 12:06:48 +0530 Subject: [PATCH] chain.py documented --- blockchain/chain.py | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/blockchain/chain.py b/blockchain/chain.py index 1c48c2f..894696e 100644 --- a/blockchain/chain.py +++ b/blockchain/chain.py @@ -1,3 +1,17 @@ +# -*- coding: utf-8 -*- +# =================================================== +# ==================== META DATA =================== +# ================================================== +__author__ = "Daxeel Soni" +__url__ = "https://daxeel.github.io" +__email__ = "daxeelsoni44@gmail.com" +__license__ = "MIT" +__version__ = "0.1" +__maintainer__ = "Daxeel Soni" + +# ================================================== +# ================= IMPORT MODULES ================= +# ================================================== import hashlib import datetime import json @@ -5,9 +19,13 @@ from colorama import Fore, Back, Style import time import sys -# index, timestamp, previousHash, blockHash, data - +# ================================================== +# =================== BLOCK CLASS ================== +# ================================================== class Block: + """ + Create a new block in chain with metadata + """ def __init__(self, data, index=0): self.index = index self.previousHash = "" @@ -17,10 +35,16 @@ class Block: self.hash = self.calculateHash() def calculateHash(self): + """ + Method to calculate hash from metadata + """ hashData = str(self.index) + str(self.data) + self.timestamp + self.previousHash + str(self.nonce) return hashlib.sha256(hashData).hexdigest() def mineBlock(self, difficulty): + """ + Method for Proof of Work + """ print Back.RED + "\n[Status] Mining block (" + str(self.index) + ") with PoW ..." startTime = time.time() @@ -33,15 +57,27 @@ class Block: print Back.BLUE + "[ Info ] Mined Hash : " + self.hash print Style.RESET_ALL +# ================================================== +# ================ BLOCKCHAIN CLASS ================ +# ================================================== class Blockchain: + """ + Initialize blockchain + """ def __init__(self): self.chain = [self.createGenesisBlock()] self.difficulty = 3 def createGenesisBlock(self): + """ + Method create genesis block + """ return Block("Genesis Block") def addBlock(self, newBlock): + """ + Method to add new block from Block class + """ newBlock.index = len(self.chain) newBlock.previousHash = self.chain[-1].hash newBlock.mineBlock(self.difficulty) @@ -49,6 +85,9 @@ class Blockchain: self.writeBlocks() def writeBlocks(self): + """ + Method to write new mined block to blockchain + """ dataFile = file("chain.txt", "w") chainData = [] for eachBlock in self.chain: