0% found this document useful (0 votes)
12 views74 pages

IS4302 Lecture 2 Fall 2024

Uploaded by

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

IS4302 Lecture 2 Fall 2024

Uploaded by

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

IS4228: Information Technology and Financial Services

IS4302
Blockchain and Distributed
Ledger Technologies
Week 2

© Copyright National University of Singapore. All Rights Reserved.


Overview

• Introduction to Blockchain (cont.)

• Ethereum basics

• Solidity language basics

2
The shared ledger is maintained without a central
authority (“bank”)
Network

• New transactions are broadcast to all nodes.


• Each node collects new transactions into a block.
• Each node works on finding the nonce for its block.
• When a node finds a nonce, it broadcasts the block (nonce)
to all nodes.
• Nodes accept the block only if all transactions in it are valid
and not already spent.
• Nodes express their acceptance of the block by working on
creating the next block in the chain, using the hash of the
accepted block as the previous hash.

4
Consensus algorithm

• Forking:

• The longest chain is considered to be the correct one.


• (Honest) nodes will keep working on extending it.

5
The first person to confirm a new change to the
ledger shares it
Maintainers certify transactions (changes) to the
ledger
Maintainers switch to confirmed ledger and start working on
next version (with transactions from the following 10-minute
cycle)
Proof-of-work system

• Analogous to a majority voting system.


• Vote not counted by heads but the amounts of
computational power that supports various arguments in a
disagreement.
• To implement this, we need a puzzle that is moderately
hard (yet feasible) to solve but easy to check.
• Calculating a hash value is easy.
• Reverting a hash function can be computationally not
feasible.
• Find an input, the hash of which is within a range. This
range can be changed to tune the difficulty of the puzzle.
9
Proof-of-work system

• Increment a nonce in the block until a value is found that


gives the block’s hash within the required range.

• Finding the nonce takes computational effort.


• Whoever finds the nonce first gets the power to write the
next block.
• The likelihood of finding a nonce first is proportional to
the computational power (hash rate).
10
Summary of Bitcoin Network’s consensus algorithm
• Writers show disagreement through forking.
• Writers show support for each fork by working on extending
it.
• The speed of extending a fork is (statistically) proportional to
the computational power works on it.
• The longest chain is considered the valid one and the creators
of blocks on it can earn coin rewards.
• Results of the consensus algorithm:
• If a writer cares about the voting results, it is a majority voting
where the number of votes is proportional to computational
power.
• If a writer cares only about the coin rewards instead of voting
results, this writer always works on the longest (winning) fork. 11
Double spending attack

• An attacker trying to generate an alternate chain longer


than the honest chain.
• Even if this is accomplished, it does not throw the system
open to arbitrary changes.
• An attacker can only try to change one of his own
transactions to take back money he recently spent.
• And then spend it again.

12
Double spending attack

13
Security

• Delay before finalization


• Usually recommend 6 blocks (10 min/block)
• The more blocks the receiver of the transaction wait before
the finalization of the deal, the more security the receiver
has.
• If the attacker controls less than half computational
power, exponentially less likely for the attack to be
successful.
• This is why the “chain” matters.

14
Privacy
• The traditional banking model achieves a level of privacy
by limiting access to information to the parties involved
and the trusted third party.
• The necessity to announce all transactions publicly
precludes this method.
• Privacy can still be maintained by breaking the flow of
information in another place: by keeping public keys
anonymous.
• The public can see that someone is sending an amount to
someone else.
• But not knowing who they personally are.
• Similar to the level of information released by stock
exchange 15
Privacy

16
Privacy

• A new key pair should be used for each transaction to keep


them from being linked to a common owner.

• Some linking is still unavoidable with multi-input


transactions, which necessarily reveal that their inputs
were owned by the same owner.

• If the owner of a key is revealed, linking could reveal other


transactions that belonged to the same owner.

17
My summary of blockchain in its original form

• Key ideas
• Distributed power of writing the ledger to avoid trust on
centralized authority.
• “chain” structure to ensure the security of the distributed
ledger.

• Key assumptions
• The majority of the nodes will work honestly on writing
the ledger.
• The nodes will publicize the nonce once they found it for
a block.
18
Overview

• Introduction to Blockchain (cont.)

• Ethereum basics

• Solidity language basics

19
Overview

• Introduction to Blockchain (cont.)

• Ethereum basics
• Ethereum vs. Bitcoin
• Proof of Work vs. Proof of Stake
• Smart Contracts

• Solidity language basics

20
Key differences between Bitcoin & Ethereum

21
https://youtu.be/owFY_z5fF-Y
Key differences between Bitcoin & Ethereum

Bitcoin network Ethereum network


