Sei sulla pagina 1di 23

BLOCK CHAIN GUIDE

Introduction

Blockchain Types

Ethereum

Geth

Create & Deploy your First Smart Contract on Private BlockChain

Create & Deploy Node.js app based on Ethereum BlockChain

Introduction

This guide will only contain must have information regarding key elements in Blockchain &
practical walkthrough as well. Blockchain technology has many flavors which are designed
according to industry needs, here we will focus primarily on two flavors, called ​Ethereum​ &
Hyperledger Fabric​.

Basically a blockchain consists of these elements:

- Genesis block (first block)


- Chain of blocks
- Each block have data, hash, previous block hash (If data changes -> hash will
change)
- Proof of work (also called mining -> consume processing power)
- Consensus of Nodes (in Peer-to-Peer network)

Blockchain Types

It can be of two types depending on purpose of use.


- Public blockchain
- Private blockchain

Public blockchain

A public blockchain network is completely open. Anyone can join and participate in the
network. The network typically has an incentivizing mechanism to encourage more
participants to join the network. ​Bitcoin ​is one of the largest public blockchain networks in
production today while ​Ethereum c​ omes second.

Private blockchain
A private blockchain involves a separate, essentially closed network, of blockchain
participants (also known as nodes). Each participant has their own copy of the blockchain,
essentially a ledger, with a locked down history of all of the transactions that took place in
the network. ​Hyperledger Fabric​ is an example of private blockchain.

Now let’s move to the platform you are going to use first. It is Ethereum, which is used to
develope DApps (Decentralized apps).

Ethereum
Ethereum is an open source decentralized platform featuring smart contract functionality. It
provides a decentralized virtual machine, the Ethereum Virtual Machine (EVM), that can
execute peer-to-peer contracts using a crypto-fuel called Ether.

How it works

- Ethereum blockchain network is simply lots of EVM (Ethereum Virtual Machines) or


“nodes” connected to every other node to create a mesh. An EVM can be visualized
as a simple nodejs (or any other) process for example which behaves like a
full-fledged Ethereum instance.
- 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 get updated and this change 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 keep updated) a copy of the entire Ethereum blockchain through ​CLI tools
which Ethereum provides. Geth is one such tool which is intended for web
development.
Geth

Geth is a command line interface (CLI) tool that communicates with the Ethereum Network
and acts as a link between your computer and the rest of the ethereum nodes (or network
computers) just like you would download a torrent client to become part of a torrent network.

You can download Geth client from ​here​.

With Geth client you can:


- mine Ethers (ether is the cryptocurrency fueling the Ethereum network)
- transfer funds between addresses
- create smart contracts and transact with them
- explore block history and much much more

Once you download and open Geth client, it will try to connect to main Ethereum network
where you need real ​Ethers ​to perform transactions. At this stage, you should connect to
Private BlockChain instead, the process is defined in the next step.

Create & Deploy your First Smart Contract on Private BlockChain

So let’s start by creating your private blockchain where geth client will interact to your local
private blockchain, As mentioned above, every blockchain starts with Genesis block which
has no predecessor (these instructions assume a windows environment).

1) Create a new folder on your desktop called ​Private Chain​.


2) Open command prompt in this folder and create a data directory for your ​chaindata
by typing ​mkdir chaindata​.
3) Next, you need to create and save your ​genesis.json​ block in your ​Private Chain
folder, as the genesis block will be used to initialize your private network and store
data in the data directory ​chaindata​.
4) Open up notepad, copy & paste the code below into a new file called
“​genesis.json​” and save this file in your ​Private Chain​ folder.

{
"coinbase" :
"0x0000000000000000000000000000000000000001",
"difficulty" : "0x20000",
"extraData" : "",
"gasLimit" : "0x2fefd8",
"nonce" : "0x0000000000000042",
"mixhash" :
"0x000000000000000000000000000000000000000000000000000
0000000000000",
"parentHash" :
"0x000000000000000000000000000000000000000000000000000
0000000000000",
"timestamp" : "0x00",
"alloc": {},
"config": {
"chainId": 15,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
}
}

every block consists of these attributes. Here is some explanation of the important
ones,

Gas
Given that Ethereum is a distributed platform, there must be a way to limit the
resources available to a given smart contract, otherwise it could starve the whole
network’s computing power. Gas solves that issue by fixing a cost for every
instruction executed in the EVM.

Difficulty
This value is used to control the Mining Complexity (Block generation time) of a
Blockchain. The higher the difficulty, the statistically more calculations a Miner must
perform to discover a valid block. On your test network, we will keep this value low to
speed up the process during tests, since the generation of a valid Block is required to
execute a transaction on the Blockchain.

Alloc
This is where you can create your wallet and pre-fill it with ​fake ethers.​ It is sort of an
opening balance​ in your wallet so do not necessarily need to mine before you can
run your tests.

Config
The config block defines the settings for your custom chain and has certain attributes
to create a private blockchain

5) Next initialize your private network in the ​chaindata ​by using the ​genesis.json​ file
using the following command.

geth --nodiscover --networkid 1999 --datadir=./chaindata/


init ./genesis.json
6) Start Geth and connect to your own private chain. As you will see the ​geth.ipc
endpoint socket connection will be opened and so will port 30303.

geth --datadir=./chaindata/

Whenever you start Geth an ​ipc​ endpoint will open, which is used to process connections
from Geth to programs like MetaMask, Ethereum Wallet, Mist Browser, or for opening the
Geth Javascript API console, here you will use Mist Browser which is a standalone desktop
application.

Mist Browser
Mist is powerful in that it includes a Geth node that runs in the background upon launch; a
connection to the Ethereum blockchain is made right away. But because you want to
practice developing a smart contract, you are going to run a node on your private network.

You can download Mist browser from ​here

As geth client is already running and ​ipc ​is open to connect Mist browser, So lets open
Mist browser, once you open Mist the ​geth.ipc​ endpoint will open; Mist will then make the
connection to your private network. Make sure Mist is connected i.e. ​Private-Net​ is
displayed in the upper right corner of the Mist launch window.

7) Now you can launch the application, it is connected to your private-chain, here you
can create & deploy smart contracts, but before doing that you need to have your
account. So Let’s create an account by clicking “Add Account” (synonymous with
“wallet”). Choose “Create new account”, and enter a super safe password (even
though this is an account on your private network and will not be connected to the
actual Ethereum network, it is a good habit). Click “OK” to create your wallet.

8) To create ​Smart Contracts​, Mist browser provides ​Remix IDE​ which you can access
from the ​develop ​tab. Smart contracts are written in a language called ​Solidity​, a
java-script type language with the file extension “.sol”

9) Paste the following code in the file named ​HelloWorld.sol


While calling functions on the Ethereum network will require a small amount of gas to
be spent; no gas is required when returning a constant function.

10) Your code should be in Remix and “Auto compile” should be checked by default
under the “Compile” tab. Make your way over to the “Run” tab. Default settings will
have the environment set to JavaScript VM, an account will be selected, gas limit will
be 3000000, and your gas price & value will be 0. Click on “Create” under your “Run”
tab, you will notice amount of ​ether​ will be ticked town slightly after contract has
been created, now It’s time to deploy.

11) Open Mist browser, make sure it is connected to your private chain at bottom left
corner then move to Contracts tab → Deploy New Contract → paste your code from
Remix into the source code box here.

12) To deploy contract, you need some ​ether​ in your wallet, you can mine for ​ether
on your private network by running the ​miner​. You will do this through the Geth
JavaScript console. Open another instance of command prompt and navigate to
private chain folder and execute:

geth attach

Once its attached now you can starting mining, execute:


miner.start();

After it you will see that the console returns “null” and mining has begun! Take a look
at your wallet on Mist, you will see increments of 5 ​ether​ continuously added to
your wallet, You can stop the ​miner​ anytime by executing:
miner.stop();
13) Now you can deploy your contract, Contracts tab → Deploy → After you have
entered your password, make your way back over to the “Wallets” tab. Scroll down to
“Latest Transactions” and you will see the contract you just deployed. You will also
notice that the contract shows 0 of 12 confirmations and is stuck in a perpetual state
of “creating contract”. It’s mean you need to start mining again as you are not working
in peer-to-peer network so others can mine, execute:
miner.start();

Once you start mining again you will see that the number of confirmations will start to
tick up, eventually fully deploying your contract.

14) Now click on the contract name. From here you can do all sorts of things. You can
transfer ​ether​ to the contract, copy the contract address, generate a QR code to be
scanned, get the contracts interface (ABI), and even execute contract functions.

As you can see your “Hello World” contract is displaying your ​getCounter()​function with
the counter state variable of 5. Make your way over to “select function” and select either
“add” or “subtract” function. Once selected, hit “execute”. Do not forget, you are the only one
on this private network so you need to confirm the transaction by running ​miner​ yourself!
Create & Deploy Node.js app based on Ethereum BlockChain
Here I will describe you how you will create a simple node.js app which will have user
interface and interaction with smart contracts using web3.js API further advancing your
smart contract structure to use Events, Modifiers, Struct, Mapping, Inheritance and at the
end about its deployment on lite-server, following are the tools/apis you will use in this
subject.

Remix IDE​ (for creating smart contracts)


Ganache​ (to set-up private blockchain and run tests)
web3.js​ API (provides interface to interact with smart contracts)
Node.js
Lite-server

Let me explain the complete flow:

Setup the project


So after downloading all these tools, lets setup the project by running following commands
on console:

mkdir instructor-eth
cd instructor-eth

Next, run the npm init command to create a package.json file, which will store project
dependencies:
npm init

Then install web3.js which will register its entry in package.json


npm install ethereum/web3.js --save

Run Ganache
Run the Ganache tool to setup private blockchain with 10 test accounts provided and it will
start listening on this port ​http://localhost:8545​ for transactions
Create Smart Contract
Open Remix IDE and create smart contract, here is the sample code:

Deploy Smart Contract


Switch over to the Remix IDE, click on the Run tab, and then change the Environment
dropdown from Javascript VM to Web3 Provider.

