Constructing a Simple Blockchain using PYTHON

Reading Time: 6 minutes

– by Aman Pandey

 

What does the path consist?

The goal of this article is to let you know about a BASIC BLOCKCHAIN structure by making a sample blockchain by using a Scripting language Python.

And a small assignment at the last.

The information about the following will be provided on the further articles:

    • various applications of blockchain and at various levels
    • use blockchain to create your own cryptocurrency
    • use of blockchain to create a file deployment system

and Many More…

This article will, for right now, will not have information about deploying your own Blockchain Application, and creating a distributed and decentralized file sharing system.

If you are just interested with how to create a blockchain Jump directly to CONSTRUCTING even I would have done that…

So, let’s start to learn something new……

What is Blockchain?

Back in 2008, some mysterious Person/group of persons named SATOSHI NAKAMOTO released a whitepaper  named Bitcoin: A Peer to Peer Electronics Cash System (I suggest that you read the paper to understand how it was presented to the world) in which BITCOIN was described to be a BLOCKCHAIN based technology,

    • a completely trustless (though the meaning is exactly the opposite, it actually means no trust issues)
    • Distributed
    • Decentralised
    • and, Encrypted

technology that can actually serve as a new form of currency which has its value just as a Stock Share and transaction just like a Barter system.

So, right now before turning this article into a History(story) or market revolutionalizing technology journey let’s start some keyboard ticking and see where we are able to implement key points of a Blockchain, though I will provide you enough resources to read more about emergence and have an intuitive idea about its potential.

Let’s get started…

Design and Features

So, let us begin with the basic design of blockchain by understanding how does it implement its key features.

Before explaining further I want you to go through this wonderful video about blockchain. So we shall jump directly to the technical part. It will let you understand most of the things.

Now after this you must have understood the basic structure of Blockchain.

It is a distributed and decentralized ledger system which provides a TAMPER free service to store records.

Constructing a Simple Blockchain using PYTHON

Image Source: https://i.stack.imgur.com/hDDzg.png

Constructing:

Constructing a Simple Blockchain using PYTHON

Prerequisites:

    • Python 3.6 (a basic python would work but if you don’t know any about it don’t worry it’s very simple and I will try to give an intuitive idea about what I am using and why.)
    • a cool text editor would work well
      > Sublime Text 3 (choose according to the platform you have, it’s lightweight and good)n
      > Atom (the best one to use, has an extension for a terminal)
    • LINUX (Suggested, It’s better to switch to Linux now if you really have to do some good)

                                                                                                                                                          ……that’s it for now, its basic

Let us start by creating a BLOCK:

-> BLOCK:-

We’ll start by creating a class of simple BLOCK using Python:

Constructing a Simple Blockchain using PYTHON

class block:
      def __init__ (self, timestamp, data, previousHash = ' '):
         self.timestamp = timestamp
         self.data = data
         self.previousHash = previousHash
         self.hash = #TODO function calculateHash()

Just have a look at this block we have 4 arguments. Of course, self is working for self-element initialization, for those who don’t understand just understand that it is a kind of PYTHON convention of constructors.

Also that we haven’t included hash in the block argument as it will be calculated and stored inside the function itself #TODO.

Now let’s write the function to calculate hash the block:

def calculateHash(self):
    return sha256((str(self.timestamp) + str(self.data) + \
                str(self.previousHash).encode()).hexdigest())

Now, few points to note here are

    • use of encode() and in the return line hexdigest()
      → so the answer for that is you need to encode every text before hashing, I’ll try to cover it in further blogs.
      → and to convert hash object into a string  we need to use the hexdigest function
    • and yes, for sha256 you need to import hashlib library, and also you need to convert everything into a string before hashing it
  • Also, we need to include time for timestamp

So the code for blocks looks like: –

from hashlib import sha256
import time
class block:
      def __init__ (self, timestamp, data, previousHash = ' '):
         self.timestamp = timestamp
         self.data = data
         self.previousHash = previousHash
         self.hash = # TODO
      def calculateHash(self):
         return sha256((str(self.timestamp) + str(self.data) + \ str(self.previousHash).encode()).hexdigest())

and now let’s begin with our Blockchain class definition:

-> BLOCKCHAIN:-

Genesis Block: the very first block of the blockchain is termed as a genesis block. And it generally can have any data. So we need to initialize our blockchain with it if we don’t have any block in the BLOCKCHAIN. We will have the following structure:

Data → “genesisBlock”

previousHash → “00000”

class blockchain:
      def __init__(self):
         self.chain = [self.createGenesis()]
      def createGenesis(self):
         return block(time.ctime(), "genesisBlock", "00000")

So this is our blockchain which gets initialized with a list named chain, everytime a new class object is created. We’re still having some functions to add to it.

-> MINING:-

