Assignment 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Smart Contracts

Dr. P. Raghu Vamsi


JIIT, Noida.
Objectives
 History of smart contracts
 Exploring various blockchain platforms
 Study the elements and structure of smart contract
 Problems that can be solved by smart contracts
 Syntax and semantics of Solidity
 Designing a smart contract solution
 Using Remix web IDE platform (remix.etherum.org) to
deploy and invoke smart contracts
Introduction
 Smart contract is the computational element of blockchian technology.
 The concept of smart contract exists before blockchain.
 Computer scientist Nick Szabo in his research paper coined Smart
contracts in 1996.
 Smart contract is central idea of Ethereum blockchain.
 Improper design, code, deploy and execution of smart contracts can cause
serious attacks on blockchain.
 Linux Hyperledger blockchain offers smart contracts via Chaincode.
 Chaincode is written in Go language and executed in Docker environment.
 Docker is a lightweight container technology for executing the code.
Smart Contracts: Building Blocks for Digital Markets
– Nick Szabo @ 1996
Blockchain platforms (1)
 Ethereum
 Popularity: High, Actively followed in GitHub
 N/w Type: Public, Smart Contract based
 Cost: Ether for transaction and computational services
 Programming Languages: Python, Go , C++
 GitHub Repo : pyethereum (Python), gpethereum (GoLang), cpp-
ethereum (C++)

 Hyperledger(Sawtooth Lake)
 Popularity: High and actively updated in GitHub
 N/w Type: Both Private and Public
 Cost: Open Source
 Programming Languages: Python (For Sawtooth Lake)
 GitHub Repo: sawtooth-core (Python)
5
Blockchain Platforms (2)
 Multichain
 Popularity: Medium but actively updated in GitHub
 N/w Type: Private, Permissioned
 Pricing: Free, Open Source
 Supported Languages: Python, C#, JavaScript , PHP, Ruby
 GitHub Repo: savior (Python), c# MultichainLib (C#), Multichain-
Node (JavaScript), libphp-multichain (PHP), multichain-client (Ruby)

 HydraChain
 Popularity: Low but actively updated in GitHub
 N/w Type: Private, Permissioned
 Pricing: Open Source
 Supported Languages: Python
 GitHub Repo: hydrachain (Python)
6
Blockchain Platforms (3)
 Open Chain
 Popularity: Medium but actively updated in GitHub
 N/w Type: Private
 Pricing: Open Source
 Supported Languages: Javascript
 GitHub Repo: openchain-js (Javascript)

 IBM Bluemix Blockchain


 Popularity: Medium but actively updated in GitHub
 N/w Type: Private/ Permissioned
 Pricing: Limited free plan with paid upgrade to enterprise plan
 Supported Languages: Go, Javascript
 GitHub Repo: learn-chaincode (Go), ibm-blockchain-js (Javascript)
7
Blockchain Platforms (4)
 Chain
 Popularity: Medium but actively updated in GitHub
 N/w Type: Permissioned
 Pricing: Enterprise Licensing
 Supported Languages: Java, Ruby, Node.JS
 GitHub Repo: sdk-Java (Java), sdk-Ruby (Ruby), sdk-Nodejs
(Node.JS/Javascript)

 IOTA
 Popularity: Low but actively updated in GitHub
 N/w Type: Public, Permissioned
 Pricing: Based on IOTA Token
 Supported Languages: Python , C, Javascript
 GitHub Repo: iota.lib.py (Java), ccurl (C), iota.lib.js (Javascript)
8
What is Smart Contract?
 Facilitates transfer of assets other than value or cryptocurrency.
 Specifies rules for an operation on blockchain.
 Implements policies for transfer of assets in decentralized networks.
 Adds programmability and intelligence to the blockchain.
 Represents business logic layer.
 Includes messages that invokes functions.
Bitcoin transaction vs. Smart contract transaction
Tx(SendValue) Tx(Vote)

S2 S3 S2 S3
Tx(SendValue)
Tx(Validate Voter) Tx(Count)
Tx(SendValue)
S1 S1
S4 S4
Tx(Declare winner)
Tx(SendValue)
S5 S5

Bitcoin transaction Smart contract transaction : Voting example


What are the problems solved by Smart
contracts
 Generally currency transfer is done to avail a service, utility, or
product.
 There may be other things involved in executing the transactions.
 The other things may be rules, policies, laws, regulations, governing
contexts, etc.
 Smart contracts allow these real world constraints to include in the
blockchain.
 In this way, smart contracts allow wide variety of decentralized
applications of arbitrary complexity to be implemented in
blockchain.
 This feature allows to develop a wide variety of decentralized
applications ranging from supply chain to disaster recovery.
Solidity – A High-level language for coding
smart contracts
 It is an object-oriented, contract-oriented, statically typed,
Turing complete and a high level language for coding smart
contracts.
 It is designed to target EVM.
 Style/Syntax is similar to Java Script.
 Visit https://github.com/ethereum/solidity/releases to observe
the new functionality available in Solidity.
 Solidity programs can be written and executed using web