Hit "OK" and then specify the Ganache localhost address (by default, it is
http://localhost:8545​)
Hit “Create”, you will need the address of this contract shortly, so leave this window open.

Create User Interface


Now you will create user interface to play with, open up your preferred code editor with the
project folder you created. Here, you will notice a ​node_modules​ folder, which includes
web3 that you installed via npm earlier.

Let's create an ​index.html​ in the project folder.


It will consist of a simple UI, having form with 2 input fields for a name and age.

To get started, paste the following code into the empty ​index.html​ file:

Create CSS file


As you can see, you are referencing a main.css file, so create that file and paste in the
following rulesets real quickly:
Configure Web3.js

I - Setup Default Address


Now It’s time to interact with smart contracts using web3.js, just replace the <script></script>
tags with this piece of code, It will connect to your Ganache client to do transactions with the
default address mentioned below, using first address of provided 10 accounts:
II- Setup Smart Contract Interface
Next, you need to use the ​web3.eth.contract()​ method to initialize (or create) the
contract on an address. It accepts one parameter, which is referred to as the ABI
(Application Binary Interface).
This ABI allows you to call functions and receive data from your smart contract.

If you switch back to the Remix IDE, click on the ​Compile​ tab and click ​Details.​ Scroll down
until you see the Interface - ​ABI section​ and click the ​copy icon​ as shown below:

Then going back to ​index.html​ and paste it where mentioned:

III- Setup Smart Contract Address


After having interface object to interact, the last thing to do is to define the actual contract
address, to do this Goto Remix IDE -> Run tab, create the contract and click on the copy
icon next to the contract that you just created on the right column.
Back to ​index.html​ and update it with the address:
Now, let’s open ​index.html​ to see if its connected to your smart contract or not.
CTRL-SHIFT-I (i) ​will show the console. You will see something similar to the following:

Interacting with Smart Contract


Smart contract has been connected, now let's use jQuery to make function calls based on
your form, update the ​index.html​:
Awesome, save and refresh it then give it a go!, now UI will look like this:

But here after clicking on “Update Instructor” values set successfully but not reflected on the
UI instantly, for which you will need to refresh the page and then see the results

Events & Modifiers


To get rid of manually refreshing the UI, Solidity introduces the concept ​Events​, here you will
add it in your smart contract and also listen for the events in the UI script tags, the other
​ hich is just like, to whom you want to give
thing you are going to add is ​Modifiers w
permission to your contract interface, after adding ​Event & Modifier, y​ our smart contract will
look like this:
After updating the contract, you must need to re-Create the contract from Remix IDE then
update its ABI and address in ​index.html ​file.
Now you are going to make some changes on the UI part. First, no longer need to call
contract.getInstructor()​, so you are going to remove that.

Then, you are going to create a variable to reference your event and adding the ​watch()
method on ​instructorEvent ​with a callback. Beneath the above line of code, paste this:
Also lets add the loader as well:

After doing all this stuff refresh the ​index.html​ file on browser, try to update values, you will
see UI will be refreshed instantly:
Mapping using Struct
Let’s start with the new contract named ​Courses.sol​, first you need to create struct of
Instructor in it which will store its name, first name and last name, just like model class in
java referred from Hashmap, further details can be seen on Solidity site, here is the
complete contract, just copy/paste it at your end:

Inheritance
A common pattern in smart contracts when it concerns inheritance is to define an owner
address and a modifier that gives only the smart contract owner address the ability to access
certain functions.
Above the contract ​Courses ​, you are going to create a new base contract for that
purpose:

​ odifier to the
You can assure that this works by adding the ​onlyOwner​ m
setInstructor()​ function in the derived contract:

Strings to Bytes
In the above contract, you will notice your smart contract consists of two strings ​first name
and ​last name.​ Strings are costworthy on the Ethereum blockchain, and when possible, you
should actually use type of bytes.
Modify the smart contract so that each reference of ​first and last name,​ is no longer a type of
string​, but ​bytes16​ instead as mentioned in above ​setInstructor()​ method

Deploying on Lite-Server
Your smart contract is ready to deploy, before deploying it, you need to install lite-server &
MetaMask chrome plugin, which will allow you to connect to the Ropsten test network to
more accurately simulate the experience of the dApp on the live Ethereum blockchain, So at
this point you will turn off Ganache client to use Ropsten test network instead. Because of
this, you have to install a lite-server in order for MetaMask to inject an instance of the Web3
API. If you do not, MetaMask will not work by just loading your ​index.html​ file into the
browser straight from the hard drive.

Visit your console in the project folder you have been working in, and use ​npm​ to install the
lite-server​ package:

Note:​ If you have problems running this command as I did, make sure you are running your
console as administrator.

Next, open up your code editor and inside of the ​package.json​ file, add this under scripts:

Now, you can run the following command to start the ​lite-server​, which will automatically load
the ​index.html​ file you have been working on, in your browser at a localhost address:

Installing MetaMask
Going forward, you will use MetaMask, which is a chrome extension that brings Ethereum to
your browser. It provides you with a wallet, and the ability to connect to different test
networks, as well as the main Ethereum blockchain.

It provides you with a way to interact with decentralized apps by providing you with a way to
manage multiple accounts on the live network and test network. It also allows you to
sign/approve transactions that are initiated by your Web3 project.

Install the plugin and follow this ​guide​ to getting started with setting up the plugin for the first
time. You want to get to the point at which you are logged in to the Ropsten test network. If
you need to, you can click Buy, which will provide you with free test Ether for use in your
project.

Deploying the Contract to the Ropsten Test Network


Since you have updated the contract, so, let's go back to the ​Remix IDE​ and redeploy this
contract.

Click on Run and change the Environment to Injected Web3.

This will use MetaMask's injected Web3 instance, which will deploy the contract on the
Ropsten test network. After moving back to ​index.html​, again you need to update contract
Address, ABI to reflect the changes and also updating the UI part a little bit:
As you are now using Ropsten test network on ​MetaMask​ instead using your own private-net
on ​Ganache​, therefore need to do some changes mentioned below:
After deployment lets run it on ​lite-server,​ now you see the results:

After pressing submit it will take some time depends upon the Gas price, higher for quick
processing of transaction.
here is the Full Solidity contract which you have deployed, just make sure at your end:

Potrebbero piacerti anche