How to Build Your Own Blockchain

All the code samples here are outdated. Please use this article as a reference guide only. According to a survey, conducted by Juniper Research, 6 of 10 large business owners are either thinking about or developing their own blockchain technologies, for example in healthcare...

#1. Using a blockchain vs. Using a database
#2. Let’s make a Blockchain
#3. Install Go Ethereum
#4. Create your blockchain
#5. Send some ETH to your newly created account
#6. Start mining
#7. Install the Solidity Compiler
#8. Difference between mortal and greeter contracts
#9. Unlock your account
#10. Create a smart contract
#11. Prepare your smart contract for deployment
#12. Test your smart contract

All the code samples here are outdated. Please use this article as a reference guide only.

According to a survey, conducted by Juniper Research, 6 of 10 large business owners are either thinking about or developing their own blockchain technologies, for example in healthcare. Among those companies, 66% really believe blockchain technology to be integrated into their companies by the begin of 2019.

As for the reasons for choosing blockchain, it’s widely believed that many companies are fond of using brand new technologies for bigger profits. In fact, businesses often rely on new solutions in order to completely redesign legacy processes to fit the new digital world.

The point is systemic changes are more efficient than technological ones. So, using the advantage of a blockchain offers a reliable way for your company to integrate into the age of the twenty-first century!

Using a blockchain vs. Using a database

Now, that’s a good question, isn’t it? Actually, there are at least five firm reasons to decentralize things instead of keeping them in a centralized server aka database. Here they are:
Immutability. When you have all your crucial data deployed on a blockchain, it’s impossible to tamper with your records. As for keeping data in a database, anyone can easily change files before sending them to another person.
Redundancy. There’s no need for you to go mad with losing important files. Really, you can get the same set of data from anywhere in your network. So, no more data loss and file corruption for you, blockchain users!
Security. A centralized database makes a good target for hackers. The blockchain is a whole different “animal”. The more users/nods you have on a network, the more exact copies of priceless data you get. Such an approach allows preventing vital information from severe corruption or even permanent loss.
Cost-efficiency. Companies using decentralized networks of nodes to maintain their ledgers can save money on security, hosting and maintenance. Every node in a network is a sort of self-contained system keeping files for years to come.
Transparency. Using a blockchain, you get the higher level of trust and the ability to do business in an open manner.

Let’s make a Blockchain

Before we begin, you should also know that there are two types of blockchain: private blockchain and public blockchain.

So, how about to give it a try and create your very own blockchain? All you need is to follow the guide below.

Please note that we used Ubuntu, but the guide will be OK for people using other Linux distributions, MacOS (with Homebrew manager) and Windows 10 (using terminals and the latest stable binary).

Install Go Ethereum

Your first step is to install Go Ethereum (geth). Go Ethereum is one of the original implementations (along with C++ and Python) of the Ethereum protocol written in Go.
To install geth, Mac OS X users should use Homebrew, an additional package manager for MacOS. Homebrew installs the stuff you need but can’t find in Apple store. Once you have the manager installed, run these commands:

brew tap ethereum/ethereum
brew install ethereum

To install Go Ethereum on Ubuntu, you only need to use apt-get. Run the following commands:

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:thereum/ethereum
sudo apt-get update
sudo apt-get install ethereum

As for Windows users, they don’t need to think too hard. All you need is to download the corresponding geth installation and run it.
Now you can create a new directory and write a json file to make a genesis block:

cd
mkdir eth-new
cd eth-new
nano genesis.json

To create the genesis block, paste the following code into the newly created JSON file:

{
"nonce": "0x0000000000000042",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"difficulty": "0x4000",
"alloc": {},
"coinbase": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "Custem Ethereum Genesis Block",
"gasLimit": "0xffffffff"
}

Press Ctrl+X, Y, Enter to save your new genesis block.

Create your blockchain

Run the following commands to create a blockchain (the maxpeers option is set to 0 in order to disable the network):

mkdir eth-data
geth --datadir eth-new genesis.json init eth-new/genesis.json --networkid 123 --nodiscover --maxpeers 0 console

To make a new account and password type the following in the geth console (don’t forget to specify login data in brackets). Oh, there’s one more thing: you’ll have to specify your new password twice:

personal.newAccount()

The output after this should be a string of letters and numbers, i.e. an address of your account. To stay on the safe side, save the address specified somewhere else and exit (type “exit” and press Enter).

Send some ETH to your newly created account

Open the genesis block file once again and type the following:

nano genesis.json

Copy previously saved account address and paste it into the “alloc” brackets. Next, go ahead and give yourself an ETH balance. The amount shown next to “balance” below is equal to 10 ETH. Once you are done with making changes, save the file with Ctrl+X, Y, Enter.

Delete an old blockchain and create a fresh one. Use these commands to get rid of the old blockchain data and restart geth:

cd eth-data
rm -rf chaindata dapp history nodekey
cd ..
geth --datadir eth-new genesis.json --networkid 123 --nodiscover --maxpeers 0 console

In the geth console, type the following:

> primary = eth.accounts[0]
> web3.fromWei(eth.getBalance(primary), "ether")

As a result, you get a new address and balance of 10 ETH.

Start mining

To get yourself a full-fledged blockchain, you need to develop miners. To cope with this challenges, close the geth console (type “exit” + hit Enter).
Run the following command to start mining:

geth --mine --datadir eth-data --networkid 123 --nodiscover --> maxpeers 0 console 2>>geth.log

Congrats! You’ve just created your very own miner capable to collect ETH fees. If you want to check your cryptocurrency balance, run the following command:

> primary = eth.accounts[0]
> balance = web3.fromWei(eth.getBalance(primary), "ether")

Install the Solidity Compiler

Just like other cryptocurrencies, the Ethereum uses the advantage of smart contracts written in Solidity. So, to use that contract-oriented programming language, you need to install the Solidity Compiler. To do this, type the following lines in a new terminal:

bash
sudo add-apt-repository ppa:ethereum/ethereum

After getting a message: “Press ENTER to continue” press Enter and type the following:

sudo apt-get update
sudo apt-get install solc -y
which solc

This will provide a path to Solc that you’ll need to remember. Now, return to the terminal window showing the geth console. Run the following commands, changing to the path value you got:

admin.setSolc("")
eth.getCompilers()

If you get [“Solidity”] as a response to the second command, it means, you got yourself the Solidity Compiler and can write in Solidity.

Difference between mortal and greeter contracts

Below is the code for a simple contract with added comments. It contains two types of contracts:
a mortal contract that can be killed by the person who wrote it and it needs to be declared as such, as contracts are immortal by default;
a greeter contract that is nothing but a “Hello World!” greeting.

contract mortal {
/* Define var owner of the type address*/
address owner;
/* this function sets the owner of the contract */
function mortal() { owner = msg.sender; }
/* Function to recover fees */
function kill() { if (msg.sender == owner) selfdestruct(owner); }
}
contract greeter is mortal {
/* define variable greeting type*/
string greeting;
/* this runs when the contract is executed */
function greeter(string _greeting) public {
greeting = _greeting;
}
/* main*/
function greet() constant returns (string) {
return greeting;
}
}

Unlock your account

When you start a new contract, it takes ETH fees. So you need to unlock your account first. To do this, type the following:

primary = eth.accounts[0]
personal.unlockAccount(primary)

Don’t forget the password! If you get “true” output, that means you’ve successfully unlocked your account.

Create a smart contract

In the geth console, copy and paste the whole source code of your contract from the previous version in a line without the comments:

var greeterSource = 'contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) suicide(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } }'

Get “undefined” as a response.
Type the following in the geth console:

> var greeterCompiled = web3.eth.compile.solidity(greeterSource)

The response is the same: “undefined.”

Prepare your smart contract for deployment

If you read this, then you got your mortal contract and greeter contract. Now you need to work with your smart-contract, come up with a greeting message and instantiate your account objects. Get ready to spend some more ETH for that.

In your geth console, run these commands:

var _greeting = "Hello World!"
var greeterContract = web3.eth.contract(greeterCompiled.greeter.info.abiDefinition);
var greeter = greeterContract.new(_greeting, {from: eth.accounts[0], data: greeterCompiled.greeter.code, gas: 1000000}, function(e, contract){
if(!e) {
if(!contract.address) {
console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");
} else {
console.log("Contract mined! Address: " + contract.address);
console.log(contract);
}
}
})

A “Contract transaction send” message appears. A few seconds later you’ll get a message saying: “Contract mined!”

Test your smart contract

By running the following commands you can return a long address and then your greeting message.

eth.getCode(greeter.address)
greeter.greet()

That’s it! Now you have your very own blockchain!

Do you want to integrate a blockchain technology? Tell us about your project and get a free quote.
Rate it (2 ratings, average 5 out of 5)
Thank you!
1
(Poor)
2
(Bad)
3
(Average)
4
(Good)
5
(Awesome)


Thank you!