Use Bitcoin (BTC) Crypto Currency Ether (ETH) Crypto Currency;
Many types of digital assets;
Decentralized, executable
programs
Consensus Proof of Work Proof of Stake
mechanism
Transaction 10 minutes 12 seconds
Speed
Maximum 21 million bitcoins No maximum
cap
Tracking Unspent Transaction Outputs Account-based
Balances (UTXO)

22
UTXO vs Account-based
• What is UTXO?
• “Unspent transaction”
• Each UTXO represents an currently ‘unspent’ note of a
defined value
• Each UTXO can only spent only ONCE
• A transaction takes in unspent UTXO, and generate new ones
• Sum of inputs and outputs is same

23
UTXO model (Bitcoin)

24
UTXO model (Bitcoin)

• Money can be sent to a new address

25
UTXO model (Bitcoin)

• The state of the blockchain is stored as a list of unspent


outputs

26
UTXO model (Bitcoin)

• Old rows removed


• New rows added
• Don’t need to worry about order of transactions,
Either the transaction goes through or it fails

27
UTXO vs Account-based

• Account-based model (Ethereum)


• Account keys are derived from crypto public keys
• Keys are re-used (unlike UTXOs)
• Balances are tied to each key
• Key can also be used to represent an identity
• Transactions represent state change

28
Ethereum model (Ethereum)

29
Ethereum model (Ethereum)

• Updates Rows, reusing old addresses


• Cannot run in parallel, depends on order

30
Ethereum model (Ethereum)

• Updates Rows, reusing old addresses


• Easier for interacting & updating contracts that stay at
specific addresses

31
UTXO vs Account-based

• Generalized calls using smart contracts


• Ledger is history of a general state machine
• Transactions represent valid state transitions in a
[gigantic] state machine
• Smart contracts define what valid transitions are
• Mixed with primitive transactions (simple eth token
transfer)

32
Overview

• Introduction to Blockchain (cont.)

• Ethereum basics
• Ethereum vs. Bitcoin
• Proof of Work vs. Proof of Stake
• Smart Contracts

• Solidity language basics

37
Ethereum 2.0

38
Proof of Work (PoW) in Blockchain

• Miners “lock up” their money in hardware costs


• They spend electricity to have the chance to validate a
block of transactions, and win the block reward, plus tips
• The more they spend (in electricity and hardware) the
higher their hash rate, and the greater chance they have
to win

39
Proof of Work (PoW) in Blockchain

• Why do we need this at all?

40
Proof of Work (PoW) in Blockchain

• Why do we need this at all?


• To make forking the
blockchain expensive
• This prevents “double
spending”

41
Proof of Work (PoW) in Blockchain

• What are the downsides of Proof of Work?

42
Proof of Work (PoW) in Blockchain

• What are the downsides of Proof of Work?


• Lots of “needless” Electricity Use and Pollution

https://digiconomist.net/bitcoin-energy-consumption

43
Proof of Work (PoW) in Blockchain

• What are the downsides of Proof of Work?


• Centralization Risks
• Mining Pools
• Geographic Centralization

44
Mining pools/Significant miners

• Miners tend to form pools or become


significant miners because of:

• Lower Volatility
• Miners form pools to smooth their income
stream.

• Economics of Scale
• Large mining factories are much more cost
effective than a single CPU/GPU.

45
Proof of Work (PoW) in Blockchain

• What are the downsides of Proof of Work?


• Centralization Risks
• Mining Pools
• Geographic Centralization

https://chainbulletin.com/bitcoin-mining-map/
46
Proof of Stake (PoS) in Blockchain

• Instead of hardware and electricity, validators can


stake currency on-chain.

47
Proof of Stake (PoS) in Blockchain

• Staking
• You “lock up” a certain amount of tokens and run
a node that validates transactions

48
Proof of Stake (PoS) in Blockchain

• Choosing a Validator
• The blockchain chooses semi-randomly which
“validator node” gets chosen to validate the
transactions in a block and paid a reward

49
Proof of Stake (PoS) in Blockchain

• Choosing a Validator
• The more crypto that is staked, the higher the
chances you will be chosen as a validator

50
Proof of Stake (PoS) in Blockchain

• Validating
• Your computer checks that the signatures are correct and
double spending hasn’t happened
• Other nodes on the network check that the validation is
correct
• If you validate truthfully, you collect the transaction fees. If
you “lie,” your stake is forfeit.

51
Advantages of PoS

• Energy-efficient (uses 99.95% less electricity)

• Decentralized
• In PoW mining pools cause centralization, there are
“economies of scale”
• In PoS rewards scale linearly with size of stake

52
Weakness of PoS

• Rich get Richer effects

• Novel Technology, potential for novel attacks

• Forking
• If the blockchain “splits” a validator node can have it’s
same stake on both branches and keep validating both
instead of forcing a convergence

53
Proof-of-Authority (Permissioned Chains)

• Pre-chosen, reputable validators and known ahead of


time
• Useful for private/consortium settings and
permissioned networks
• Consensus participants are known and reputable.
• No need for mining or transaction fees.
• More secure against 51% attacks if the chain is small
or low-value.
• Can be faster with lower fees (less coordination costs)
• Ripple (XRP) uses a mechanism similar to PoA where a
set of “trusted nodes” collectively vote to approve or
dispute transactions

54
Overview

• Introduction to Blockchain (cont.)

• Ethereum basics
• Ethereum vs. Bitcoin
• Proof of Work vs. Proof of Stake
• Smart Contracts

• Solidity language basics

55
Smart contracts in Ethereum

• Tiny computer programs


• The “rules” are transparent to all users
• Automatically execute, no matter what
• Often handles money
• No trusted 3rd party
• Ethereum specifically created to support smart contracts

56
Smart Contract Use Cases

• Finance:
• Insurance, crowd-funding,
cross-border payments,
real-world asset
tokenization
• Games:
• Betting markets, In-game
assets
• Business
• Supply chain tracking,
automatic royalties, voting
57
Overview

• Introduction to Blockchain (cont.)

• Ethereum basics

• Solidity language basics

58
Solidity – basic structure

• pragma
• Defines solidity version
• Contract / Library
• Features:
• Class Inheritance
• functions
• visibility/scope
• Strongly typed
• Aspect oriented
• Language reference:
https://docs.soliditylang.org/en/v0.8.11/ 60
Solidity – basic structure

Reader.sol

ReadWriter.sol

61
Solidity – basic structure

62
Solidity – basic data types
• bool – boolean
• enum <name> { <member names> … }
• example: enum direction { left, right, up,
down }
• int, uint, int8, uint8, int16, uint16 … uint256
• signed (int) and unsigned (uint) integers (with size, defaults to
256)
• int = int256, uint = uint256
• int8 => 1 byte signed integer
• address – holds a 20 byte address
• contract
• Bytes1 .. Bytes32 – fixed size byte array
• String 63
Solidity – complex data types
• bytes – dynamic array of bytes
• <type>[ ] – dynamic array
• Ex: uint[ ] numberArray;
• mapping( <key type> => <value type> )
hash map of <key type> to <value type>
• Ex: mapping(address => uint) balance;
• struct <name> { <member types> }
• Ex:
struct record {
uint id;
address addr;
}

64
Solidity – storage scope

• Local variables – defined within scope of a function. Working


variables during smart contract execution. Consumes EVM
stack memory during execution, discarded after the call.
• Example:

contract ReadWriter {

function foo() {
uint temp;

}
}
65
Solidity – storage scope

• State variables – defined within scope of a contract. Persistent


storage, stored in Ethereum’s ledger
• Example:

contract ReadWriter {
uint data;
}

66
Solidity – storage scope

• Function parameters and local variables can also be defined as


storage or memory explicitly.
• storage – EVM’s persistent storage (expensive for GAS).
Default for state variables
• memory – EVM temporary storage. Default for local variables

67
Solidity – language syntax

• Operators on bool: ! && || == !=


• Comparison for numerals: <= < == != >=
• Bit operators: & | ^
• Shift operators: << >>
• Arithemetic operators: + - * / % ** (power)
• Address function calls: send call delegatecall staticcall
• Control structures(same as c/c++/java/javascript):
if, else, while, do, for, break, continue, return
• Comments:
//comment
/* more
comments */

68
Solidity – function syntax

69
Solidity –visibility

• external – can be called from another contract using call


or delegatecall
• public – public function or state variables that is callable (eg.
using web3)

• internal – function or state variables accessible from current


or inherited contracts
• private – function or state variables accessible from current
contract

70
Solidity – function modifier

• payable – able to receive ether. Otherwise, the call will


throw an error if ether is provided.

• view – does not change state variables. Can be called


without transaction fee (read-only functions, does not
modify state at all)

• pure– does not access state variables at all. Can be called


without transaction fee. ‘pure’ calculation function.

71
Solidity – function modifier using _

72
Solidity – some special functions & variables

• function () – fallback function, for all calls without


defined function name
• selfdestruct() – permanently disable contract
• block.timestamp = now – timestamp at miner’s
execution time
• msg.value – amount of ether sent in transaction call
• msg.sender – caller of current transaction
• tx.origin – original caller of transaction chain
• tx.gasprice – gas price specified by caller
73
Solidity – msg.sender vs tx.origin

74
Solidity – Library re-use

• library - does have its own persistent storage and


cannot hold ether. It is used in the storage context of the
calling contract.

76
Solidity - events

• Events – allow applications to subscribe and listen to these


events through an Ethereum client.

Definition:
event <name> (<parameters>)

send event:
emit <name> (<parameters>)

77
Solidity – events (example)

78
It should print details similar to as following −

79
Thank you!

80

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy