A Beginner’s Guide to Blockchain Programming

I had a lot of questions on my quest to understand how Blockchain works. The important one was “How do I build applications on it?”. It took a few weeks of digging up, reading and experimenting to finally get it. I couldn’t find a short but comprehensive guide. Now, that I have some decent understanding, I thought of writing one that could help others. This is a light speed guide, I have kept only the important parts in order to reduce the learning curve.

Chapters

  1. The Purpose of Blockchain
  2. How was the Blockchain invented?
  3. Introduction to Ethereum & Smart Contracts
  4. Programming Smart Contracts on Ethereum
  5. The Way Ahead

The Purpose of Blockchain

Roopa lives in one of the remote areas of Delhi. The government of India has allocated her few resources of food every month. Since she belongs to the BPL(Below Poverty Line) category. The government uses a middleman to distribute these food resources. Only one-third of the allocated food resources reach people like Roopa, the rest is sold by the middleman for profit.

Sara writes fiction books, she publishes them on Amazon. She’s upset because Amazon takes 50% of the sale as commission. That’s unfair because she alone has put in the efforts of writing and marketing.

The problem is middleman is hungry for power and money. Their motto has become “profit at any cost”, to support producers and to empower the poor, we need middlemen to act ethically. That’s almost impossible to achieve, but what if we can replace middleman with an autonomous system?

Since computers don’t have biases they neither need money or power. This could have been Satoshi Namakato’s thought when he invented bitcoin using the blockchain technology in 2008.

How was the Blockchain Invented?

Money has evolved over time, each evolution reduced its cost of production and made their transactions more convenient. Gold coins were costly to produce. The invention of paper currency solved this problem. But, after the invention of computers and internet, people found a better way to make transactions convenient and faster.

To safe keep our lifetime’s earnings and to facilitate digital transactions we need a middleman(bank). This made banks powerful, they can impose a heavy fee on our withdrawals /transactions, sell our private information, etc

Banks hunger for money caused the financial crisis in 2008. Banks failed to respect their customer’s privacy. Their weak security systems gave rise to digital fraud.

The next evolution of money had to solve the following problems.

  1. It shouldn’t be stored with a central entity.
  2. It needs to be highly secure.
  3. It should ensure privacy.

Since fiat currency is controlled by the government, Satoshi had no option but to invent a new currency (Bitcoin). He solved these problems with the help of peer-to-peer networks and cryptography.

DecentralisationCredits : xkcd

Torrents use peer-to-peer technology to share files. The torrent app doesn’t download the file from a central server or a single computer, instead, it connects to the people in its network, finds out who has the file and download it from their computers.

You get the pieces of a file from different computers around the world. If one person in the network goes away, your download isn’t affected because there are other people who can share the file.

Satoshi adopted this technology since it stores money in a decentralized way. No single entity will have control over it.

CryptographyCredits : xkcd

In cryptography, one can digitally sign a message. In order to do this we need three things a public key, private key, and message.

The public key and private key are a set of long characters that are mathematically connected. A public key is public like your username, and the private key is a secret like your password.

A message is an information you want to authorise, ex: “I authorise you to pay John $100”.

If you input the algorithm with a public key, private key and message. The cryptographic algorithm will produce a signature. That is another set of characters unique to the contents of that message.

Public Key -----BEGIN EC PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE50uE+YSxqDgMkFByhpcgTVqXCqHO h68Ljt1z0jklDff/WV7xo+U6o3REBtK/C0/LM+Ef3FB3wR9aXMGNMLb9EA== -----END EC PUBLIC KEY-----
Private Key -----BEGIN EC PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgwqIsXl9FqsgrzMdx axI6flBwWIev0Z7i+WF4j8BGnrKhRANCAATnS4T5hLGoOAyQUHKGlyBNWpcKoc6H rwuO3XPSOSUN9/9ZXvGj5TqjdEQG0r8LT8sz4R/cUHfBH1pcwY0wtv0Q -----END EC PRIVATE KEY-----
MessageHello World
SignatureB0A9A4F641D3A2E3A65576B7311DCD62ABE78BBF4D3F5FE856598508E24FCB2E6F0277C2F8D57E9E2E108B7C493986E783F5316B8046597019951669B4EE6922

To verify the message, one has to input the public key, the message, and the signature. The cryptographic algorithm can verify if the message was signed by the owner of the public key.

It would take 1000’s of years to break the cryptographic algorithm. This cannot be done faster because of the computational limits we have. Quantum computers in the future might challenge this. But, the Bitcoin system can be upgraded to ensure security.

Satoshi incorporated cryptography in his system to help people authorise bitcoin transactions from their wallets.

PrivacyCredits : xkcd

You register to bitcoin by generating a wallet (public key/private key). The systems collect no information such as email id, full name, etc. Hence you are anonymous unless you announce your public key.

Putting it Together

Satoshi built a shared ledger using cryptography and peer-to-peer networks. When someone sends bitcoins to someone, a message is cryptographically signed and broadcasted to the entire people in the network. They update their ledger, hence everyone in the network knows who owns what.

Blockchain

Every ten minutes transactions are grouped together into a block and linked back to the previous blocks. This process makes a continuous blockchain. Mining is a process by which a block is confirmed, this involves computers in the network to solve a mathematical problem. The first computer/miner who solves the problem gets rewarded in bitcoins made out of thin air.

Once the block is confirmed and added to the network, it is replicated across the entire network. Blockchain was invented in the process of making the autonomous Bitcoin system which confirmed transactions without human intervention. If you are looking for a simplified explanation for blockchain, here’s a story.

A Beginner’s Guide to Blockchain

