paint-brush
Here’s how I built a private blockchain network, and you can tooby@chakrvyuh
132,253 reads
132,253 reads

Here’s how I built a private blockchain network, and you can too

by Abhishek ChakravartyMarch 11th, 2017
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

This is PART-4 of <strong>The Product Manager’s guide to the Blockchain</strong> series! If you somehow landed on my publication for the first time, Welcome! I recommend you start from <a href="https://medium.com/the-time-of-the-product/the-product-managers-guide-to-the-blockchain-part-1-fb95dfb7af31" target="_blank">part 1</a>, and then read <a href="https://medium.com/the-time-of-the-product/why-ethereum-when-we-already-have-bitcoins-blockchain-3359eb7e087e" target="_blank">part 2</a> and <a href="https://hackernoon.com/product-managers-guide-to-blockchain-part-3-fb0cffbff7f8" target="_blank">part3 </a>before reading this post. However If you are the explorer type, read on!

Company Mentioned

Mention Thumbnail

Coins Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Here’s how I built a private blockchain network, and you can too
Abhishek Chakravarty HackerNoon profile picture

Nothing helps understand blockchains better than building one yourself

This is PART-4 of The Product Manager’s guide to the Blockchain series! If you somehow landed on my publication for the first time, Welcome! I recommend you start from part 1, and then read part 2 and part3 before reading this post. However If you are the explorer type, read on!

(Update: Here’s the latest — part 5 of the blockchain series )

In Part 3 of this series, we looked at the mechanics of Ethereum and also talked about the concept of Ethereum Accounts, Smart Contracts and Gas — the fuel that helps all these pieces to work together. Its been a lot of reading so far, but while you can read all the blockchain content available on the internet, nothing helps understand blockchains better than building one yourself. So that’s what I did. You can simply follow this post and build a little prototype to see how everything we’ve talked about so far comes together.

Alright, lets get started

Here is what we will accomplish in this post,

We will,

But, before we start…..quick recap

We’ve seen this before, but basically the Ethereum blockchain network is simply lots of EVM (Ethereum Virtual Machines) or “nodes” connected to every other node to create a mesh. Each node runs a copy of the entire blockchain and competes to mine the next block or validate a transaction. Whenever a new block is added, the blockchain updates and is propagated to the entire network, such that each node is in sync.

To become a node in the Ethereum network, your computer will have to download and update a copy of the entire Ethereum blockchain. To achieve this Ethereum provides tools that you can download, connect to the Ethereum network with and then interact with it. These are:

Geth “……if you have experience with web development and are interested in building frontends for dapps, you should experiment with Geth.”

Eth — “…If you want added security by running two different implementations in parallel or are serious about GPU mining, then the C++ “Eth” client is for you.

Pyethapp — “ …If you are a Python developer that wants to build decentralized apps or are interested in Ethereum for research or an academic purpose, this is a great client

Each of these tools will eventually provide us access to a console — a JavaScript environment that contains all of the main features that we’d need later so I am guessing no matter what tool you choose to set up your blockchain, we should eventually converge on the console.

I simply chose Geth since I have some understanding of web development. The rest of this post assumes that we are using Geth to interact with the Ethereum Network.

Ethereum’s Go implementation is called Geth

Geth is a command line interface (CLI) tool that communicates with the Ethereum Network and acts as the a link between your computer, its hardware and the rest of the ethereum nodes or network computers.

If a block is mined by another node, your Geth program will pick it up and then pass on the new information onto your GPU or CPU to update the blockchain. With Geth, you can

  • mine ether (ether is the cryptocurrency fueling the Ethereum network)
  • transfer funds between addresses
  • create smart contracts and send transactions to them
  • explore block history and much much more

Ok, Let’s install Geth

Homebrew, The missing package manager for macOS

Here are the instructions for how to install Geth on a mac. I simply used Homebrew which makes installing Geth (really anything) really easy. If you have a mac but don’t have Homebrew , you should install it first.

Windows & Linux users:

Here are the latest stable binaries for windows and Linux for you to download. And here is what to do after you’ve downloaded it.

Once you have installed Geth_,_ you can technically connect to the Main or public Ethereum blockchain Network and run a full ethereum node. But we don’t want to do that just yet because If you are reading this article, chances are you have no ether (Ethereum’s cryptocurrency) — and without ether you cannot really do much on the Main blockchain.

What if you have no ether to start with?

I didn’t have any either, but Ethereum lets you create your own ‘private’ blockchain network, sort of a dev/staging version of the main network. This private network is exactly like the main Ethereum chain from a functionality standpoint, except any transactions and smart contracts deployed on this network are only accessible to nodes that are connected t this private network. So that’s what we’ll do — we will create a private blockchain.

Creating a private Ethereum Blockchain

Geth enables you to set up a “private” or “testnet” Ethereum blockchain. It is the best way to learn blockchain concepts that you hear and read about on the internet. You can build smart contracts, make transactions an even distributed apps — without needing real ether_._ You can actually CREATE your own fake ether, preassign ether to your account and then use it to make transactions , transfers or deploy smart contracts.

Blockchain & The Genesis Block

blockchain

As you probably know by now, a blockchain is nothing but a digital ledger in which transactions are recorded chronologically and publicly. These transactions are recorded in blocks, and nodes in a distributed network compete to find the next valid block. Once a valid block is found, it is added to the blockchain, and this information relayed to the network. Every node then updates their blockchain to the latest copy.

Every blockchain starts with a Genesis Block, the very first block in the chain, block ZERO— the only block that does not have a predecessor.

To create our private blockchain then, we will create a genesis block. To do this, we will create a custom Genesis file, and ask Geth to use that genesis file to create our own genesis block , which in turn will be the start of our custom private blockchain.

Here’s what a Genesis file looks like:










{"config": {"chainId": 987,"homesteadBlock": 0,"eip155Block": 0,"eip158Block": 0},"difficulty": "0x400","gasLimit": "0x8000000", //set this really high for testing"alloc": {}


}}

and this is what the attributes mean…

config: the config block defines the settings for our custom chain and has certain attributes to create a private blockchain

- chainId: identifies our blockchain, the main Ethereum chain has its own ID, but we will set it to a unique value for our private chain.

- homesteadBlock: Homestead is the second major version of the Ethereum platform and is the first production release of Ethereum. It includes several protocol changes. Since we are already on homestead version, this attribute is 0.

- eip155Block/eip158Block: Homestead version was released with a few backward-incompatible protocol changes, and therefore requires a hard fork. These protocol changes/improvements proposed through a process Ethereum Improvement Proposals (EIPs). Our chain however won’t be hard-forking for these changes, so leave as 0

- **difficulty:**This value is used to control the Block generation time of a Blockchain. The higher the difficulty, the statistically more calculations a Miner must perform to discover a valid block.On our test network, we will keep this value low to avoid waiting during tests, since the generation of a valid Block is required to execute a transaction on the Blockchain.

- **gasLimit: ** this value specifies current chain-wide limit of 'Gas' expenditure per block. Gas is Ethereum's fuel that is spent during transactions. We will mark this value high enough in our case to avoid being limited during tests.

- alloc: This is where you can create your wallet and pre fill it with fake ether. For this post however, we will mine our ether locally quickly so we don’t use this option.

At this point, lets go ahead and create our CustomGenesis.jsonfile . I simply used a text editor and stored it in a folder on my computer.

Next open terminal and assuming you have installed Geth, simply run this snippet

geth — identity “yourIdentity” — init /path_to_folder/CustomGenesis.json — datadir /path_to_your_data_directory/ACPrivateChain

This snippet instructs Geth to use the CustomGenesis.json file you created as to be the first block of your custom blockchain. Then, we also specify a data directory where our private chain data will be stored. Geth will create the data directory for you. Just choose a location that is separate from the public Ethereum chain folder, if you have one

Once you run this snippet on your terminal window, you should see Geth connect to the genesis file and provide confirmation of the same

my terminal window showing successful genesis state written

Create a private network that will share this Blockchain

Ok, so at this point we have set up the very beginning of private chain. Next, we will start our private network so we can mine new blocks that will be added to our private chain.

To do this, run this command on your terminal

