├── .gitattributes ├── README.md └── blockchain.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Simple Python Blockchain with MINING! 2 | ===================================== 3 | 4 | This is the source code for howCode's simple Python Blockchain. 5 | 6 | You can watch the video that accompanies this source code here: https://youtu.be/b81Ib_oYbFk 7 | -------------------------------------------------------------------------------- /blockchain.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import hashlib 3 | 4 | class Block: 5 | blockNo = 0 6 | data = None 7 | next = None 8 | hash = None 9 | nonce = 0 10 | previous_hash = 0x0 11 | timestamp = datetime.datetime.now() 12 | 13 | def __init__(self, data): 14 | self.data = data 15 | 16 | def hash(self): 17 | h = hashlib.sha256() 18 | h.update( 19 | str(self.nonce).encode('utf-8') + 20 | str(self.data).encode('utf-8') + 21 | str(self.previous_hash).encode('utf-8') + 22 | str(self.timestamp).encode('utf-8') + 23 | str(self.blockNo).encode('utf-8') 24 | ) 25 | return h.hexdigest() 26 | 27 | def __str__(self): 28 | return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nHashes: " + str(self.nonce) + "\n--------------" 29 | 30 | class Blockchain: 31 | 32 | diff = 20 33 | maxNonce = 2**32 34 | target = 2 ** (256-diff) 35 | 36 | block = Block("Genesis") 37 | dummy = head = block 38 | 39 | def add(self, block): 40 | 41 | block.previous_hash = self.block.hash() 42 | block.blockNo = self.block.blockNo + 1 43 | 44 | self.block.next = block 45 | self.block = self.block.next 46 | 47 | def mine(self, block): 48 | for n in range(self.maxNonce): 49 | if int(block.hash(), 16) <= self.target: 50 | self.add(block) 51 | print(block) 52 | break 53 | else: 54 | block.nonce += 1 55 | 56 | blockchain = Blockchain() 57 | 58 | for n in range(10): 59 | blockchain.mine(Block("Block " + str(n+1))) 60 | 61 | while blockchain.head != None: 62 | print(blockchain.head) 63 | blockchain.head = blockchain.head.next 64 | --------------------------------------------------------------------------------