browser based IDE called REMIX.
 Visit https://remix.ethereum.org for IDE.
 REMIX support only compilation and testing,.
 To include smart contract in blockchain one has to use
blockchain gateway service such as INFURA (https://infura.io/).
Solidity basics
StorageState.sol
// COMMENT Class or Contract named StorageState
pragma solidity ^0.4.16;
contract StorageState{
// COMMENT SINGLE LINE - unsigned integer variable named statedData
uint stateData;
/* COMMENT MULTI LINE
The setter and the getter for variable named stateData
*/
function set(uint x) {
stateData = x;
}
function get() constant returns (uint) {
return stateData;
}
}
Solidity Control and Flow statements (1)
Solidity Control and Flow statements (2)
Data Types (1)
Data Types (2)
Data Types (3)
Data Types (4)
Data Types (5)
Visibility Specifiers
Block and
Transaction
Properties
Order of
operations
Functions and parameters
Cryptographic
Functions
Contract related functions

Functions on Addresses
Solidity features
 Inheritance
contract StandardPolicies { ….}
contract StatePolicies is StandardPolicies {
// other policies …
}
 Function definition
function nameOfFunction(parameters) visibilityModifiers
accessModifiers returns (returnParameters) { … }
 Any number of parameters can be returned unlike other programming
languages
e.g., var(name,age) = getNameAge();
Solidity Structure
 Solidity: Java Script + Java + C++, written to target EVM
 Remix IDE is used to code and test the solidity.
 Remix IDE provides three test environments:
 Java Script VM
 Injected Web 3 (e.g., Meta Mask)
 Web 3 Provider (e.g., Ethereum Node)
 Detailed structure of Solidity includes
 Data or state variables
 List of functions
 Constructor – Default or user specified
 Fall back functions
 View functions
 Pure functions (e.g., Math functions)
 Public functions – accessible to transactions
 Private functions – accessible to current contract
 Internal functions – accessible to inside/inherited contract
 External functions – accessible from only outside of the contract
 User defined types in struct and enums
 Modifiers
 Events
Processing Smart Contracts
Smart Smart contract address is computed
by hashing EOA number with nonce
Contract

Remix
Compile
Process

Contract Web GAS Function Instance


ABI deploy
byte code estimate hashes byte code
script
Application Binary Used to instantiate It has two items Provides GAS First four bytes of The byte code
Interface is the the contract on 1) JSON script to estimate to deploy the function of smart
interface schema EVM (Like web application and invoke the signature to contract
for a transaction to executing the to invoke smart functions facilitate function instance.
invoke functions on constructor to contract. invocation by a
smart contract invoke the object) 2) Script for transaction.
instance byte code. grammatically
deploying smart
contract from
web application.
Deploying Smart Contracts
 Smart contracts can be deployed using Remix IDE, Another smart contract,
Command Line Interface, Another High level applications, and a web
application.
 Smart contract requires an address, it is generated by hashing the senders
address with a nonce.
 If a target's address is zero or null, it is meant for creating a new smart contract
using its payload feed.
 The payload of a transaction contains the bytecode for the smart contract.
 This code is executed as a part of the transaction execution to instantiate the
bytecode for the actual smart contract.
 The execution of a smart contract creation transaction results in the
deployment of this smart contract code on the EVM.
 It is permanently stored in the EVM for future invocation.
 This transaction goes through all the regular verification and validation specified
in the etherium blockchain protocol.
 Block creation, transaction confirmation by the full nodes deploys a the same
contract on all the nodes.
Smart contracts design steps
1. Understand the problem statement
2. Analyze the problem statement
3. Use class diagram to represent design
4. Define the visibility for state variables and functions
5. Define access modifiers for the functions
6. Define validations for input variables of the functions
7. Define conditions that must hold true on completion of
critical operations with in functions.
8. Express conditions that were discovered from step 4 to
step 7
Designing Smart Contract: A Case Study
Ballot Smart Contract

An organization invites proposals for a project, a


chairperson organizes this process. The number of
proposals is specified at the time of creation of the smart
contract. The chairperson registers all the voters. Voters
including the chairperson vote on the proposal. To make
things interesting, we've given a weight of two for the
chairperson's vote and a rate of one for the regular voter.
The winning proposal is determined and announced to
the world. Let exclude the delegation of voting function
that is present in the current valid smart contract.
Ballot Case Study (1)
 Chairperson: 2 Votes, Others: 1 Vote
 State variable and functions Ballot
-struct Voter;
-struct Proposal;
-Proposal[] proposals;
-mapping(address => Voter) votes;
-address chairperson;
+Ballot()
+register();
+vote()
+winningProposal()
 Ballot() – Constructor
 Register() – only chairperson can register the voter
 Vote() – any registered person including chairperson can vote for proposal
 WiningProposal() – only chairperson can reveal the winning proposal
 Voter and Proposal are declared as structure for possible future
extensions.
Ballot Case Study (2)
 Typical voting process includes voter registration with in a deadline, voting
period, etc.
 Example: In India, voters need to register themselves via ECI website at
least 6 months before the polling date.Voting takes place on a single day.
 It means registration needs to be completed before voting.
 BallotBasic.sol does not have the timing for registration and voting.
 Add distinct stages of polling via enumerated data type – initial, register,
vote, and done.
 When smart contract is initiated the stage should be Initial.
 Fix a time for registration.
 Fix a time for voting after registration.
 Fix a time for announcing winning decision after voting.
 Use now to do all the aforementioned steps.
 Let us examine BallotV2.sol
Ballot Case study (3)
 Modifier and required clauses using the Ballot smart contract functions:
 Modifiers are used for input validations such as who and how functions are
used, how long the function can be used etc.
 Modifiers can change the behaviour of a function.
 Modifiers can be considers as a gate keeper for the function.
 Modifiers keep the condition with require and can revert the transactions if
the condition is not met.
 If condition fails, the transaction is rejected and there will be no recording
on the blockchain.
 Modifications to Ballot case study
 Define modifier for clause “onlyBy(chairperson)”
 Adding the special notation (_;) to the modifier definition that includes the
function.
 Using the modifier clause in the function header.

 Let us examine BallotV3.sol


Modifiers
Rules, Laws, policies, Function
Governance coded as
modifiers
Function Header

Input arguments validation


using “require” (Tx
revertible)
Function guard conditions
Modifiers (Tx revertible) Function code
referenced in the function
header Assertion (Tx revertible)

Execution order
Modifiers (Example)

At least 5 sellers have


Function buy() payable
registered
atleastFiveSellers .. returns
(..)

Enough value to buy item?

Function code: collect value


modifier atleastFiveSellers { and transfer digital item
requires(noOfSellers >= 5);
_; Assertion (itemTransfered)
}

Execution order
Some questions needs to be addressed
 Can we reject the transaction if it doesn’t conform to the rules?
 Use revert() declaration
 Apply the concepts of function modifier, revert and assert
 Can we separate validation from the code that is executed?
 Can we specify the problem specific rules and conditions so that
they can be independently specified and audited?
 How to interact with the client applications?
 Use events to interact with client applications. It is by defining and
pushing an event to the subscribers listener.
 Syntax: event nameOfEvent(parameters);
 Example: event votingCompleted();
 Events are pushed from the smart contract and user applications listen
them using listener code to 1) track transactions, 2) receive results, 3)
initiate pull request to receive information from smart contract.
Smart contracts – Best practices (1)
 Make sure that your application requirements require
blockchain features
 Blockchain suitable for decentralized problems
 Applications involve peer-to-peer transactions
 Applications that work beyond boundaries of trust among
unknown peers.
 Applications that require verification, validation and recording
of transactions over global time with immutable ledger.
 Applications involve autonomous operations guided by rules
and policies.
Smart contracts – Best practices (2)
 Make sure you need a smart contract on blockchain for your
application.
 Smart contracts are visible to all participants on the chain and can be
executed on all full nodes in the network.
 Smart contracts are needed when collective agreement of rules and
policies are required.
 Decisions and problems must be recorded.
 Smart contract is not for single node computation.
 Keep the smart contract code simple, coherent and auditable.
 Should not include redundant data and non useful functions.
 Make smart contract functions auditable by using custom function
modifiers instead of inline if-else code.
 Keep only necessary data in the smart contract.
 Separate on-chain and off-chain data.
Smart contracts – Best practices (3)
 Use appropriate data types.
 Example: In Ballot smart contract, use number for proposal instead
of name (string) for it. It is because string is dynamic.
 Top level applications may map id with names.
 EVM has a 256 bit processor.
 Make sure using of integer arithmetic for computational needs.
 Uint8 to 256-bit data type
 Understand public visibility modifier for the data
 Irrespective of a variable visibility, each variable can be visible
to all participants on the chain.
 If a variable is explicitly declared as public then Solidity
compiler generates a getter method for it.
 Public data internally accessed via variable name, but externally via
getter function generated by Solidity compiler.
Smart contracts – Best Practices (4)
Public visibility example
contract MyC {
uint public data = 33;
}
contract CallerMyC {
MyC myc = new MyC();
function fun() {
uint local = myc.data();
}
}
 Maintain a standard order for different function types with in the smart
contracts. The order may be 1) constructor, 2) fallback functions, 3) external, 4)
public, 5) internal, 6) private, and place 7) constant functions at last.
 Functions can have any number of modifiers. Visibility modifier should come
before custom defined modifiers.
 Multiple modifier functions should be written by a white space separation.
 Modifier functions to be called based on dependency.
Smart contracts – Best practices (5)
 Use Solidity defined payable modifier when sending a value.
 function deposit() payable {}
 function register (address sender) payable {}
 Pay attention to the order of functions in the code.
 Use modifier declarations for implementing rules.
 Use function access modifiers for
 Implementing rules, policies and regulations
 Implementing common rules for all who may access the functions
 Declaratively validating application specific functions
 Providing auditable elements to allow verification of the correctness of a smart
contract.
 Use events for notification
 Events can carry at most 3 index parameters.
 Beware of now time variable.
 Use secure hashing for protecting data.
(keccak256(), sha256(),ripemd256())
 Beware of static warning in Remix IDE.

You might also like