0% found this document useful (0 votes)
17 views106 pages

Week 4

Uploaded by

mzmindykkyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views106 pages

Week 4

Uploaded by

mzmindykkyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 106

CSIT6000Q-Blockchain &

Smart Contracts
Week – 4
Pritom Rajkhowa
Consensus Model

Consen Model
sus

This is a procedure we are going to use to make sure that everyone


agrees on something
Consensus Model Cryptocurrency

Consen
sus

This is a procedure we are going to use to make sure that everyone


agrees on something
Consensus Model Cryptocurrency
Transactions

Consen
sus

This is a procedure we are going to use to make sure that everyone


agrees on something
Consensus Model Cryptocurrency

Proof of Work Proof of Stake


Solve Cryptographic Puzzle

Valid

Attack Free coin

Work

51% Computing
More work you put work in, More chances power of network
to win reword.
You need billions or trillions of dollars
Miner 1

Finish Line

Miner 2

Miner 3

Proof of work
Miner 1

Finish Line

Miner 2

Miner 3

Proof of work
Miner 1

Finish Line

Miner 2

Miner 3

Proof of work
Miner 1

Finish Line

Miner 2
Continually races,
Back to Back

Miner 3 Miner 3

Proof of work
Miner 1

Finish Line

Miner 2
Continually races,
Back to Back

Miner 3 Miner 3

Proof of work
Miner 1

Finish Line

Miner 2

Miner 3

Proof of work
Miner 1

Finish Line

Miner 2

Miner 3

Proof of work
Miner 1

Miner 2
Finish Line

Miner 2
Miner 3

Miner 3 Miner 4

Proof of work Proof of Stake


Validator 1

Validator 2
Finish Line

Validator 3

Validator 4

Proof of stake
Validator 1

Validator 2
Finish Line

Validator 3

Proof of stake
Validator 1

Validator 2
Finish Line

Validator 3

Validator 4

Proof of stake
Validator 1

Validator 2
Finish Line

Validator 3

Validator 4

Proof of stake
Finish Line

Proof of stake
Finish Line

Proof of stake
Finish Line

Proof of stake
Finish Line

Proof of stake
Finish Line

Proof of stake
Finish Line

Proof of stake
Miner 1
Miner 1

Miner 2
Finish Line
Finish Line
Miner 2
Miner 3

Miner 3 Miner 4

Proof of stake
Proof of work
How do they pick?
Validator
How do they pick?
Validator

How long you have been staking


How do they pick?
ble
Validator sta
u
Tr
&
ble
l i a
Re
How do they pick?
Validator

Randomness : To give everyone fair chance


How long is the Race?

Finish Line
How long is the Race?

Finish Line

Proof of Work

Block Puzzle solve moderately


How long is the Race?

Finish Line

Proof of Stake
How long is the Race?

Finish Line Finish Line

Proof of Work Proof of Stack

10 minutes to mine a blockchain approximately 15 seconds


What is someone cheat?

Free coin

Stake
Fact Check
Fake Transaction

Validator
will lose part Report it
of its stake
Proof of Stake

Transition
Network Grows

Cost of mining increases

Less powerful computer play luck


game
Proof of Work
Proof of Stake

Transition If it is too Early

Network Grows
51% Attack

If it is too late

Less powerful computer play luck


game Too much power consumption
Proof of Work
Proof of Work (PoW)

How It Works: Miners solve complex mathematical problems to validate


transactions and create new blocks. The first to solve the problem gets to add the
block to the blockchain and is rewarded with cryptocurrency.
Pros:
• Highly secure due to the computational power required.
• Proven effective (e.g., Bitcoin).
Cons:
• Energy-intensive, leading to environmental concerns.
• Centralization risk as mining becomes dominated by a few entities with
resources.
Proof of Stake (PoS)

How It Works: Validators are chosen to create new blocks based on the number of
coins they hold and are willing to “stake” as collateral.
Pros:
Energy-efficient compared to PoW.
Reduces the risk of centralization.
Cons:
Wealth concentration can lead to centralization.
"Nothing at stake" problem, where validators can vote on multiple chains.
Delegated Proof of Stake (DPoS)

How It Works: Coin holders vote for a small number of delegates who validate
transactions and create blocks on their behalf.
Pros:
• Fast transaction times due to fewer validators.
• Democratic voting process.
Cons:
• Risk of centralization as a few delegates hold significant power.
• Voter apathy can lead to unrepresentative governance.
Proof of Authority (PoA)

How It Works: A limited number of trusted nodes are authorized to create new
blocks and validate transactions, based on their identity and reputation.
Pros:
• High throughput and low latency.
• Simple and efficient for private networks.
Cons:
• Centralization risk as it relies on a few trusted authorities.
• Less secure as it can be vulnerable to collusion.
Practical Byzantine Fault
Tolerance (PBFT)
How It Works: Nodes communicate with each other to reach a consensus, even
when some nodes may fail or act maliciously. A transaction is accepted once a
supermajority (typically 2/3) agrees.
Pros:
• High fault tolerance and security against malicious nodes.
• Fast transaction finality.
Cons:
• Scalability issues with a large number of nodes.
• Communication overhead can slow down the process.
Proof of Space and Time (PoST)

How It Works: Participants prove that they have allocated a certain amount of disk
space and time to secure the network. The more space they allocate, the higher the
chances of being selected to create a block.
Pros:
• More energy-efficient than PoW.
• Utilizes underused disk space.
Cons:
• Requires significant storage resources.
• Potential for centralization around those with more storage capacity.
Proof of Burn (PoB)

How It Works: Participants “burn” (destroy) a portion of their cryptocurrency to


earn the right to mine or validate transactions. This shows commitment to the
network.
Pros:
• Reduces the supply of the currency, potentially increasing value.
• Encourages long-term investment.
Cons:
• Destruction of coins may deter participation.
• Not as straightforward as other mechanisms.
Proof of Elapsed Time (PoET)

How It Works: Participants wait for a randomly chosen time period before they can
create a new block. The winner is the one whose wait time expires first.
Pros:
• Energy-efficient and simple.
• Reduces the risk of centralization.
Cons:
• Requires a trusted execution environment to ensure randomness.
• Vulnerable to attacks if the environment is compromised.
Hybrid Proof of Work/Proof of
Stake (PoW/PoS)
How It Works: Combines both PoW and PoS mechanisms, allowing miners to
contribute computational power while validators stake their coins for added
security.
Pros:
• Balances security and efficiency.
• Reduces energy consumption compared to pure PoW.
Cons:
• Complexity in implementation.
• Can inherit weaknesses from both mechanisms.
Federated Byzantine Agreement
(FBA)
How It Works: A group of trusted nodes (validators) reach consensus without
requiring all nodes to communicate with each other. Each node can choose which
validators to trust.
Pros:
• Fast consensus with low latency.
• Flexible and scalable.
Cons:
• Trust relies on the chosen validators, risking centralization.
• Less secure than some fully decentralized mechanisms.
Proof of Responsibility (PoR)

How It Works: Validators are chosen based on their reputation and performance in
maintaining the network. They must hold a certain amount of the network's
tokens.
Pros:
• Encourages responsible behavior among validators.
• Reduces the risk of malicious actions.
Cons:
• Requires a robust reputation system.
• Potential for collusion among validators.
Proof of Stake Velocity (PoSV)

How It Works: This mechanism rewards users not only for staking their coins but
also for the speed at which they are transacted, combining elements of PoS and
transaction activity.
Pros:
• Encourages active participation in the network.
• Balances rewards between holding and usage.
Cons:
• Complexity in calculation can lead to confusion.
• Risk of gaming the system through rapid transactions.
How Blockchain works

User Requested
Transaction is Transaction will be validated
User Once the transaction is verified by Transaction Is
Broadcasted to by any node in this Network
Requests A multiple Nodes in the Blockchain completed
Blockchain through some algorithms and
transaction peer-to-peer network then new block gets added to
smart contract chain and replicated across all the
network
nodes
Ethereum Blockchain framework
Ethereum is a decentralized platform that runs smart
contracts: applications that run exactly as programmed
without any possibility of downtime, censorship, fraud or
third-party interference.
Smart Contract
Agreements are written as Smart Contracts.

Smart Contracts are business logic

Transactions are validated against Smart Contract

Digitized and codified rules of transaction between


accounts

In Ethereum world smart contracts are written in


language called Solidity and deployed into Ethereum
network
Smart Contract

A option contract between A triggering event like an Regulator can the


parties written as code expiration date and strike blockchain to understand
into the blockchain. The price is hit and executes the activity in the market
individual involves are itself according to coded while maintaining the
anonymous, but contract terms . privacy of individual actor
are in public ledger. positions.
How smart contract works
https://financesonline.com/what-is-a-smart-contract/
Smart Contract: Where you can use Smart
Contract

Financial derivatives
Insurance premiums
Breach contracts
Property law
Credit enforcement
Financial services
Legal processes
Crowdfunding agreements
And more
Analyze Blockchain data with
SQL and Dune Analytics
What is Dune Analytics?

Dune Analytics is a data querying platform that allows everyone to


query data from blockchain projects and domains such as NFTs and
DeFi, and visualize the results.

Simply put, Dune makes it simple for crypto users to turn blockchain
data into insights, charts, and analytics.

https://benny.hashnode.dev/analyze-blockchain-and-defi-data-in-minutes-with-sql-and-dune-analytics-a-quickstart-guide
How does Dune Analytics work?

Dune Analytics aggregates and parses public blockchain data in a


queryable PostgreSQL database. PostgreSQL is a powerful open-
source relational database that enables querying in both SQL and
JSON formats. It's also known for its resilience, authenticity, and
integrity. A vast amount of blockchain data can be queried with this
database.

Currently, Dune supports Ethereum, Polygon, Optimism, and Binance


Smart Chain data.
Getting started with Dune
Analytics
INTRODUCTION TO OOP

Objective:

•Know the difference between functional


programming
and OOP
• Know basic terminology in OOP
• Know the importance of OOP
• Know four design principles of OOP
• Know OOP programming languages

66
STRUCTURED vs. OO PROGRAMMING

STRUCTURED PROGRAMMING:
MAIN PROGRAM GLOBAL DATA

FUNCTION FUNCTION 2 FUNCTION 3


1

FUNCTION 4 FUNCTION 5

67
Structured Programming

• Using function
• Function & program is divided into modules
• Every module has its own data and function which
can be called by other modules.

68
OBJECT ORIENTED PROGRAMMING

Object 2
Object 1

Data Data

Function Function

Object 3

Data

Function

69
OBJECT ORIENTED PROGRAMMING

Objects have both data and methods


Objects of the same class have the same data elements
and methods
Objects send and receive messages to invoke actions

Key idea in object-oriented:

The real world can be accurately described as a collection of


objects that interact.

70
Basic terminology

object
- usually a person, place or thing (a noun)
method
- an action performed by an object (a verb)
attribute
- description of objects in a class
class
- a category of similar objects (such as automobiles)
- does not hold any values of the object’s attributes
71
Example for attributes and methods

Attributes: Methods:
• manufacturer’s name • Define data items
• model name (specify manufacturer’s
• year made name, model, year,
• color etc.)
• number of doors • Change a data item
(color, engine, etc.)
• size of engine
• Display data items
• etc.
• Calculate cost
• etc.

72
Why OOP?

Save development time (and cost) by reusing code


once an object class is created it can be used in other applications
Easier debugging
classes can be tested independently
reused objects have already been tested

73
Design Principles of OOP

Four main design principles of Object-Oriented


Programming(OOP):

Encapsulation
Abstraction
Polymorphism
Inheritance

74
Encapsulation

Also known as data hiding


Only object’s methods can modify information in the
object.

Analogy:
ATM machine can only update accounts of one person
or object only.

75
Abstraction
• Focus only on the important facts about the
problem at hand
• to design, produce, and describe so that it can be
easily used without knowing the details of how it
works.
Analogy:
• When you drive a car, you don’t have to know
how the gasoline and air are mixed and ignited.
• Instead you only have to know how to use the
controls.
• Draw map

76
Polymorphism

the same word or phrase can mean different things in


different contexts

Analogy:
In English, bank can mean side of a river or a place to
put money
move -

77
Function Overloading

• The operation of one function depends on the argument passed to it.


• Example: Fly(), Fly(low), Fly(150)

78
Inheritance

Inheritance—a way of organizing classes


Term comes from inheritance of traits like eye color,
hair color, and so on.
Classes with properties in common can be grouped
so that their common properties are only defined once.
Superclass – inherit its attributes & methods to the
subclass(es).
Subclass – can inherit all its superclass attributes &
methods besides having its own unique attributes &
methods.
79
An Inheritance Hierarchy

Superclass
Vehicle
Subclasses

Automobile Motorcycle Bus

Sedan Sports Car Luxury Bus School Bus

What properties does each vehicle inherit from the types


of vehicles above it in the diagram?

80
Object-Oriented Programming Languages

· Pure OO Languages
Smalltalk, Eiffel, Actor, Java

· Hybrid OO Languages
C++, Objective-C, Object-Pascal

81
Enum

Solidity supports enumerables and they


are useful to model choice and keep For example, if we consider an
track of state. Enums can be declared application for a fresh juice shop, it
outside of a contract. Enums restrict a would be possible to restrict the glass
variable to have one of only a few size to small, medium, and large. This
predefined values. The values in this would make sure that it would not allow
enumerated list are called enums. With anyone to order any size other than
the use of enums it is possible to reduce small, medium, or large.
the number of bugs in your code.
Structure
You can define your own type by creating a struct.
They are useful for grouping together related data.
Structs can be declared outside of a contract and imported in another contract.

Struct types are used to represent a record. Suppose you want to keep track of yourbooks in a library.

You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Struct

To define a Struct, you must use the struct keyword. The struct keyword
defines a new data type, with more than one member. The format of
the struct statement is as follows −
Structure Example
Data Locations - Storage, Memory
and Calldata

Variables are declared as


either storage, memory or calldata to explicitly specify the
location of the data.
• storage - variable is a state variable (store on blockchain)
• memory - variable is in memory and it exists while a function
is being called
• calldata - special data location that contains function
arguments
Function

There are several ways to return outputs from a function.


Public functions cannot accept certain data types as inputs or outputs

View and Pure Functions

• Getter functions can be declared view or pure.


• View function declares that no state will be changed.
• Pure function declares that no state variable will be changed or read.
Function Modifier

Modifiers are code that can be run before and / or after a function call.
Modifiers can be used to:
• Restrict access
• Validate inputs
• Guard against reentrancy hack
Events

Events allow logging to the Ethereum blockchain. Some use cases for
events are:
• Listening for events and updating user interface
• A cheap form of storage
Constructor

A constructor is an optional function that is executed upon


contract creation.
Inheritance

• Solidity supports multiple inheritance. Contracts can inherit other


contract by using the is keyword.
• Function that is going to be overridden by a child contract must be
declared as virtual.
• Function that is going to override a parent function must use the
keyword override.
• Order of inheritance is important.
• You have to list the parent contracts in the order from “most base-
like” to “most derived”.
Shadowing Inherited State Variables

Unlike functions, state variables cannot be overridden by re-declaring it


in the child contract.
Visibility

Functions and state variables have to declare whether they are accessible by other contracts.
Functions can be declared as
• public - any contract and account can call
• private - only inside the contract that defines the function
• internal- only inside contract that inherits an internal function
• external - only other contracts and accounts can call
State variables can be declared as public, private, or internal but not external.
Function Visibility Specifier in Solidity

Function in Solidity is a set of code that performs a specific task. The function
provides reusability of code in smart contracts. In Solidity, functions are defined
using the function keyword. The syntax of the function definition in Solidity is:

Function visibility in Solidity defines the visibility of the function to other functions
within the contract, or in other contracts. Function visibility helps to identify where in
the contract or in other contracts, functions can be used. It is specified by the developer
of the smart contract. The default variable visibility in Solidity is internal. The default
function visibility in Solidity is public.
How do Function Visibility Modifiers and Inheritance Work
Together?
Calling Parent Contracts

Parent contracts can be called directly, or by using the keyword super.


Interface

You can interact with other contracts by declaring


an Interface.
Interface
• cannot have any functions implemented
• can inherit from other interfaces
• all declared functions must be external
• cannot declare a constructor
• cannot declare state variables
Payable

Functions and addresses declared payable can receive ether into the
contract.
Sending Ether (transfer, send, call)

How to send Ether?


You can send Ether to other contracts by
• transfer (2300 gas, throws error)
• send (2300 gas, returns bool)
• call (forward all gas or set gas, returns bool)

How to receive Ether?


A contract receiving Ether must have at least one of the functions below
• receive() external payable
• fallback() external payable
receive() is called if msg.data is empty, otherwise fallback() is called.

Which method should you use?


call in combination with re-entrancy guard is the recommended method to use after December 2019.
Guard against re-entrancy by
• making all state changes before calling other contracts
• using re-entrancy guard modifier
Fallback
fallback is a special function that is executed either when
• a function that does not exist is called or
• Ether is sent directly to a contract but receive() does not exist
or msg.data is not empty

fallback has a 2300 gas limit when called by transfer or send.


Call
call is a low level function to interact with other contracts.
This is the recommended method to use when you're just sending Ether via calling
the fallback function.
However it is not the recommend way to call existing functions.
Few reasons why low-level call is not recommended
• Reverts are not bubbled up
• Type checks are bypassed
• Function existence checks are omitted
Delegatecall
delegatecall is a low level function similar to call.
When contract A executes delegatecall to contract B, B's
code is executed.
With contract A's storage, msg.sender and msg.value.
Function Selector

When a function is called, the first 4 bytes of calldata specifies which function to call.
This 4 bytes is called a function selector.
Take for example, this code below. It uses call to execute transfer on a contract at the
address addr.

addr.call(abi.encodeWithSignature("transfer(address,uint256)", 0xSomeAddress, 123))

The first 4 bytes returned from abi.encodeWithSignature(....) is the function selector.


Perhaps you can save a tiny amount of gas if you precompute and inline the function selector
in your code?

You might also like