Whenever a new transaction is made, and a new block is created and added to the blockchain, the complete process is termed as mining.

As to make blockchain simple for this very first blog, I am not going to put any complex mining functions and verification algorithms for now. Just deal with simple mining.

So, the mining functions will be having to take input from the user and create a block/node for it.

So, before making mining, we have to deal with taking the user’s input and start mining:

  • Starting a Blockchain
  • CEVcoin = blockchain()
  • Taking user input and creating a block
  • data = input()
  • Writing mineBlock():

This function is the part of the blockchain so has to be written inside blockchain. Hence our code  with the function of adding nodes looks like:

from hashlib import sha256
import time
class block:
  def __init__ (self, timestamp, data, previousHash = ' '):
    self.timestamp = timestamp
    self.data = data
    self.previousHash = previousHash
    self.hash = self.calculateHash()
  def calculateHash(self):
    return sha256((str(self.timestamp) + str(self.data) + str(self.previousHash).encode()).hexdigest())
class blockchain:
  def __init__(self):
    self.chain = [self.createGenesis()]
  def createGenesis(self):
    return block(time.ctime(), "genesisBlock", "00000")
  def mineBlock(self, data):
    node = block(time.ctime(), data, self.chain[-1].hash)
    # mining a new block to the blockchain
    self.chain.append(node)
CEVcoin = blockchain()
data = input()
# sending data to get mined
print(“\n\nMining new block……..”)
CEVcoin.mineBlock(data)

*do note down the self.calculateHash() application in def __init__ function of block

Well, this the BACKBONE of every BLOCKCHAIN.

Its applications are at many places. Bitcoin is one of them. Refer links at the bottom for them.

One last thing I’ll do is to print the Blockchain we just made:

def printBlockchain(self):
    for i in range(len(self.chain)):
      print("\n-----Block ", i ,"---------\n timestamp = "\
            , self.chain[i].timestamp,"\n data = ", \
             self.chain[i].data, "\n previousHash = ",\
               self.chain[i].previousHash,"\n hash = ", \
                  self.chain[i].hash)

Just add it inside the class blockchain().

And here, you are done with your first blockchain cryptocurrency

For complete CODE refer : https://github.com/johnsoncarl/Blog-CEVcoin

*i’ll add more blogs with its applications like

  • Making a ledger system
  • Making your own cryptocurrency
  • Regarding P2P network based blockchain

**Please do like & share this blog if you really like it. And comment if any doubts.

Blog by:

Aman Pandey

2nd Year, Civil Engineering, SVNIT.

You can also have a look at my team Project with Ujjwal Kumar – LinkedIn & Hrishabh Sharma – LinkedIn, another CEV members @ Rajasthan DIGIFEST 2k18 Online hackathon – a 36 hours hackathon held on 6 July 2018 on making a cryptocurrency RAJCOIN for Rajasthan Govt @ the following Github link.

https://github.com/Sharma-Hrishabh/digifest2k18

You need to follow the complete instructions given in readme. SO, KEEP PATIENCE.

Extra Resources to read:

Assignment:

Now the assignment is that, make your own crypto coin and mail the code as a zip file to my email id aman0902pandey@gmail.com.

**you can ask any doubts regarding this @ the email address provided above.

Please give a thumbs up and share if you really like the blog.

NOTE: this is only for Educational purposes and not for commercialization.

Cheers…

Why has our Education System Failed?

Reading Time: 3 minutes

Education has been a problem in our country and lack of it has been blamed for all sorts of evil for hundreds of years. The rate of progress is since colonial times is that we established IITs, IIMs, law schools and other institutions of excellence but to get admission is far more difficult as students now routinely score 90% marks so that even students with 90+ percentage find it difficult to get into the colleges of their choice. When a student is interested in science and technology related studies cannot, in most of the cases, be admitted into his desired college why?? A simple answer, many genius minds who are not interested in that field, study hard and reach the same but ultimately change their domain after their graduation which leads to another question why do they do such things??

Why has our Education System Failed?

Similarly, another simple answer, OUR EDUCATION SYSTEM as sometimes due to our great education system our parents force us to study hard and secure our future but are not concerned about what exactly an individual wants to do. In this matter parents cannot be completely blamed as they want their child to have a secure and a safe future, the only thing to be blamed is our education system where children are not guided properly (At an early age in secondary and primary) as what should they do in their future life. Some schools provide such great opportunities and education that many students educate with a goal and achieve that goal and rich to great highs in their life but what about other students who cannot afford such fees. Creating a few more schools or allowing hundreds of colleges and private universities to mushroom are not going to solve the crisis of education in India. And a crisis it is – we are in a country where people are spending their parent’s life savings and borrowed money on education – and even then not getting a standard education, and struggling to find employment of their choice. In this country, millions of students are the victim of an unrealistic, pointless, mindless rat race. The mind-numbing competition and rote learning do not only crush the creativity and originality of millions of Indian students every year, it also drives brilliant students to commit suicide. We also live in a country where the people see education as the means of climbing the social and economic ladder. If the education system is failing – then it is certainly not due to lack of demand for good education, or because a market for education does not exist.