geth --datadir /path_to_your_data_directory/ACPrivateChain --networkid 9876

This snippet tells geth to start our private network and use the directory we just specified to access our private blockchain details .

Note that we also specified a parameter called networkid. This marks the identity of your Ethereum network. We’ve used 9876 in this example, but You SHOULD replace it with a random number of your choice to create your own network and to prevent others from inadvertently connecting to your network

The Main Ethereum network has a networkid=1 . Here is a list of network ids and the corresponding networks.







0: Olympic, Ethereum public pre-release testnet1: Frontier, Homestead, Metropolis, the Ethereum public main network1: Classic, the (un)forked public Ethereum Classic main network, chain ID _61 _1: Expanse, an alternative Ethereum implementation, chain ID _2 _2: Morden, the public Ethereum testnet, now Ethereum Classic testnet3: Ropsten, the public cross-client Ethereum testnet4: Rinkeby, the public Geth Ethereum testnet42: Kovan, the public Parity Ethereum testnet7762959: Musicoin, the music blockchain

Anyway, Once you run the command on your terminal — your private network will go live. Here’s what my terminal shows after running the snippet.

Another important thing. Every time you want to access your private chain, you will have to run these two snippets as is and in that order since Geth DOES NOT remember the parameters of your private blockchain network. Therefore, I suggest you save the set-up steps below, so you can access it later.


#1geth — identity “yourIdentity” — init /path_to_folder/CustomGenesis.jsondatadir /path_to_your_data_directory/YOUR_FOLDER


#2geth --datadir /path_to_your_data_directory/ACPrivateChain --networkid YOUR_NETWORK_ID

If you’ve followed along then at this point, You have a private blockchain, and a private network up and running! Now, we can start interacting with our private chain and our private network through accounts.

Create an Externally Owned Account (EOA)

We will now create an account to manipulate our blockchain network. If you have been following this series, we talked about accounts in our last post.

Types of accounts in Ethereum

Once you have your first geth instance open, open another console/terminal and type the following:

geth attach /path_to_your_data_directory/YOUR_FOLDER/geth.ipc

This will connect your 2nd console to the Geth instance running on your first terminal window (make sure its actually running). You should get a Javascript console like so

Once you have the javascript console, you are all set to create an account .

personal.newAccount()

You will be asked to setup a password following which, a new account will be generated. Simple!

Now, save this account # as since you will need it very often. Also, remember you passphrase because you’ll need it to access your account. But you knew that already.

Next, check to see how much ether this account has using the following line of code

eth.getBalance("ENTER_YOUR_ACCOUNT_NUMBER_HERE")

here’s what I got

Your balance should be 0. Rightly so, since you wouldn’t have any ether when you first create an account.

There are 2 ways to get ether into your account, either somebody sends you some , or you mine transaction blocks and get rewarded with ether in turn.

Since you are all alone in your private network at this point, your only option right now is to mine some blocks and get rewarded.

Mine some ether into our account

Mining in the real or Main Ethereum blockchain is pretty difficult and would need specialized hardware such as dedicated GPUs. However, mining for blocks in a private chain is easy to do, since we specified the difficulty level to be very low in our genesis file, remember? We can simply start mining using the following code

miner.start()

At this point, if you look at the other console that is running the Geth instance, you will see blocks being mined successfully by your miner. Give it 10–15 seconds and check your balance again.

Woohoo! Lots of ether show up in your new account. (Remember this is fake ether, you cannot use this ether to make transactions on the Main Ethereum network) but you can use this to test our several functions of the blockchain including transfers, deploying contracts etc.

Finally, stop the miner using the miner.stop() script.

Congratulations!

You just built your first private ethereum blockchain and mined some ether! Lots of details, but I am hoping some of this made sense, and gave you a little more clarity on how blockchains work.

In the next post, we will add another node to our private blockchain, write and deploy smart contracts and demonstrate how to call contract.

Want to know when a new post is up? Just Follow The Whiteboard :)

Also, If you found the post helpful, please recommend it to others by clapping for this post ! If you have insights or comments, I would love to hear from you . You can also reach out to me directly on twitter.

https://upscri.be/hackernoon/