So I just want to share this little achievement of mine, I know it's kinda easy for some to make this but for me as a beginner, it's very satisfying. So I made a simple blockchain using a Programming language which is
Python. Some of you already know what Python is, it's a programming language that is similar to c+, java and many more. You can use it to manipulate modules especially advanced devices to work based on your instructions.
I made a twist here, I'm actually doing this experiment by using my Raspberry Pi. --
It's kinda basic though but for me, it's another learning that I've achieved today.
So these are the codes that I've used on my blockchain.
import datetime
import hashlib
class Block:
blockNo = 0
data = None
next = None
hash = None
nonce = 0
previous_hash = 0x0
timestamp = datetime.datetime.now()
def __init__(self, data):
self.data = data
def hash(self):
h = hashlib.sha256()
h.update(
str(self.nonce).encode('utf-8') +
str(self.data).encode('utf-8') +
str(self.previous_hash).encode('utf-8') +
str(self.timestamp).encode('utf-8') +
str(self.blockNo).encode('utf-8')
)
return h.hexdigest()
def __str__(self):
return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nHashes: " + str(self.nonce) + "\n--------------"
class Blockchain:
diff = 20
maxNonce = 2**32
target = 2 ** (256-diff)
block = Block("Genesis")
dummy = head = block
def add(self, block):
block.previous_hash = self.block.hash()
block.blockNo = self.block.blockNo + 1
self.block.next = block
self.block = self.block.next
def mine(self, block):
for n in range(self.maxNonce):
if int(block.hash(), 16) <= self.target:
self.add(block)
print(block)
break
else:
block.nonce += 1
blockchain = Blockchain()
for n in range(10):
blockchain.mine(Block("Block " + str(n+1)))
while blockchain.head != None:
print(blockchain.head)
blockchain.head = blockchain.head.next
credits to howCodeORG of github.The code is already existing but the twist here is I used my RPi.
I also know that some of you aren't familiar with this kind of software so here it goes.
Once I put all of the codes in the terminal of Rpi, it's now ready to run.
This is the output of blockchain.py.
It generates its own Block Hash and Hashes. You can also try it on your pc/laptop, RPi is also applicable since it's the device that I've used to show this.
--
Thanks for reading!