Why has our Education System Failed?

 

Blog by:

Deep Jariwala.

3rd Year, Electronics and Communications, SVNIT.

 

Should we be interplanetary or rather focus on making Earth a better place?

Reading Time: 2 minutes

Friday, 3rd of August marked the commencement of the weekly CEV group discussion for the academic year 2018-19 with the topic:

“Should we be interplanetary or rather focus on making Earth a better place?”

Should we be interplanetary or rather focus on making Earth a better place?  

The purpose was to look at it from an engineering point of view. And to discuss the problems we would face in becoming an interplanetary species. The following points are the minutes of the group discussion that we CEVians had conducted :

  • Viruses may infect humans due to interplanetary travels and may lead to untreatable diseases.
  • Time span required to completely settle on another planet and studying the chemical composition there would be challenging.
  • The uneducated audience is a basic problem.
  • Increasing population may decrease resource per person.
  • Problems: transferring masses, resources, data collection.
  • Classifications of civilization can be done according to needs.
  • Calculations are just hypothesis can be proved wrong.
  • May lead to the war situation, for example, ELYSIUM.
  • Competition among the countries to conquer another planet may help in developing new ways and may give better results.
  • Interplanetary travel would be for limited citizens, therefore Earth has to be made liveable for the majority of mass.
  • Problem: new inventions may lead to decreased use of renewable resources
  • Outer space should be explored to find new renewable resources.
  • Other option like underwater cities may help.
  • Unexplored oceans may be explored well.
  • Government expenditure on researches should be made up marked.
  • Materials required to build houses deep water are a great challenge and hence should be given more research time.

Should we be interplanetary or rather focus on making Earth a better place?

Conclusion:
Civilization and education are the foremost before actually shifting our population. At the same time, the organization must compete among themselves to bring the best solutions, as earth’s life should also be unmarked. Space exploration may also help in making earth a better place, still keeping the civilization transfer on another planet our secondary goal. Making the place where we already live is better than doing some probabilistic research. But even technical advancement in creating artificial environment may not help in biological conditions. Proper calculation of resources is also needed. It is the need of the hour that each citizen takes individual responsibility in making Earth a better place and asking others to do the same.

 

Minutes by:

Aman Pandey

2nd Year, Civil Engineering, SVNIT.

CEV Orientation 5.0

Reading Time: 2 minutes

CEV Orientation 5.0

On 6th of October 2017, CEV embarked its presence among the batch of 2021 by conducting an orientation of one of most unique and special student chapter of SVNIT.

The CEV core team of the pre-final year students conducted a very healthy discussion with the freshers and gave them great advice about college life. The Do’s and the Don’ts and the consequences of bad indulgence were also shared among them.

CEV Orientation 5.0 CEV Orientation 5.0

CEV Orientation 5.0 CEV Orientation 5.0

CEV Orientation 5.0 CEV Orientation 5.0

CEV Orientation 5.0

The wise words of Darshan Rajput (Former President, CEV) also encouraged and motivated the freshers. He had a truthful and honest discussion session with them and directed them towards leading a fabulous college life. Also, we had video messages from alumni all around the world which also made this orientation really special.

Apart from that, CEV also encouraged freshers to explore all other student chapters of our college and find out their passion and field of interest. The general discussion consisted of suggesting freshers with great books, must watch TV series and movies. Ways to keep a balance between academics and extra-curriculum was also laid stress upon.CEV Orientation 5.0

 

‘Apun ka business’ vs. ‘Ek secure life’

Reading Time: 3 minutes

Is working for a startup better for me or should I join a large MNC? Is it better to be a big fish in a small pond or a small fish in a big pond? We all have had these questions come to our mind at one time or the other. Let’s examine both the options and see if we can bring an end to this debate.

Having the next ‘big thing’ is the new cool. We all have fantasized about having our own billion dollar company at one time or the other with our friends. Startups are considered fun and are known for their employee-centric work cultures. An important thing that differentiates a startup from a regular business is the fact that a startup is built to grow, to adapt to fast change.

Let’s have a look at some of the skills that one requires for being a successful entrepreneur.

  • Public speaking:

Public speaking comes in handy when marketing your product to the masses. Steve Jobs is a perfect example of how the charisma of one’s personality can help form the image of the company.

  • Financial skills:

How much should I give away 15% in my company for ? Is buying this company worth it ? These are some of the few questions which one can answer when one is well versed in the jargons of Wall Street.

  • Human relation skills:

