Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction
Blockchain Types
Ethereum
Geth
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.
Blockchain Types
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
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.
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.
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).
{
"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 --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.
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”
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
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.
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
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:
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.
To get started, paste the following code into the empty index.html file:
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:
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
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.
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: