You are on page 1of 151

BLOCKCHAIN

Dr. Emmanuel S. Pilli


Malaviya NIT Jaipur
Bitcoin: First Blockchain Based
Cryptocurrency
■ Proposed by Satoshi Nakamoto
in 2008- “Bitcoin: A Peer-to-Peer
Electronic Cash System”

■ On January 3, 2009, Satoshi


Nakamoto mined the first ever
block on chain, known as the
genesis block.
Genesis Block
On the day of its launch,
coinbase of genesis block
references a story in Times of
London-

“Chancellor bailing out banks


- Bitcoin’s libertarian roots”

Block Reward: 50 BTC


Mining of Bitcoins
■ Generation of Bitcoins is based on solving an encryption formula which
requires extreme amounts of computing power.
– Each time you solve the formula you earn some bitcoins.
■ Only 21 million bitcoins will ever exist.
■ Nearly 93% bitcoins have been mined.
■ Daily on an average 144 blocks are mined.
■ Daily about 900 new bitcoins are mined with the current block reward of
6.25 BTC per block.
Bitcoin Denominations

Other Bitcoin denominations:


1 bitcoin
= 1,000 millibitcoins (mBTC);
= 10,00,000 microbitcoins (μBTC);
= 100,000,000 satoshis
Bitcoins transactions and transaction fees are made in Satoshis.
Transfer of Bitcoins
If you want to get some bitcoins, you either:
■ Buy it from a bitcoin exchange using fiat currency (ex. Rs, USD)
■ Get a friend to transfer it to your bitcoin address
■ Mine a bitcoin block with -
– current hashrate: ~494.6 Million TeraHashes per second (on Nov 23rd,
2023)
– current mining reward: 6.25 BTC

Source: Blockchain.com
Bitcoin Hash Rate

■ It is a measure of how many times the Bitcoin network can attempt to solve
Proof of Work (POW) puzzle per second for mining.
■ The more hashing power in the network, the greater its security and overall
resistance to 51% attack.
Halving of Bitcoin Rewards
Halving of Bitcoin rewards:
■ Every 210,000 blocks (approx. 4 yrs)
■ Maintains a controlled supply of currency. As reduced supply leads to
an increased demand.
■ Previous halvings:
– Jan 2009: 50 BTC
– Nov 2012: 25 BTC
– Jul 2016: 12.5 BTC
– May 2020: 6.25 BTC
■ Next halving:
– At block 740,000, approx in April, 2024
– Block reward: 3.125 BTC
Bitcoin - Gaining Value
■ 1st Bitcoin transfer: from Satoshi Nakamoto to Hal Finney.
■ May, 2010: Laszlo Hanyecz purchased $25 worth of pizza for 10,000 BTC.
■ 2010: Jed McCaleb creates Mt. Gox, the biggest online bitcoin exchange.
■ 2014: Mt. Gox loses 744,408 bitcoins in a theft; Mt. Gox declares
bankruptcy.
Bitcoin- Gaining Value
■ Feb 2011: Silk Road
opens as the anonymous
“eBay of Drugs”, using
Tor and payments using
Bitcoin.
■ Oct 2013: the FBI shut
down Silk Road.
■ Bitcoin Boom:
Dec 2017: Bitcoin price
~ Rs. 13 lacs
Nov, 2021: 1 BTC ~ Rs.
47 lacs
Bitcoin - Gaining in Last 1 Year
Highest BTC value in Nov 2021, 1 BTC ~ Rs. 47 lacs
Currently, 1 BTC ~ Rs. 31.4 lacs (on Nov 24th, 2023)

Considered as
Digital Gold by
market experts.

Source: Coinbase (Accessed on Nov 24th, 2023)


Explosion of Altcoins
Top 10 Crypto Coins

Token pegged
to US dollar

ETH staked
in LIDO
liquidity
Token pegged protocol
to US dollar

Token on
Binance
blockchain
Token on
Cardano
blockchain

Ripple Token Currency


on XRP used as a
ledger tipping
system
Cryptography in Bitcoin

■ Elliptic Curve Cryptography:


– secp256k1 elliptic curve over a finite field of prime order p:

y256
2
= (x332+ 7) 9mod8 p 7 6 4
■p=2 –2 –2 –2 –2 –2 –2 –1
■ Security of Bitcoin is guaranteed by the inefficiency of Elliptic Curve
Discrete Logarithm Problem (ECDLP) solution for large enough
private keys.
i.e. finding the integer k such that P = k * G
Cryptography in Bitcoin
■ Ownership of Bitcoins is established through:
– Digital keys
– Digital signature
■ Use of Asymmetric cryptography in which a pair of keys
(public/private) is used.
■ Public key is used to receive funds and Private key is used to sign txns
to spend funds.
■ Private key, k is a 256 bit random number within 1 and 2256.
■ Public key, P is a point on elliptic curve generated from private key:
P=k*G
where, G is the generator for the elliptic curve
It is a one-way function and calculating P from k is not possible.
Cryptography in Bitcoin
Public key and Address generation:
Digital Signatures
■ Digital signatures are used in txns to provide authentication of who is
signing the transaction and integrity of the msg being signed.
■ It also provides non-repudiation which ensures that neither the sender or
receiver can deny participating in the communication.
■ Digital Signature used in Bitcoin:
– Elliptic Curve Digital Signature Algorithm (ECDSA)
– Schnorr Signature
Digital Signatures
Significance of Bitcoin
■ First ever cryptocurrency which is:
– purely digital,
– not controlled by any central entity,
– solves double spending issue.
■ Peer-to-peer network in which transactions directly between users; no
intermediary.
■ Transactions verified by network users.
■ Transactions recorded as block in public ledger- blockchain
Blockchain

Blocks are chained together using the previous block’s hash to form a
Blockchain.

Source: Bitcoin whitepaper


Blockchain – Distributed Ledger
It is a method of storing data amongst multiple parties that ensures data
integrity.
A “distributed ledger” or shared database where:
❏everyone holds a copy of entire logged history of txns,
❏is immutable,
❏is timestamped.
Blockchain Transaction

Txns are msgs that let users spend their Bitcoins.

Hash of the txn


Output public keys (addresses) receiving
Input public key (address) bitcoins
spending bitcoins

Amount of Bitcoin
Txn fees = Output bitcoins - Input transferred
bitcoins
Blockchain Transaction
In a Bitcoin txn, each input spends the bitcoins paid to a previous output.

Source: Bitcoin Wiki


Blockchain Transaction

When a user wants to spend bitcoins:


1. User creates a txn.
2. Txn is sent to her immediate peers.
3. Txn is verified, if validated it is sent to their neighbouring peers.
4. Txn is broadcasted in the entire peer-to-peer (p2p) network.
Bitcoin Transaction
Bitcoin Transaction

Receiver’s address
Blockchain Databases
Other than blockchain, each bitcoin client stores these databases as well:

UTXO set -
■ file that contains all the spendable o/p that are available to be spent in
a txn.

Mempool -
■ file that contains txns which are received by peer nodes but are yet to
be included in any block i.e. unconfirmed txns.
Hashing
Cryptographic hash function used: SHA256

Source: Blockchain Demo


Block

Source: Blockchain Demo


Block

Each block is linked to its previous block by a link making it a chain of


blocks.
Bitcoin Block Size
Bitcoin block size ~ 1MB
Number of transactions may differ in each block.
■ Segwit has increased the number of transactions in a block.
Blockchain Hash

Source: Blockchain demo


Block Header

Each block contains:


● cryptographic hash of the
previous block,
● timestamp,
● transaction data

BlockID = H(block header) = H(prev block hash || merkle root || nonce)


Immutability

Blockchain is Immutable as any change in a previously accepted txn will


cause change in hash of subsequent blocks.
■ prevents Double Spending of funds.
Immutability in Blockchain

Difficult to change data in transactions in blockchain as:


■ Avalanche Effect in Cryptographic hash function
– Slight change in input can cause significant and unpredicted change in
output.
Immutability in Blockchain
As each block chains back to the previous block.
change in data in a transaction

change in hash of transaction

change in hash of block

change in hash of next block


Immutability in Blockchain
Difficult to change data in a block without mining successive blocks.

Data changed in this block. Change in hash of next blocks. Requires re-mining of blocks.
Bitcoin Ledger
We can check ledger of bitcoin on a blockchain explorer like
blockchain.info, blockexplorer.com

No. of block added to the Mining pool which


longest chain has mined this block No. of txns in Size of the block Time at which block is
block ~ 1 MB mined, included by
miner
Bitcoin Ledger

Block Size > 1MB

Source: Blockchain.com (Accessed on Nov 24th, 2023)


Bitcoin Ledger
No. of blocks added referring to this
block
Block hash
with 19 preceding zeros. Hash of previous block it refers to
Depends upon the difficulty of block mining

Hash of next block that


No. of txns included in this refers to it Txns are arranged in data structure: Merkle Tree.
block This is the hash of its root.
Bitcoin Ledger
Bitcoin Transaction:
Fees Included in txn
Input bitcoin addresses = Output - input
sending bitcoins Claimed by miner
Amount of bitcoins Output bitcoin
Txn hash sent in the txn addresses receiving Amount of bitcoin
bitcoins received
Merkle Root

Merkle Root combines the hash values of txns together until there is a
singular root (a Merkle tree root hash).

It is an effective mechanism to:


■ summarize txns in a block.
■ verify the presence of a txn in a block.
■ provide immutability of txns since Merkle root hash will not
match if change is made to any txn.
Merkle Root
● Tree like data structure to store blockchain txns information in a
block header.
● Merkle tree root hash is stored in the block header.
Consensus Mechanism

■ Consensus Mechanism is implemented in a decentralized network to


take over the responsibilities from the central control. ex. a bank
managing users’ money.
■ In a blockchain, it ensures the integrity of the block and the
transaction within it that have to be added in the ledger.
■ The ledger is updated when all the participating nodes accepts a block
and constituent transactions as valid.
■ The updated ledger is broadcasted to all the nodes in the network.
Byzantine Generals’ Problem

■ Faults in a distributed network:


– Fail-stop fault- When a node is unable to communicate/offline/
NA.
– Byzantine fault- When a node if malicious. It can validate an
incorrect transaction/stop valid transactions from being included in
blockchain.
Two Generals’ Problem

■ In an army, the generals


have to agree on either
Attack or Retreat.
■ In case of 2 generals,
even if both are honest,
due to unreliable nature
of communication, the
consensus cannot be
achieved in an assured
manner.
Three Generals’ Problem

■ In case of 3 generals, 1
commander and 2 lieutenants, if 1
is faulty (Byzantine) and others
are loyal:
– Consensus cannot be achieved
as Lieutenant1 has received
conflicting msgs- Retreat,
Attack.
Four Generals’ Problem

■ In case of 4 generals, 1
commander (Byzantine) and 3
lieutenants (honest). Consensus
can be achieved as the received
msgs are:
– Lieutenant1- R, R, A
– Lieutenant2- R, R, A
– Lieutenant3- R, R, A
■ Final decision- Retreat.
Consensus achieved
n Generals’ Problem

■ To achieve consensus in a distributed network with upto f faulty nodes,


a minimum of 3f+1 total nodes are required.
– f : Byzantine nodes
– 2f+1 : Honest nodes
■ Some common consensus mechanisms used in Blockchains:
– Proof of Work- Bitcoin, Litecoin
– Proof of Stake- Ethereum, Cardano
– RAFT- used in enterprise blockchains
Mining a Block

Mining is the process to find new block.


■ To add a new block, miners need to verify it by solving a computationally
difficult Proof of Work (PoW) puzzle.
■ It involves brute force computations which spend resources.
■ PoW involves scanning for a value (called nonce) that when hashed
results in a hash beginning with a number of 0s.
Mining Process

A bitcoin miner must:


1. Download the entire bitcoin blockchain
2. Verify incoming transactions
3. Create a block
4. Find a valid nonce
5. Broadcast your block
6. Profit!
Mining Process

It confirms the transactions in a


trustful manner when enough
computational power is
devoted to block.
Proof of Work

Mining a block is difficult


because the SHA-256 hash of a
block header must be lower
than or equal to the target.
Bitcoin Difficulty
■ Measure of how difficult it is to mine a Bitcoin block.
– Difficulty = MAX_TARGET / current_target

■ Adjusted every 2016 blocks to keep average block mining


time ~ 10 mins.
– Next Difficulty = current difficulty * 2 weeks / T ( Time in
which previous 2016 blocks found)
– High difficulty => Lower target value
– Low difficulty => Higher target value
Target Value

To compensate for increasing hardware speed and varying interest in


running nodes over time, the proof-of-work difficulty is determined by a
moving average targeting an average number of blocks per hour. If
they’re generated too fast, the difficulty increases.
■ adjusts every 2016 blocks (roughly 2 weeks).
■ ensures that a block is mined once every 10 mins on average.
CPU, GPU, ASIC Mining
■ Originally Satoshi Nakamoto proposed "1 CPU 1 vote" mining, but over
time Bitcoin miners adopted GPUs , FPGA and ASICs.
■ When bitcoin was first released, one could mine 100 bitcoins a day using
CPU.
■ Now, bitcoin mining hardware (ASICs) are high specialized computers
used to mine bitcoins.
CPU, GPU, ASIC Mining
■ ASIC is a microchip specifically designed to execute a hashing
algorithm as quickly as possible.
■ ASICs cost a significant amount of money in electricity bills.
■ Cooperating miners pool together who agree to share block rewards
in proportion to their contributed mining power.
CPU, GPU, ASIC Mining
Centralization in Mining:
Due to the costs and logistical issues, ASICs inevitably leads to powerful
mining farms taking over huge % of the hash rate.
So, ASIC resistant mining algorithms (memory-hard algorithms) are
developed:
■ HashCash (BitCoin) : https://github.com/bitcoin/bitcoin
■ Proof of Stake ( Upcoming Ethereum Mining Algo) :
https://github.com/ethereum/casper
CPU, GPU, ASIC Mining

ASIC resistant mining algorithms:


■ Equihash : https://github.com/khovratovich/equihash
■ Ethash (Current Ethereum Mining Algo) :
https://github.com/ethereum/ethash
■ RandomX: adapted by Monero
Proof of Stake
Eth 2.0: Proof-of-Stake blockchain and Shard Chains.

Phase 0 rolled out as Beacon chain in Dec, 2020:


Shard Chains-
■ Rather than just one blockchain, Ethereum will become 64 blockchains all
running in parallel.
■ It will increase the number of txns Ethereum can handle per second.
Proof of Stake
Miners are chosen depending on:
■ The relative value of coins held in the miner’s wallet.
■ The length of time that a miner has held coins in their wallet.

More stake a user has in the system, the more likely it will want the
system to succeed thus expecting honest behavior.
Delegated Proof Of Stake
■ Stakeholders select a node (delegate) that proposes and validates a
block.
■ Delegates are selected using some lottery mechanism.
■ Delegates are scored based upon:
– Punctuality in block creation when selected.
– Creating valid blocks.
■ Blockchains like Ethereum and Cardano use DPoS, as they use
staking pools which other users can delegate to.
■ The more stake that is delegated to a stake pool, the greater chance it
has of being selected as a slot leader.
Risks in Cryptocurrency

■ Cryptocurrencies are extremely volatile as they are prone to:


– Market hype
– Security risks - double spending, 51% attack, network attacks,
privacy attacks.
– Volatility
– Liquidity
– Unclear regulations
■ Once cryptocurrency is stolen, it gets difficult to recover it due to
irreversible nature of txn.
Top Crypto Hacks

■ Mt. Gox Hack (2011, 2014)


■ Decentralized Autonomous Organization (DAO) attack
■ Nomad Bridge hack
■ Ronin network, Axie Infinity hack
■ Poly network attack
■ Coincheck exchange hack
■ Binance exchange hack
■ …. many more !!!
What is Double Spending?

Gillian promises 10 BTC to Brian


in one txn, and she promises same
10 BTC to Nadir in another.
Here, Gillian is performing a
double spend attack.
A Successful Double Spending Attack in
Blockchain
■ Buyer sends the same coin to 2 sellers in different txns.
■ Possible if two blocks each with one of these conflicting txns are mined
at same approx time.
■ Successful if Seller B sends the services before confirmation of txn and
is later rejected by the network.
A Successful Double Spending Attack in
Blockchain
The transaction which get the maximum number of confirmations from the
network will be included in the blockchain.
A Successful Double Spending Attack in
Blockchain
Buyer succeeds in double spending his coin by issuing a:
■ confirmed txn to Seller A.
■ rejected txn to Seller B, but received services nonetheless.
51% Attack in Blockchain
When a single miner or a group of miners attains majority of the
network’s hash rate.
Effects:
■ prevent txns & blocks from being verified.
■ reverse txns to allow double spending.
■ prevent other miners from finding any block.
■ fork the blockchain.
51% Attack in Blockchain
■ Can happen when there is centralization by mining pools which
acquire >50% hash power.
■ It is easy to implement in altcoins.
■ In order to control 51% of an altcoin network hashrate, only a small
proportion of miners from larger coins need to switch to a smaller
coin.
51% Attack in Blockchain
■ Extremely expensive for popular blockchains like Bitcoin, Ethereum.
■ But it gets much cheaper quickly for newer blockchains.
■ A research has demonstrated that it would take as little as $1.5
million to execute a 51% attack on Ethereum Classic (ETC) —
with a market cap of over $2 billion.
51% Attack in Blockchain
Ex. An Ethereum hard fork, Ethereum Classic (ETC), suffered 51% attack
3 times in Aug 2020.
■ Attack can be identified by an unusual high rate of orphaned blocks.
Mitigation:
A blockchain DASH uses a secondary validation layer called Chainlocks.
It prevents block reorg by making it expensive for attacker.
Selfish Mining Attack in Blockchain
Honest Chain

Selfish Miner Chain

■ It is when the miners deliberately keep their blocks private upon


discovery.
■ They continue to mine their own private blocks to obtain a chain longer
than the public blockchain.
■ Then they release the private blocks for higher rewards.
Effect:
Efforts put by honest miners to mine blocks are wasted.
DDoS Attack on Blockchain

No or minimal adverse effect due to distributed network.


But, Multiple DDoS Attack launched on:
■ competing miners, effectively taking them out of the network and
increasing the malicious miners’ effective hashrate.
■ honest miners to waste their time in verifying fake txns, reducing their
chance of mining a block.
Network Attacks on Blockchain
Goal is to isolate a user from the real network and lead them to a fake
network.
ex. DNS Attack:

● When a new node joins


the blockchain network, it
is bootstrapped to some
DNS nodes to download
the blockchain.
Network Attacks on Blockchain
Goal is to isolate a user from the real network and lead them to a fake
network.
ex. DNS Attack:

● Fake entry point nodes


returned to user.
● User could be routed to
some alternate network
rather than current
blockchain.
Network Attacks on Blockchain
Eclipse Attack:
■ When a group of malicious nodes isolate its neighboring node,
compromising their incoming and outgoing traffic.
■ They change the blockchain view of honest node.
■ Feed them fake information regarding blockchain and txns.

White honest nodes attacked by red malicious nodes


Network Attacks on Blockchain
Eclipse Attack:
■ Malicious nodes then send fake transactions and blocks to these
nodes.

White honest nodes attacked by red malicious nodes


Privacy Attacks on Blockchain

A blockchain
network is
considered
anonymous as:
each user is
identified by its
address only and
can generate as
many addresses as
required.
Privacy Attacks on Blockchain

As blockchain is replicated at each node,


■ observer can use the txn history in blockchain to find:
– topology of the network
– patterns of the transactions
– patterns of users’ interactions
Privacy Attacks on Blockchain
User can be mapped to its geographical location using network
information.
Privacy Attacks on Blockchain

■ Txn network can be developed to study the flow of Bitcoins in the


network.
■ User network can be developed to study the ownership and spending
patterns of users.
Privacy Attacks on Blockchain

Using txn patterns and info gathered off the network, an adversary can
attempt to deanonymize the users
by mapping their bitcoin addresses with their real-world identities making
it pseudo-anonymous.
Txn Network Analysis: example

Payment to a vendor whose addr is scrapped off internet

User address Vendor address


Txn Network Analysis: example

All input addresses belong to a same user as txn is generated from one
source.
Txn Network Analysis: example

Txn 1

Txn 2

All change addresses and Original Address belong to the same user.
Illegal Activity using Cryptocurrency

Digital coins provide anonymity to its user to some extent.


■ can be used for money-laundering.
■ can be used for illicit activities on deep web.
■ irreversible scam activities like tricking people into sending Bitcoins.
No central authority makes it hard to claim fraud and expect
reimbursement.
Wallet Theft Attack

■ Wallet is a file that contains credentials, i.e. public and private keys
for a blockchain address.
■ In some blockchains like Bitcoin, wallet file is stored unencrypted by
default.
■ Malware attacks on host computer can led to wallet theft.
■ If adversary steals the file, they can sign txns on user’s behalf,
spending their balance.
Bitcoin Scripting Language
■ Bitcoin transaction script language: Script
• Stack-based execution language
• Simple language with limited operations
• Designed to be limited in scope and executable on a range of
hardware, perhaps as simple as an embedded device.
• Requires minimal processing
• Limited in operations as compared to modern programming
languages.
Bitcoin Transaction

Input Outputs
Bitcoin Locking Script
● Locking script is a spending condition placed on a Bitcoin transaction
output.
○ Specifies the conditions that must be met to spend the output in
the future.
○ Also called scriptPubKey, as it usually contains a public key or
bitcoin address (public key hash).

Locking script for Output 1: Locking script for Output 2:


Bitcoin Unlocking Script
● Unlocking script is a script that:
○ Satisfies the conditions placed on an output by a locking script.
○ Allows the output to be spent.
○ Part of every transaction input.
○ Mostly contains a digital signature produced by the user’s wallet
using its private key.
○ Also called scriptSig as it usually contained a digital signature.
Bitcoin Unlocking Script

Locking script on the input applied on


previous transaction when the input
UTXO was created.

Unlocking script on the input applied in


this transaction to spend it: <Signature>
<Public Key>
Script Example
● Script consists of two components:
○ Data - ex., public keys and signatures.
○ Opcodes - Simple functions that operate on the data.

Unlocking script Locking script


Executing a Script

● Data is always pushed onto the stack.


Executing a Script

● Opcodes - can pop elements off the stack, do mentioned operation on


them, then optionally “push” new elements on to the stack.
Executing a Script

● A script is valid if the top and only element left on the stack is a 1 (or
greater).

Unlocking Locking
Script Script
Executing a Script

The script is invalid if:

1. The final stack is empty.


2. The top element is on the stack is 0.
3. There is more than one element left on the stack at the end of
execution.
4. The script exits prematurely.
Bitcoin Standard Transactions

● P2PK (Pay to Public Key)


● P2PKH (Pay to Public Key Hash)
● P2MS (Pay to MultiSig)
● P2SH (Pay to Script Hash)
Segwit Txns:
● P2WPKH (Pay to Witness Public Key Hash)
● P2WSH (Pay to Witness Script Hash)
● P2TR (Pay to Taproot)
P2PK Script

● P2PK (Pay To Pubkey) is a script pattern that locks an output to


a public key.
● It is a simpler version of more commonly used P2PKH locking script.
Working of P2PK Script
P2PKH Script

● P2PKH is the default script used by wallets when you want to send
someone bitcoins.
● Most common scripts used in transactions.
Working of P2PKH Script
● The P2PKH script pattern contains a hashed public key surrounded by
following shown opcodes.

● To solve this script,


the owner of hashed
public key needs to
provide the original
public key, along with
valid signature.
Multisignature Script
■ Sets a condition where N public keys are recorded in the script and at least M
of those must provide signatures to unlock the funds.
■ Also known as an M-of-N scheme, where N is the total number of keys and
M is the threshold of signatures required for validation.
■ General form of a locking script setting an M-of-N multisignature condition
is:
M <Public Key 1> <Public Key 2> ... <Public Key N> N CHECKMULTISIG
Issues with Multisignature Script
● Longer locking scripts
● Ex.
2 <Mohammed's Public Key> <Partner1 Public Key> <Partner2 Public Key> <Partner3 Public Key> <Attorney Public Key> 5
CHECKMULTISIG

2 04C16B8698A9ABF84250A7C3EA7EEDEF9897D1C8C6ADF47F06CF73370D74DCCA01CDCA79DCC5C395
D7EEC6984D83F1F50C900A24DD47F569FD4193AF5DE762C58704A2192968D8655D6A935BEAF2CA23
E3FB87A3495E7AF308EDF08DAC3C1FCBFC2C75B4B0F4D0B1B70CD2423657738C0C2B1D5CE65C97D7
8D0E34224858008E8B49047E63248B75DB7379BE9CDA8CE5751D16485F431E46117B9D0C1837C9D5
737812F393DA7D4420D7E1A9162F0279CFC10F1E8E8F3020DECDBC3C0DD389D99779650421D65CBD
7149B255382ED7F78E946580657EE6FDA162A187543A9D85BAAA93A4AB3A8F044DADA618D0872274
40645ABE8A35DA8C5B73997AD343BE5C2AFD94A5043752580AFA1ECED3C68D446BCAB69AC0BA7DF5
0D56231BE0AABF1FDEEC78A6A45E394BA29A1EDF518C022DD618DA774D207D137AAB59E0B000EB7E
D238F4D800 5 CHECKMULTISIG
P2SH Script

● Solves issues of a multisig script


● In P2SH payments, the complex locking script is replaced with its digital
fingerprint, a cryptographic hash.
● When a transaction attempting to spend the UTXO is presented later, it must
contain the script that matches the hash, in addition to the unlocking script.
P2SH Script

● P2SH means “pay to a script matching this hash, a script that will be
presented later when this output is spent.”
● Locking script that is replaced by a hash is referred to as the redeem
script because it is presented to the system at redemption time rather
than as a locking script.
Working of P2SH Script
Advantages of P2SH Script
● Complex scripts replaced by shorter fingerprints in the transaction output,
making the transaction smaller.
● P2SH shifts the burden of constructing the script to the recipient, not the
sender.
● P2SH shifts the burden in data storage for the long script from the output
(which is in the UTXO set) to the input (stored on the blockchain).
● P2SH shifts the burden in data storage for the long script from the present
time (payment) to a future time (when it is spent).
● P2SH shifts the transaction fee cost of a long script from the sender to the
recipient,who has to include the long redeem script to spend it.
Hash Lock Script
■ A txn output is locked until a specified data is revealed
■ It can be used in applications like atomic swaps where both parties cannot
swap their funds until a secret used to lock the txn, is exchanged between
them.
■ Output Script:
– OP_HASH160 <Hash value> OP_EQUALVERIFY OP_DUP OP_hash160 <hash of
public key> OP_EQUALVERIFY OP_CHECKSIG
■ Input Script:
– Sender has to reveal the secret such that its hash results in the hash mentioned in the
output lock.
– <Size of signature> <Signature> <Public key> <secret>
Time Lock Script
■ A txn output is locked until a specified time or a block height.
■ It can be used in applications like investing bitcoins until a point in time.
■ Output Script:
– Script to lock bitcoins until specified expiry time. After that the funds can be spent by
signing the output with the specified public key in the script
– <expiry time> OP_CHECKLOCKTIMEVERIFY OP_DROP OP_DUP OP_HASH160
<pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
■ Input Script:
– Spent only after waiting for the expiry time to be reached.
– <Signature> <Public key>
Pay to Taproot (P2TR)
■ Taproot is a major Bitcoin upgrade rolled out in Aug, 2021.
■ Introduction of P2TR txns and Schnorr digital signatures in Bitcoin.
■ P2TR allows script path or key path spending of a txn output.
■ If a P2TR output is unlocked using key spending path, the possibility of
spending through a script path is not even revealed.
■ In case if a particular script path is used to unlock the output, the other
scripts are not revealed.
■ Saves space and transaction fee on the unused conditions to be specified by
the spending party in txn.
■ Increases the privacy of a contract between parties.
Features of P2TR
■ Indistinguishable locking and unlocking for spending bitcoins using key or
script path.
■ Alternative signature scheme- Schnorr signatures.
– Allows aggregation of public keys for multisignature txn, making it
appear as a single party signature on-chain.
■ Specifying txn spending paths in the form of a data structure called
Merkelized Abstract Syntax Tree(MAST).
■ Batch verification of multiple signatures. It saves time in individual
verification of each signature.
P2TR Transaction
■ Output locking script:
<Witness version 1> <32 Bytes Taproot Output Key>
■ Taproot output key: Q = P + hash(P || M) * G
Here,
P = Taproot internal key corresponding to key path spending. It can be the
public key whose signature is required for spending the output. In case of a
multisig txn, it can an aggregate public key.
M = Root of merkle tree whose leaves represent possible ways to unlock the
output.
G = Generator point of elliptic curve.
P2TR Transaction
■ Script Tree:
– All possible script paths for locking an output are arranged in a
merkle tree.
– Scripts are arranged as merkle tree leaf nodes.
P2TR Transaction
■ Key path spending, unlocking script:
<signature corresponding to taproot internal key, P>
■ Script path spending, unlocking script consists of following elements:
– Taproot internal key
– Script which is used to spend the output
– Inputs for successful execution of the script
– Merkle path from the unlocking script to the merkle tree root -
This confirms the presence of script in the tree
Blockchain 2.0
Blockchain applications also called as dApps (Decentralized
Applications) other than cryptocurrencies:
■ Supply chain management
■ Land Registry
■ Healthcare
and many more...
Blockchain in Healthcare
■ Blockchain allows for secure recording and sharing of medical
information in a ledger to:
– Verify integrity of patient health information.
– Perform unchangeable medical audits.
– Prove the integrity of clinical research results.
– Ensure data safety.
– Detect fraudulent drug dealers.
Blockchain 2.0: Smart Contract

Code that facilitates, verifies, or enforces the negotiation or execution of a


digital contract.
A trusted entity must run this code.
Blockchain 2.0: Smart Contract

■ Ethereum is one decentralized platform designed to run smart


contracts.
■ Smart contracts in Ethereum react to external world when poked by
Transactions.
■ written in languages: Solidity, Vyper
Blockchain 2.0: Solidity

Documentation: https://solidity.readthedocs.io/en/v0.7.0/

Editors:
Remix- https://remix.ethereum.org/
Visual Studio Code- extensions available for solidity
Ethereum Development Framework
Ethereum Development Framework

Set of APIs, SDKs and tools to Ethereum development


develop web3 apps. environment for
professionals.
Ethereum Development Framework
Ethereum Networks

■ Main network: Primary, public Ethereum production blockchain.


■ Test network: Used by protocol developers or smart contract
developers for simulations in a production-like-environment before
deployment on mainnet.
– Sepolia- recommended default testnet for application
development.
– Goerli- testnet for validating and staking.
Blockchain 2.0:
Solidity

Coin.sol
A simple smart contract to
mint and send coins of a
cryptocurrency.
Attacks in Smart Contracts

If the code written in smart contract is not secure, it may lead to some
attacks:
■ Reentrancy Attacks:
– recursive calls to call.value() of the smart contract.
– happened in famous DAO hack in Ethereum in 2016.
– DAO is decentralized autonomous organization intended to act as
an automated company.
Attacks in Smart Contracts
■ Reentrancy Attacks:
– Less than 3 months after its launch, DAO was hacked and $60M of
ether was stolen.
Attacks in Smart Contracts
Contract code with DAO vulnerability: Contract code exploiting DAO vulnerability:
withdrawBalance() calls itself again and again:

withdrawBalance() function called multiple times to


empty the account as the account balance is reduced
after this call.
Attacks in Smart Contracts

If the code written in smart contract is not secure, it may lead to some
attacks:
■ Overflow Attack: Ethereum smart contracts don't support values
greater than 2256. Buffer overflow attacks might be created by having a
really large value.
■ Forcible Balance Transfer: If the contract is vulnerable, forcible
balance transfer can be done and limits can be exceeded.
■ DoS Attacks: Smart contract can be written with malicious intent
causing denial of service.
Ethereum Token Standards

■ Tokens are digital representation of a real world/virtual asset


■ They are created on top of another pre-existing blockchain platform.
■ They can represent any asset which is tradeable.
– Fungible token: divisible, non-unique asset.
– Non-fungible token (NFT): unique, non-divisible asset. one-of-a-
kind.
■ Tokens are governed by a smart contract.
Ethereum Token Standards

■ ERC-20: Standard interface for fungible tokens.


– ex. Voting tokens, Stablecoins, Reward point tokens
■ ERC-721: Standard interface for non-fungible tokens.
– ex. Deed for artwork or music, title of ownership of a property,
flight ticket
■ ERC-1155: Interface to create both fungible and non-fungible tokens.
– Bundles creation of tokens, saving costs.
Ethereum Accounts

1. Externally-Owned Account (EOA)


■ represents individual user
■ identified by 20-byte address
■ holds an amount of ether as its state
1. Contract Account
■ holds bytecode of a deployed smart contract.
■ identified by 20-byte contract address
■ holds an amount of ether as its state
Ethereum Txn

Each txn in Ethereum requires some “gas”.


These are the ethers charged as txn fees.

Types of Txns:
■ Funds transfer between EOA.
■ Deploy contract on Ethereum blockchain.
■ Execute a function on a contract account.
Ethereum Txn
From: Txn sender who
initiates this txn.

Gas: Max no. of


computational steps allowed
in a txn.
To avoid infinite loops.

Gas Price: Fee sender


pays per computation.
In Wei

Input: Signature and


encoded arguments of
functions included in smart
contract.

To: Recipient of txn.


0X0 means new
contract is deployed.
State Change in Ethereum
Consider it as a world computer with state changing when a txn occurs:

State is the
information Change in state of Ethereum when txn is
about each made.
Ethereum
account.

Eth Account 1

Eth Account 2

Eth Account 3

Eth Account 4
Ethereum Txn
Client interacts with
DApp deployed on Ethereum application on blockchain.
blockchain. Cost Ethers.
Cost Ethers. A txn results in change of
Ethereum state.
Validated by miners.
Permissioned Blockchain
■ Permissioned blockchain controls:
– which user can join the network
– which user can participate in consensus and validate txns and
blocks
■ Such blockchains are preferred by the centralized organizations.
■ Users cannot:
– easily join the network
– view the history and issue txns
Hyperledger
■ Hyperledger is an open
source, enterprise-grade suite
of tools and frameworks for
a permissioned blockchain
solution development.
■ Hyperledger Fabric:
Framework for developing
blockchain apps with a
modular architecture.
Hyperledger

■ Hyperledger Aries: Used for developing digital credential solutions.


■ Hyperledger Indy: Tools and libraries for creating and using
independent digital identities.
■ Hyperledger Cacti: Blockchain integration tool for securely
integrating different blockchains.
■ Hyperledger Besu: Java-based Ethereum client.
Privacy Preserving Blockchain
Monero
Pseudo-anonymity: Lack of privacy in Bitcoin.
Monero, another cryptocurrency which enhances user privacy using:
■ Stealth, single-use addresses
■ Ring signatures
■ Confidential txns
Monero- Stealth Addresses
Provides Unlinkability:

Linkability:
Ability to link all addresses
held by a single person by
analyzing txns.

Both output addresses


belong to Charlie, but
unlinkable to network.

Use of different address for


Charlie in each txn.
Monero- Stealth Addresses

■ A different destination address for each output is derived from one


Monero address of the user.
■ Only the owner of that Monero address knows that output is for him
(using View Keys).
■ Nobody can tell these outputs are going to the same person.
Monero- Ring Signatures
Provides Untraceability:
Traceability:
Ability to trace funds
held by same person
by analyzing txn
data.

Monero provides
untraceability by
using Ring
signatures.
Monero- Ring Signatures
Inputs in a txn-
■ Atleast one real participant and other mixins.
■ Mixins are outputs from some previous txns.
■ Ring signature created to sign the txn.

For a verifier, no way to tell who is the real participant, all appears valid
Monero- Ring Signatures

■ Find some outputs in the blockchain with the same amount X as the
output A you want to spend.
■ These other outputs are called “mixins”. All mixins of same value.
■ You can use 4-25 mixins in a txn.
■ You sign this txn using a ring signature.
Monero- Ring Signatures

■ It is easy to verify that at least one user from inputs have signed this
ring txn.
■ Not easy to find which user has signed the txn.
Monero- Ring Signatures
All inputs: mixins and real input are of same value.

Mixin 1

Real Input

Mixin 2

Mixin 3

Verifier cannot know that Output O is the real spender in


this txn.

You might also like