Entrepreneurship is all about the people. You can’t expect to run a successful startup if you can’t make people work for you.

In the last couple of years, the startup ecosystem in India has been given an impetus by the recent policies of the Indian Government especially the likes of Startup India program, Make In India program and AIC (Atal Incubation Centres ).

A corporate job is commonly associated with security. It is often made to seem that there is no personal development for a person who decides to work for another company instead of building his own. But I think it is not true. We have, as examples, our very own Satya Nadella and Sundar Pichai who depict the possibility of corporate success. A corporate scenario provides plenty of opportunities for one’s self-improvement. Skills like public speaking, marketing and finance prove really handy in AC corporate job as well.

Making it big in the startup world is a journey in itself. For becoming successful as an entrepreneur, one has to exercise a lot of self-awareness and know himself or herself deeply. In a startup, one has the tremendous job of building one’s own distribution network which is not the case in a job. A startup provides opportunities for great growth in a small period of time which is usually not available in case of a corporate job. Usually, growth in corporate life comes slowly.’Slow and steady wins the race’ aptly applies to the corporate scenario.

So, what should one go for ?

According to me, one must definitely go for a startup if he/she thinks that his/her idea can bring something new to the table.

But, as Rajat Khanna of TVF Pitchers (if you guys haven’t watched it  yet, watch it, it’s brilliant ) says :

‘Apun ka business’ vs. ‘Ek secure life’

 

Startups, if done just as another option to improve one’s life prospect, there are more chances of it to fail. According to some statistics, as much as 75% of all venture-backed startups fail.

Sometimes an entrepreneur’s life becomes too monotonous. One has to sacrifice a lot of things that one can experience as a normal person. In this regard, a well-suited job may serve you better in helping you experience all the different joys that life has to offer you.

So, what do you think about entrepreneurship ? Is it overhyped and glorified ? Is a 9-to-5 job really adventureless or is it just another cliche ? Let’s talk !

 

Blog by:

Vineet Bhat

2nd Year, Electronics and Communication, SVNIT.

Solar Energy – Shining the light on solar

Reading Time: < 1 minute

Solar Energy - Shining the light on solar

Rahul Singh & Parth Shah, Electrical Engineering (Batch of 2017), SVNIT gave a talk on Solar Energy on 5th of April 2016.

The talk basically covered a lot of stuff about solar energy, from the simplest working and interpretation of solar cell to huge solar power plants. Also, interesting facts and technological implementation of solar cells were discussed in great depth.

We witnessed a plethora of audience from first yearites to pre-final year students who gained knowledge and got their doubts and problems solved. Also, the orators explained to us about the research work that they have done in the same field. Tesla solar roof and many such real-life examples were taken to keep up the interest among the audience, and an in-depth working of their technology was discussed.

Rahul Singh being a MITACS scholar, having done his summer research internship at the University of Manitoba, shared his experience and research work done there. Great insights were provided and also guidance was given on how to pursue solar RnD as a career.

Commercialization of Technology Innovation: Issues and Challenges

Reading Time: < 1 minute

Commercialization of Technology Innovation: Issues and ChallengesCEV was blessed to have Dr. Hemant Kumar Bulsara, Applied Mathematics and Humanities Department, SVNIT to give a talk on Commercialization of Technology Innovation: Issues and Challenges.

The audience was given knowledge about patent and how it has just become a protective mechanism for researchers and technologists rather than commercializing it and implement it among the greater good among the mass. Also, various case-studies were discussed and analyzed.

Commercialization of Technology Innovation: Issues and Challenges

Dr. Bulsara had a great interactive session. A pinch of humor and honesty was sprinkled throughout the discussion. The QnA session was also very interesting as it helped the audience visualize various problems from a very different point of view.

Commercialization of Technology Innovation: Issues and Challenges

 

CEV Orientation 4.0

Reading Time: < 1 minute

Orientation

September of 2016 was the time when Cutting Edge Visionaries (CEV) showcased its presence before the batch of 2020. It was unlike any normal orientation of student chapter of our college because the hosts were not merely restricted to informing us about the technical stuff but more importantly, they were sharing their true and honest stories with us, which helped the freshers to identify the various spectrum of college life.

In this Orientation program, students were given information about the college, life at college, facilities provided by the college, proper methods of utilizing the provided facilities, how can they be productive in the spare time etc. They were provided with various information, from which projects they can do to which TV shows and movies they should watch. Apart from this, they were also given knowledge about “Must Visit Places of Surat”, the famous delicacies and were given a glimpse of the culture and festivals celebrated here.

Special brochures were prepared and distributed among students which showcased various learning platforms, area of innovations, must watch TV series and movies, courses for academic and non-academic stuff and various other details which would be of great help to fresher.

CEV - Handout