Skip to content

Commit 4f8736e

Browse files
jadiaprateekiiest
authored andcommitted
Add BlockChain concept (prateekiiest#160)
1 parent 28ade47 commit 4f8736e

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed
22.4 KB
Loading
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Primitive BlockChain Implementation
2+
3+
![Blockchain-Structure.png](Blockchain-Structure.png)
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/bin/python3
2+
# Primitive implementaion of BlockChain Concept
3+
4+
import hashlib as hasher
5+
import datetime as date
6+
7+
# Block structure
8+
9+
10+
class Block():
11+
def __init__(self, index, timestamp, data, previous_hash):
12+
self.index = index
13+
self.timestamp = timestamp
14+
self.data = data
15+
self.previous_hash = previous_hash
16+
self.hash = self.hashBlock()
17+
18+
# Create hash of block
19+
def hashBlock(self):
20+
sha = hasher.sha256()
21+
sha.update((str(self.index) +
22+
str(self.timestamp) +
23+
str(self.data) +
24+
str(self.previous_hash)).encode())
25+
return sha.hexdigest()
26+
27+
28+
# Create genesis block
29+
30+
def createGenesisBlock():
31+
return Block(0, date.datetime.now(), "Genesis Block", "0")
32+
33+
# Create chain of blocks
34+
35+
36+
def nextBlock(lastBlock):
37+
id = lastBlock.index + 1
38+
timeStp = date.datetime.now()
39+
data = "Block number: " + str(id)
40+
hash256 = lastBlock.hash
41+
return Block(id, timeStp, data, hash256)
42+
43+
44+
# Create blockchain and add genesis block
45+
46+
blockchain = [createGenesisBlock()]
47+
previousBlock = blockchain[0]
48+
49+
50+
# How many blocks to add after genesis block
51+
noOfBlocks = 20
52+
53+
# Add blocks to chain
54+
for i in range(0, noOfBlocks):
55+
# print(f"i value: {i}")
56+
addBlock = nextBlock(previousBlock)
57+
blockchain.append(addBlock)
58+
previousBlock = addBlock
59+
# Broadcast
60+
print(f"Block #{addBlock.index} has been added to blockchain!")
61+
print(f"Hash: {addBlock.hash} \n")

0 commit comments

Comments
 (0)