Introduction to Ethereum & Smart Contracts

Earlier we talked about replacing middleman with autonomous systems. This can be done through programming. Bitcoin’s system was difficult for people to code autonomous systems.

Hence Vitalik Buterin built a new cryptocurrency called Ethereum. It was not only a decentralised cryptocurrency but a network of computers which can host code in the form of smart contracts.

In smart contracts, we can program conditions. If you want to build a decentralised bookstore. You write instructions to help authors add new books, send the download link to an ebook once the customer makes a transaction etc.

Smart contracts not only store conditions but also data. A smart contract of a decentralised bookstore in itself stores the book listing, purchases, etc.

However, we should admit the limitations of the smart contract. Some systems need human support, computers can’t handle it. In the real world implementing smart contracts isn’t easy. Smart contracts once published cannot be altered, silly mistakes can be costly.

Programming Smart Contracts on Ethereum

Credits : xkcd

We will build a simple smart contract that stores and retrieves grades of students. We will be coding the contract in solidity. Here’s the github repo.

pragma solidity ^0.4.18;
contract Grades{
}

The first line tells the compiler which version of solidity we are using. Then we define the contract grades.

We need to store two things in our contract, names of students and their grades. Hence we will create an array to store student names and an associative array to store their grades.

pragma solidity ^0.4.18;
contract Grades{
mapping (bytes32 => string) public grades;bytes32[] public studentList;
}

Now, we will create a way through which we can send the contract, a list of student names. We will do that in the constructor.

pragma solidity ^0.4.18;
contract Grades{
mapping (bytes32 => string) public grades;bytes32[] public studentList;
function Grades(bytes32[] studentNames) public {studentList = studentNames;}
}

In Solidity we would be calling the constructor only once. We will pass student names as an argument, which would be stored in the studentList array we declared earlier.

Now, we need to write a function to assign students their grade. We also need another function to check if the student is valid.

pragma solidity ^0.4.18;
contract Grades{
mapping (bytes32 => string) public grades;bytes32[] public studentList;
function Grades(bytes32[] studentNames) public {studentList = studentNames;}
function giveGradeToStudent(bytes32 student, string grade) public {require(validStudent(student));grades[student] = grade;}
function validStudent(bytes32 student) view public returns (bool) {for(uint i = 0; i < studentList.length; i++) {if (studentList[i] == student) {return true;}}return false;}
}

The “giveGradeToStudent” function takes two arguments, student name, and grade. The require function checks if the “validStudent” function returns true or false. If it returns false, the execution is canceled.

Finally, we need to write a function to fetch the grade of a student. The “getGradeForStudent” function takes student name as an argument, return the respective grade from the associative array.

pragma solidity ^0.4.18;
contract Grades{
mapping (bytes32 => string) public grades;bytes32[] public studentList;
function Grades(bytes32[] studentNames) public {studentList = studentNames;}
function giveGradeToStudent(bytes32 student, string grade) public {require(validStudent(student));grades[student] = grade;}
function validStudent(bytes32 student) view public returns (bool) {for(uint i = 0; i < studentList.length; i++) {if (studentList[i] == student) {return true;}}return false;}
function getGradeForStudent(bytes32 student) view public returns (string) {require(validStudent(student));return grades[student];}
}

For the sake of this tutorial, you can deploy this on a personal blockchain. You can create with Ganache. Here are the commands to install and run ganache.

npm install ganache-cli web3@0.20.3 solcnode_modules/.bin/ganache-cli

Keep ganache running, on a new terminal we will deploy our smart contract. Please save the smart contract as ‘Grades.sol’.

Let’s compile the code.

nodecode = fs.readFileSync('Grades.sol').toString()solc = require('solc')compiledCode = solc.compile(code)

Now let’s deploy the smart contract. Deploying contract on a blockchain will cost you gas, this is to reward people who rent their computational power to you. So we have to specify the amount of gas which you are willing to allocate. You can estimate that using a gas calculator. But, you don’t have to pay now because you are deploying on a personal blockchain and it’s your resources being used. You will have to pay when you deploy contracts on the public Ethereum blockchain.

Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
abiDefinition = JSON.parse(compiledCode.contracts[':Grades'].interface)
GradesContract = web3.eth.contract(abiDefinition)
byteCode = compiledCode.contracts[':Grades'].bytecode
deployedContract = GradesContract.new(['John','James'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})

Now let’s call our functions to give grade ‘A+’ to our student John. Later, we will check if it has been updated using our ‘getGradeForStudent’ function.

deployedContract.giveGradeToStudent('John', 'A+', {from: web3.eth.accounts[0]})
deployedContract.getGradeForStudent.call('John')'A+'

Congrats, you have deployed your smart contract. If you have questions/doubts please comment on this story, I will either comment back or update this story.

The Way Ahead

You can get in-depth understanding about writing Ethereum smart contracts in the following websites.

CryptoZombies

You don’t have to download anything, you can write code on their interactive compiler. You will learn the concepts of solidity programming by building a game. It’s free of cost.

CryptoZombies - Learn to code games on Ethereum. Powered by Loom Network

Zastrin

Zastrin has both free and paid courses. Mahesh Murthy covers all the important aspects. They even teach you to build a decentralised marketplace similar to eBay.

Zastrin | Learn Ethereum programming by doing real-world projects

Claps Please 👏 , Thank You 😊 . Follow us Hackernoon and me (Febin John James) for more stories.

I hope to write more series on building applications on blockchain. You can support me by buying me a coffee.

A Beginner’s Guide to Blockchain Programming was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

Publication date: 
05/30/2018 - 14:01