DEV Community

Pedro Matias de Araujo
Pedro Matias de Araujo

Posted on • Originally published at Medium on

3

Creating a blockchain with less 100 code lines

Creating a blockchain with less than 100 code lines

Photo by Thought Catalog on Unsplash

The basic concept of blockchain is very simple: a distributed database that maintains a continuously growing list of ordered records.

The blockchain is a term normally associated with Bitcoin and/or Ethereum, but blockchain is more than that, blockchain is the technology behind these, and behind any other cryptocurrency.

There is a lot of other’s uses for blockchain, per example, games (CryptoKitties) or also blockchain+IOT(Internet of things), and this is just the start for the technology.

One simply image about the blockchain’s concept

The blockchain is, like the name said, one chain of blocks, so, we have the first class, the Block.

In this stage my block has the attributes:

  • index — the block index the position in the chain
  • timestamp — date and time that the block was added in Blockchain
  • data — the data value, in other words, what you want to save
  • previous hash — the hash of the block index -1
  • hash — the hash of the block

If you don’t know what’s hash, I did explain in my last post here.

You will see some things interesting in the picture and here I will explain a little bit:

  • let more OOP the function isValid is for each block respond if he is valid
  • The constructor defines all the things in the block
  • the function “update” is to update the dict when reading from a file, this is for saving the data for future
  • calculating the hash for previously saved files, to convert always to the same encode, because, differents encodes have different characters and different characters produce different hashes.

So this is a chain valid, if the block was changed, the current block will know, and make yourself invalid, and if any previous block was changed, the chain will know, and all the chain will be invalid. That is the concept that makes the data save in Blockchain immutable.

So looking in our second class, Blockchain, it looks like:

So, the blockchain class create the blocks and look for any problem in the chain, and this class is responsible for saving in a simple JSON file and read from him. Our first version blockchain is ready!! \o/

All the code is below, you can execute and see the output

#!/usr/bin/python3
# coding=UTF-8
# encoding=UTF-8
import json
import os
import hashlib
import datetime
class Block:
def __init__(self, index, data, previousHash='00000'):
self.index = index
self.timestamp = str(datetime.datetime.now())
self.data = data
self.previousHash = previousHash
self.hash = self.calculateHash()
def update(self, dic):
self.__dict__=dic
return self
def calculateHash(self):
return hashlib.sha256(str(self.index).encode('utf-8')
+ self.previousHash.encode('utf-8')
+ str(self.data).encode('utf-8')
+ self.timestamp.encode('utf-8')).hexdigest()
def isValid(self):
return self.hash == self.calculateHash()
def printBlock(self):
return ("\nBlock #" + str(self.index)
+ "\nData: " + str(self.data)
+ "\nTimeStamp: " + str(self.timestamp)
+ "\nBlock Hash: " + str(self.hash)
+ "\nBlock Previous Hash: " + str(self.previousHash)
+"\n---------------")
class BlockChain:
def __init__(self, file="block.chain"):
self.chain = [Block(0, "Genesis")]
self.file=file
def getLatestBlock(self):
return self.chain[len(self.chain)-1]
def getNextIndex(self):
return self.getLatestBlock().index + 1
def generateBlock(self, data):
self.chain.append(Block(self.getNextIndex(), data, self.getLatestBlock().hash))
def isChainValid(self):
for i in range (1, len(self.chain)):
if not self.chain[i].isValid():
return False
if self.chain[i].previousHash != self.chain[i-1].hash:
return False
return True
def printBlockChain(self):
return ''.join([self.chain[i].printBlock() for i in range(1, len(self.chain))])
def save(self):
if(self.isChainValid()):
with open(self.file, 'w') as f:
f.write(json.dumps(self, default=lambda obj: obj.__dict__))
else:
print("Not saved the chain!")
def open(self):
if(os.path.exists(self.file)):
with open(self.file) as f:
data = json.load(f)
self.__dict__ = data
self.chain = [Block("","").update(dic) for dic in data["chain"]]
def main():
blockchain = BlockChain()
blockchain.generateBlock("Hello World!")
blockchain.generateBlock(3)
blockchain.generateBlock({"account": 123123, "mount": 100})
print(blockchain.printBlockChain())
print ("Chain valid? " + str(blockchain.isChainValid()))
blockchain.save()
blockchain.chain[1].data = "Hello Darkness my old friend!"
print(blockchain.printBlockChain())
print ("Chain valid? " + str(blockchain.isChainValid()))
blockchain.save()
test = BlockChain()
test.open()
print(test.printBlockChain())
print ("Chain valid? " + str(test.isChainValid()))
test.save()
if __name__ == '__main__':
main()
view raw blockchain.py hosted with ❤ by GitHub

In this version of our blockchain, we not implemented the Proof of Work, the idea first is created the blockchain and guaranteed the chain’s integrated. That will be my next step.

I created a project that you can follow in GitHub, I will increment more and more my blockchain, if you have interesting just follow me, I will write some posts about all the process.

P.S: I am not an expert in the blockchain, so any problem, code fix, or tips, this is will be very welcome to comment below and will help some peoples too. Or you can talk to me privately in the LinkedIn.

See you soon!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs