chain.py documented

This commit is contained in:
Daxeel Soni 2018-02-02 12:06:48 +05:30
parent 30c0ace50e
commit 359ebf613e
1 changed files with 41 additions and 2 deletions

View File

@ -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: