Bcta Unit-4 Notes
Bcta Unit-4 Notes
Ethereum Block chain Implementation: Introduction, Tuna Fish Tracking Use Case, Ethereum
Ecosystem, Ethereum Development, Ethereum Tool Stack, Ethereum Virtual Machine, Smart
Contract Programming, Integrated Development Environment, Truffle Framework, Ganache,
Unit Testing, Ethereum Accounts, My Ether Wallet, Ethereum Networks/Environments, Infura,
Etherscan, Ethereum Clients, Decentralized Application, Metamask, Tuna Fish Use Case
Implementation, Open Zeppelin Contracts.
1
ii)Blockchain Relevance Evaluation Framework:
We will perform the fitness assessment in this section. Let us go through the questions listed
in the assessment. These are not the final set of criteria but a good set of primary criteria to be
considered.
2
iv)Activity Diagram:
v)Sequence Diagram:
3
Vi)State Diagram
For further understanding, the state diagram is split into multiple layers. The bottom layer of
Figure 5.7 marked as State Layer shows hoy the state of tuna fish changes during its journey.
This gets recorded on blockchain via smart contracts.
The layer above this is represented as Action Layer, which shows the corresponding action that
results in that particular state change.
This is accompanied by another layer known as Inspection Layer, which performs some simple
checks to ensure that an actor is authorized to perform particular action and the current state of tuna
is valid to perform that action.
For example when a regulator wants to carry AuditTuna activity, the following checks occur:
2.isRecorded: This will ensure that the current status is "Recorded", which means that the metadata
related to tuna fish is recorded on blockchain.
The topmost layer of the state diagram represented in Figure 5.7 as Actor Layer, shows different
actors and the sequence in which they perform activities.
4
vii)Solution Architecture:
5
Ethereum Ecosystem
Introduction: -
The heart of Ethereum architecture is the Ethereum Virtual Machine (EVM), which provides
runtime environment for Ethereum blockchain.
The Ethereum ledger itself is implemented using LevelDb that stores all the transactions
initiated from a client application, which is also known as decentralized application (DApp).
To execute smart contracts, Ethereum utilizes something called Ethereum virtual machine
(EVM), which is a kind of isolated sandbox for the smart contract code running on blockchain. This
restriction where smart contract cannot access network, file system or other node assets directly
provides secure and independent environment for logic execution.
On Ethereum, smart contracts are typically coded in a language called Solidity, complied
using an EVM compiler and tested and deployed utilizing provided tool set like the Truffle. The
tool set includes capability of providing a sample node with unlocked accounts, so that developers
can utilize their own machines to develop, deploy and test code before it is ready to be tested on the
real network.
DApps and oracles can interact with the network utilizing a library called web3.js for
cryptocurrency trading or smart contracts.
6
Ethereum Development
Introduction:-
Implementing any blockchain use case on Ethereum platform essentially involves creating
smart contracts and allowing external applications to interact with them.
At a very basic level, creating an Ethereum solution in development environment involves
the following 10 steps.
Once this solution is developed and tested on local environment, it can be deployed to higher
environ- ments.
There are various tools available which assist Ethereum developers with the above-
mentioned steps. The subsequent sections deal with some important tools within the Ethereum
ecosystem.
7
Ethereum Tool Stack
Introduction:-
Ethereum tool stack contains a variety of tools that offer different features – from providing
runtime environment to interaction with DApps.
EVM can be viewed as analogous to JVM, which provides runtime for Java applications.
However, EVM has no access to system and network resources.
Gas in this context means some fraction of ether which needs to be supplied along with other
inputs while executing a transaction or smart contract on Ethereum. This is similar to fuel
(gas/petrol/ diesel) that is required to run motor vehicles.
A vehicle runs as long as fuel is available. In the same manner, code execution on Ethereum
continues till the availability of gas. Hence, EVM is known as a quasi-Turing complete machine
due to the dependency on gas availability for execution.
Also, note that gas offers protection against infinite loop scenarios in smart contract programming.
8
Interaction between Smart Contract, EVM, and DApp:-
When an external application such as DApp wants to interact with the smart contract, it
needs some details about the contract such as the function signatures and properties exposed by it.
This is similar to how a distributed application interacts with an external web service using
its service description language.
9
Layout of a Solidity Source File:-
Example:
pragma solidity 0.5.2
import “../HelperContract.sol”;
contract HelloWorld
{
string msg=“Hellow World”;
function sayHello() public returns (string)
{
return msg;
}
}
10
Contract Instance and Constructor Function: -
Similar to instantiating a class in other object-oriented programming languages, Solidity
contracts can be instantiated using the keyword new.
Example: obj= new HelloWorld();
Solidity contract can have a Constructor Function, which is executed automatically when an
object of the Solidity Contract is created. Constructor Functions are created using constructor
keyword.
Example:
pragma solidity >=0.5.2
import “../HelperContract.sol”;
contract mycontract1
{
string msg;
constructor(string arg)
{
msg=arg;
}
function sayHello() public returns (string)
{
return msg;
}
}
Modifiers:
■ Basically, modifiers are reusable code segments that are used to change the behavior of
functions.
■ When a modifier is applied on a function, they get executed first before the actual function.
In this manner, one can automatically check a condition before executing the function.
■ The syntax to declare modifiers is using the modifier keyword followed by the modifier
name.
Example:
11
Integrated Development Environment
Introduction:-
Integrated Development Environment (IDE) is a set of tools that help the developers in
writing, compiling, executing, and debugging code.
There are many IDEs that support Ethereum smart contract development.
Two of the most widely used IDEs for Ethereum development are:
-Remix
-Visual Studio Code (VS Code)
Remix: -
■ Remix can be accessed online from a browser or from a locally installed copy.
■ Developers can write Solidity code in Remix editor, which offers features such as color
coding for keywords, syntax highlighting, compilation and execution of Solidity Code.
File Explorer: which allows you to create a new Program File or open an existing File.
Plugin Manager: Which allow you to manage packages.
Editor Window: It allows you to type your program code
Solidity Compiler: Smart contract Programs are compiled using this.
Debugger Window: provides facility to see errors or outputs
Contract Deployment: provides facility to perform deployment of the project
■ It is highly customizable and offers various features such as Syntax highlighting, snippets,
intelligence, Code refactoring, Integrated terminal, GitHub integration, etc.
■ The VS Code terminal can be used to download any no. of packages required during smart
contract creation
12
Truffle Framework
Introduction:-
■ The Truffle framework is a suite of tools that assist in setting the development environment,
testing smart contract and also serves as asset pipeline for Ethereum.
■ It aims to perform a lot of heavy lifting and make Ethereum development easier.
Truffle Installation
■ Truffle is comes with a variety of tools suited for different needs.
■ It can be installed using the following command form a node console or VS Code Terminal.
npm install –g truffle
After installing Truffle, developers can start writing Solidity code from scratch or use a
boilerplate template provided by Truffle. These boilerplate codes are provided by a tool
known as Truffle Box.
■ They contain sample Solidity contracts, other helpful modules and libraries, frontend views
and more way up to complete example DApps. In this way, Truffle integrates EVM, smart
contract programming, migration, and frontend DApp technologies.
2 migrations/: This is used to handle smart contract deployments. To keep track of the
changes, a special smart contract named migration will be used.
3. test/: This may contain Solidity and JavaScript tests for smart contracts.
4 truffle-config.js: This is a Truffle configuration file. This file may have a different name,
truffle.js, on Mac/Linux.
13
Ganache
Introduction:-
■ Ganache is a personal blockchain for running Ethereum smart contracts. It comes in two
flavors:
-command line interface (CLI) and
-graphical user interface (GUI
It provides 10 built-n Ethereum accounts with 100 ether each. These can be used for development
and testing purposes with local blockchain.
Upon opening Ganache, it shows a list of accounts created, the mnemonic used to create those
accounts, account balance and related transactions.
Ganache GUI client can be installed from their website.
Unit Testing
Introduction:-
■ Whenever any piece of code is written, it is best practice to write automated unit test cases
also.
■ The Truffle ecosystem supports Chai and Monacha frameworks to write unit test cases for
Solidity smart contracts.
To Execute Unit Test Cases, we have to Run the Command truffle test from VS Code terminal (or
simply test inside truffle develop interactive console)
■ After unit testing on local blockchain network, the smart contract can be migrated to other
networks.
■ When using Ganache to work locally, Ethereum accounts with some Ethers that are needed
to migrate and perform transactions were automatically generated.
Ethereum Accounts
Introduction:-
■ An Ethereum account is a combination of public–private key pair created using Elliptic
Curve Digital Signature Algorithm (ECDSA).
■ The address is obtained by computing keccak-256 hash of the public key and taking
rightmost 20 bytes of that hash.
14
■ There are multiple options to create new Ethereum accounts:
-geth console,
-Mist wallet, or
-MyEtherWallet.
■ The basic difference between an account and a wallet is that an account is a public–private
key pair, whereas a wallet hosts account and also provides some advanced features such as
transaction log, multi-signature options, etc.
■ One of the most commonly used application to create Ethereum wallets and associated
accounts is MyEtherWallet (MEW).
MyEtherWallet (MEW)
Introduction:-
MEW is an easy-to-use, open-source platform that allows generation of Ethereum wallet
address.
No data about the generated wallet address gets stored on their platform and account owners
have complete control of the addresses they own.
15
Ethereum Networks / Environments
Introduction:-
■ Ethereum blockchain network nodes validate and record transactions. They also contain
runtime to execute smart contracts. Currently, Ethereum has the following two types of
networks:
-Mainnet
-Testnet:
Mainnet: -
Mainnet is short for “Main Network” and is the original and functional blockchain where actual
transactions take place.
Any native currency used in this network possesses real economic value. The NetworkID for
Mainnet is “1”.
Testnet: -
Testnet is short for “Test Network” and is mainly used for development and testing purpose. It
is supposedly an exact replica of the original blockchain, with the same technology, software, and
functionalities.
The only difference is that transactions on Testnet are simulated (or “fake”) and any native
currency used does not possess any real value outside.
■ Ethereum blockchain nodes for Testnet and Mainnet can be run on a developer machine as
well.
■ However, there is a cloud service named Infura that provides this functionality and reduces
the overhead for developers to run and maintain these nodes.
Infura
Introduction:-
■ Infura is a hosted Ethereum node cluster that lets the users run their application without
requiring them to set up their own Ethereum node or wallet.
■ First, developers should register with Infura. This allows creation of new project and
generates API endpoint URL and a ProjectID known as Infura key.
■ This key should be kept private and will be used in the Truffle config file for migrations.
■ The Infura endpoint URL will be different for each Ethereum network. Infura cannot sign
transactions on behalf of a user during any interaction with blockchain.
16
Etherscan
Introduction:-
■ Etherscan is a frontend interface that allows users to explore and search Ethereum
blockchain for transactions, addresses, and other activities.
■ It also offers APIs and analytics platform for Ethereum blockchain.
■ Etherscan will be very helpful to visualize transaction details while deploying a smart
contract to Testnet and also during its testing by invoking from a DApp.
Ethereum Clients
Introduction:-
■ An Ethereum client is any node that can run Ethereum blockchain – verify transactions,
execute smart contracts, and mine blocks.
■ Official CLI reference implementations of Ethereum client are as follows:
• Eth: C++ client of the webthree project. It was formerly known as cpp-ethereum.
• Geth: Golang client of the go-ethereum project.
• Pyethapp: Python client of the pyethereum project.
■ Graphical clients available by the Ethereum core developers are as follows:
• Mist: Works on top of eth or geth and aims to be a DApp browser. It currently
implements the ethereum-wallet-dapp.
• Alethzero: This is being deprecated.
■ There are some non-official clients that implement the following yellow paper specification:
parity – Rust client,
ethereumj – Java client,
ethereumjs-vm – EVM in JavaScript,
ethereumH – Haskell client,
ruby-ethereum – Ruby client,
node-blockchain-server – simple JavaScript server.
17
An application can interact with Ethereum client using JSON-RPC as depicted here. However, this
adds a lot of development overhead.
Various libraries are available to do the heavy lifting of this communication with Ethereum
blockchain.
This allows developers to focus more on implementing the functionality rather than the
communication aspects. Table 5.3 lists some of the prominent libraries.
18
Decentralized Application
Introduction:-
■ Decentralized application (DApp) is an application that runs on a peer-to-peer network of
computers.
Metamask
Introduction:-
■ Metamask is a browser extension that lets an application owner or user run DApp without
being part of the Ethereum network as an Ethereum node.
■ Instead, it allows users to connect to an Ethereum node on Infura and run smart contracts on
that node.
■ Metamask can manage Ethereum accounts within its wallet and allows the user to send and
receive Ethers through a DApp of interest.
19
Tuna Fish Use Case Implementation
Introduction: -
We will discuss about the Tuna Fish supply chain use case and how this solution can be
architected. We have chosen a multi-actor supply chain for tracking tuna fish.
A simple QR code scan should reveal the story of tuna fish to its consumers. The data
collected from RFID tracking and IoT devices can be inserted into the blockchain.
This gives details on when and where the fish was caught processing temperatures, result of
quality checks by auditors, etc.
iv)Activity Diagram:
21
v)Sequence Diagram:
Vi)State Diagram
22
For further understanding, the state diagram is split into multiple layers. The bottom layer of
Figure 5.7 marked as State Layer shows hoy the state of tuna fish changes during its journey.
This gets recorded on blockchain via smart contracts.
The layer above this is represented as Action Layer, which shows the corresponding action that
results in that particular state change.
This is accompanied by another layer known as Inspection Layer, which performs some simple
checks to ensure that an actor is authorized to perform particular action and the current state of tuna
is valid to perform that action.
For example when a regulator wants to carry AuditTuna activity, the following checks occur:
1.isRegulator: This will check whether the user is a Regulator.
2.isRecorded: This will ensure that the current status is "Recorded", which means that the
metadata related to tuna fish is recorded on blockchain.
The topmost layer of the state diagram represented in Figure 5.7 as Actor Layer, shows different
actors and the sequence in which they perform activities.
Vii)Class Diagram:-
On the basis of the specifications in Action layer and Inspection layer, a class diagram can be
created (Figure 5.8).
The das diagram in Figure 5.8 gets translated into smart contracts and functions. For
development VS Cole IDE with Solidity extension would be used.
For the sake of modularity and simplicity, the Solidity contracts and functions have been
categorized as follows:
1. Helper: This deals with helper functions related to access control.
For example, isRegulator, isAudited, etc.
2. Supply Chain: This deals with the actions and state changes performed within the
application
3. Admin: This implements some smart contract control and maintenance functions like
ownership transfer, kill, etc.
4. Gateway: This is the contract exposed to DApp and it inherits Supply Chain and Admin
contracts.
23
viii)Output Screen Shots:
During Execution, a simple QR code scan or Fish ID should reveal the story of tuna fish to
its consumers. The data collected from RFID tracking and IoT devices can be inserted into the
blockchain.
This gives details on when and where the fish was caught processing temperatures, result of
quality checks by auditors, etc
24
25
26
Openzeppelin Concepts
Introduction:-
■ OpenZeppelin is a library of secure and tested smart contracts for Ethereum and other
blockchain platforms.
■ Developers can use these standard implementations without the need to reinvent the wheel.
■ Also, these contracts can be extended as required. It can be installed by running the
following command from a node console npm install @openzeppelin/contracts.
■ OpenZeppelin contracts implement some of the common features related to access control,
ERC20 and ERC721 tokens, crowdsales, and utilities.
■ There are some other useful miscellaneous libraries within utilities, namely, Address and
Counter.
■ Address library has a collection of functions related to address data type. For example,
isContract(address), toPayable(address).
■ Counter library functions can be used to increment or decrement a value by 1. This will be
useful to track the number of elements in a mapping data type, issue token IDs, etc.
-----------------********-------------
27