0% found this document useful (0 votes)
36 views476 pages

Block Chain DLT

Uploaded by

IBARA DONIAMA
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)
36 views476 pages

Block Chain DLT

Uploaded by

IBARA DONIAMA
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/ 476

Blockchain & Distributed ledgers

Develop the ability to think critically about cybersecurity


Why study Blockchains?
Why study Blockchains?
● Provide good foundations for exploring the security of
information systems in general.
● Highlight the importance of decentralisation, a property of
increasing importance in the design of modern information
systems.
● Facilitate a solid understanding of many security critical
components, incl.
○ Key management.
○ Software security.
○ Privacy preserving technologies.
○ Public Key Infrastructure.
● They have an increasing impact on various aspects of societal
organisation.
● It’s fun!
What is a blockchain ?
What is a blockchain ?

● A blockchain is a distributed database that satisfies a unique


set of safety and liveness properties.
● Distributed ledgers use blockchain protocol as one means of
implementation.
● To understand it, we can focus to its first (and so far most
successful) application.
Case study: Money
Properties of Money

● A medium of exchange: Can be used as medium for the


exchange of goods - no bartering
● A unit of account: Can be used for pricing of all goods
and services, for accounting purposes and debt recording
● A store of value: Storing and retrieving it at a point in the
future maintains its value.
Money 1.0: Using a trusted object
Analysis of Money 1.0
● A medium of exchange: Medium
○ Ok to face to face transactions
● A unit of account: Mediocre
○ Fungible, but not divisible well
○ Typically forgeable
● A store of value: Bad
○ Some objects may deteriorate.
○ May have unknown hidden quantities
Money 2.0: Using a trusted entity
Analysis of Money 2.0

● A medium of exchange: good


○ For transactions within the domain of the trusted entity
● A unit of account: great
○ Fungible & divisible
● A store of value: Mediocre
○ Tied to the availability & reputation of the issuing entity
Money 3.0: Using cryptocurrencies
The never-ending book parable
A book of transactions

● Anyone can be a scribe and produce a page.


● New pages are produced indefinitely as long as
scribes are interested in doing so.
● Each new page requires some effort to produce
Importance of consensus

● If multiple conflicting books exist, which is the “right one” ?


Choosing the correct book ?
Assembling the current book
● Each page refers only to the previous one
● Current assembled by stringing together the longest
sequence of pages
Rules of extending the book
Effort is needed to produce a page
The benefits of randomness
Being a scribe

● Anyone can be a scribe for the book.


● As long as one has a set of dice.
● The more dice one has, the higher the likelihood to produce
the winning combination to make a page.
Using the book
Parable & Reality
Analysis of Money 3.0

● A medium of exchange: improving


○ assuming internet connectivity / adoption
● A unit of account: good
○ Fungible* & divisible
● A store of value: good
○ No trusted parties
○ No natural deterioration
Word of caution
From Money to Smart Contracts

● Since we have created the book, why stop at recording monetary


transactions?
● We can encode in the book’s pages arbitrary relations between
persons.
● Furthermore, scribes, can perform tasks such as verifying that
stakeholders comply to contractual obligations … and take action if
they do not.
Smart contract
Questions to Consider
● How are pages created? Since the book is empty at the
beginning, where do the money come from?
● How is it possible to sign something digitally?
● How does a page properly refer to the previous page?
● How are pages created? Since the book is empty at the
beginning, where do the money come from? - Proof-of-Work
● How is it possible to sign something digitally? - Digital signatures
● How does a page properly refer to the previous page? - Hash
functions
Hash Functions

● An algorithm that produces a fingerprint of a file.


● what are the required properties (traditionally): a. Efficiency b. A
good spread for various input distributions.
● What are Security/Cryptographic considerations
Collision resistance
Birthday paradox

● How many people should be in a room so that the probability


that two of them share a birthday becomes larger than 50% ?
Paradox explained
What do we learn about collision
finding?

Describe an algorithm that finds collisions taking advantage of the


Birthday paradox.
Pre-image attack
One-way functions
Does one-way functions exist?
Hash function instantiations

● Retired. MD5, SHA1.


● Current. SHA2, SHA3, available for 224,256,384,512 bits
fingerprints.
● Bitcoin. Uses SHA2 with 256 bits output, SHA-256.
Digital Signatures

● Can be produced by one specified entity.


● Can be verified by anyone (that is suitably “equipped" and
“initialised”).
● Cannot be forged on a new message even if multiple signatures
have been transmitted.
Digital Signatures
Digital Signature Security
Constructing Digital Signatures

● Major challenge:
● what prevents the adversary from learning how to sign
messages by analyzing the verification-key?
● Exercise: construct a digital signature based on a hash-
function that is one-time secure (i.e., it is secure for
signing only a single message)
Digital Signature Implementations

● Based on the RSA (Rivest Shamir Adleman), one way trapdoor


function (with hardness that relates to the factoring problem).
● The RSA algorithm
● Based on the discrete-logarithm problem.
● the DSA algorithm
● Bitcoin. Uses ECDSA, a DSA variant over elliptic curve groups.
Proof of Work
Proof-of-Work Algorithms

Hashcash (as in previous slide)


Memory hardness
ASIC resistance (ASIC = application specific integrated circuit).
A number of algorithms proposed: scrypt, argon, progpow
Cryptocurrencies from a user’s
perspective
Bitcoin
What is bitcoin ?
Bitcoin /ˈbɪtkɔɪn/

● First decentralized digital currency.


● Digital coins you can send through the Internet.
Advantages
Person to person
Fees determined by free market
Available to the whole world
You own your account
No prerequisites or arbitrary limits
Trust to third party is not a requirement
Open source: Anyone can review the
code
Open source: Anyone can review the
code
Great! But… how can I use it ?
Exchange: Buy or sell bitcoin for various
currencies
Digital wallet: Bitcoins are kept in your
computer or mobile device
Transactions: Bob wants to buy a coffee
from Alice
Transactions: Bob pays Alice by sending the
proper amount to Alice’s bitcoin address
Exchanges
Exchanges

● Bittrex
● Kraken
● Coinbase
● CoinMama
● SpectroCoin
● BitPanda
● LocalBitcoins (Buy / Sell from people near you)
● Bisq (Decentralized)
● Friends!!
Order book
Coinmarketcap
Addresses
Addresses

● Like an email address.


● You send bitcoins to a person by sending bitcoins to one of
their addresses.
● You can have as many addresses as you want.
● No need to be online to create an address.
● Pseudonymous: A unique address should be used for each
transaction.
● Most wallets do it automatically.
Addresses
Wallets
Desktop Wallet - Exodus
Desktop Bitcoin Wallet - Electrum (open source)
More Bitcoin wallets … (mobile)
Mobile wallet - Android
Hardware wallets
Explorers
Explorers
● An online blockchain browser.
● Displays the contents of individual blocks and transactions
● Displays the transaction histories and balances of addresses.
● Quick way to see if your transactions are confirmed.
● Bitcoin:
○ https://www.blockchain.com/explorer (Mainnet)
○ https://testnet.blockexplorer.com/ (Testnet)
● Ethereum:
○ https://etherscan.io/ (Mainnet)
○ https://ropsten.etherscan.io/ (Testnet)
○ https://rinkeby.etherscan.io/ (Testnet)
Transactions
Transactions
Blocks
Blocks
Blocks
Development
Faucet
Authenticated Data Structures

● Like regular data structures, but cryptographically authenticated


● Allows a verifier to store, retrieve and operate on data with an
untrusted prover
The file storage problem
The file storage problem

● Client wants to store a file on a server


● File has a name F and data D
● Clients wants to retrieve file F later
File storage: Basic protocol

● Client sends file F with data D to server


● Server stores (F, D)
● Client deletes D
● Client requests F from server
● Server returns D
● Client has recovered D
File storage: Protocol against adversaries

● What if server is adversarial and returns D’ != D?

Trivial solution:
● Client does not delete D
● When server returns D’, client compares D and D’
...what if client doesn’t have enough memory to store D for a long
time?
File storage: Hash-based protocol

● Client sends file F with data D to server


● Server stores (F, D)
● Client stores H(D), deletes D
● Client requests F from server
● Server returns D’
● Client compares H(D’) = H(D)
File storage: File chunks

● What if client wants to retrieve the 200,019th byte of the file?


● Must download the whole file…
● Merkle trees to the rescue!
Merkle Tree

● An authenticated binary tree


● Split file into chunks of, say, 1KB
Merkle Tree

● Hash each chunk using a cryptographic hash function (SHA256)


● Convention: Arrows show direction of hash function application
Merkle Tree

● Combine them by two to create a binary tree


● Each node stores the hash of the concat of its children
Merkle Tree
Proofs-of-inclusion

● Client creates Merkle Tree root MTR from initial file data D
● Client sends file data D to server
● Client deletes data D, but stores MTR (32 bytes)
● Client requests chunk x from server
● Server returns chunk x and short proof-of-inclusion π
● Client checks that chunk x is included in MTR using proof π
Merkle tree: proof of inclusion
Merkle tree: proof of inclusion
Merkle tree: proof of inclusion
Merkle tree: proof of inclusion
Merkle tree: proof of inclusion

● Prover sends chunk


● Prover sends siblings along path connecting leaf to MTR
● Verifier computes hashes along the path connecting leaf to MTR
● Verifier checks that computed root = MTR
● How big is proof-of-inclusion?
Proof-of-inclusion succinctness
Merkle Tree proof-of-inclusion security

● If adversary can present proof-of-inclusion for incorrect leaf, then


we can break the hash function
● Proof is by computational reduction (whiteboard)
Merkle Tree protocol
Merkle Tree protocol
Merkle Tree protocol
Proof-of-inclusion security
Threat modelling with bad events
● When defining a security property precisely, specify what bad
event we are trying to avoid
● In this case, the construction of a proof about a non-existent
element
● It is important to allow the adversary to choose which Merkle
Tree to attack
● It is possible that the vast majority of trees are not attackable…
● Hence, we define a game where the adversary chooses a data
set D to construct the tree from, an element x, and a proof of π
● The adversary can construct these arbitrarily. π does not need to
be produced out of a tree!
The Merkle Tree forgery game
The Merkle Tree security
The theorem: Assumption → Desirable
Proof strategy: Contraposition
Proof strategy: Contraposition
Proof strategy: Computational reduction
Situation if adversary A wins
Situation if adversary A wins
Situation if adversary A wins
Situation if adversary A wins
Proof conclusion
Proof of security is nuanced

Don’t roll your own crypto. Use standard code by others


which you know is secure.
Merkle tree applications

● Bitcoin uses Merkle trees to store transaction


● BitTorrent uses Merkle Tree to exchange files
● Ethereum uses Merkle–Patricia tries for storage and
transactions
Storing sets instead of lists

● Merkle Trees can be used to store sets of keys instead of lists


● Verifier asks prover to store a set of keys
● Verifier deletes set
● Verifier later asks prover if key belongs to set ● Prover provides
proof-of-inclusion or proof-of-non-inclusion
● Prover can be adversarial
Merkle trees for set storage

● Verifier sorts set elements


● Creates MTR on sorted set
● Proof-of-inclusion as before
● Proof-of-non-inclusion for x Show proof-of-inclusion for previous
H< and next H> element in set
● Verifier checks that H<, H> proofs-of-inclusion are correct
● Verifier checks that H<, H> are adjacent in tree
● Verifier checks that H< < x and H> > x
● The two proofs-of-inclusion can be compressed into one
Merkle tree: proof of inclusion
Merkle tree: proof of inclusion
Tries

● Called also radix tree or prefix tree


● Search tree: ordered tree data structure
● Used to store a set or an associative array (key/value store)
● Keys usually are strings
Tries

● Supports two operations: add and query


● add adds a string to the set
● query checks if a string is in the set (true/false)
● Initialize: Start with empty root
Tries: add(string)

● Start at root
● Split string into characters
● For every character, follow an edge labelled by that character
● If edge does not exist, create it
● Mark the node you arrive at
Tries: query(string)

● Start at root
● Split string into characters
● For every character, follow an edge labelled by that character
● If edge does not exist, return false
● When you arrive at a node and your string is consumed,
check if node is marked
● If it is marked, return yes
● Otherwise, return no
Tries: example

{ do: 0, dog: 1, dax: 2, dogu: 3, dodo: 4, house: 5, houses: 6 }


Tries
Patricia (or radix) trie

● Space-optimized trie
● An isolated path (with nodes which are only children) with
unmarked nodes is merged into one edge
● The label of the merged edge is the concatenation of the
merged symbols
Tries / Patricia tries as key/value store

● Marking does not need to be yes/no


● Can contain arbitrary value
● This allows us to map keys to values
● add(key, value)
● query(key) → value
Patricia trie
Merkle Patricia trie

● An authenticated Patricia Trie


● First implemented in Ethereum
● Allows proof-of-inclusion (of key, with particular value)
● Allows proof-of-non-inclusion (by showing key does not exist in
trie)
Merkle Patricia trie

● Split nodes into three types:


○ Leaf: Stores edge string leading to it, and value
○ Extension: Stores string of a single edge, pointer to next node,
and value if node marked
○ Branch: Stores one pointer to another node per alphabet
symbol, and value if node marked
● We encode keys as hex, so alphabet size is 16
● We encode all child edges in every node with some encoding
(e.g. JSON)
● Pointers are by hash application
● Arguments for correctness and security are same as for Merkle
Trees
Merkle Patricia trie
Merkle patricia trie: node
Merkle patricia trie: example

{ 'cab8': 'dog', 'cabe': 'cat', '39': 'chicken', '395': 'duck', '56f0': 'horse' }
Merkle patricia trie: example
Merkle patricia trie: example
Proof-of-work in blocks

● Blocks must satisfy proof-of-work equation


H(ctr || x || s) <= T

● for some constant T


● ctr is the nonce used to solve proof-of-work
● The value H(ctr || x || s) is known as the blockid
Blockchain

● Each block references a previous block


● This reference is by hash to its previous block, similar to Merkle
Trees
● This linked list is called the blockchain
● Convention: Arrows show authenticated inclusion

● Blocks use the s value to point to the previous block by hash


Blockchain

● The first block of a blockchain is called the Genesis Block


Notation conventions
● We use the symbol C to denote a blockchain
● C is a sequence of blocks
● We use C[i] to denote the ith block (0-based)
● C[0] denotes genesis
● We use C[-i] to denote the ith block from the end
● Chain property: For each i > 0: C[i].s = H(C[i - 1])
Notation conventions

● Range notation: C[i:j] denotes a subsequence from i (inclusive) to j


(exclusive)
● Similarly C[-i:j], C[i:-j], C[-i:-j]
Notation conventions
● Range notation: C[i:], C[-i:] denotes chain from i (or -i)
inclusive to end inclusive C[:i], C[-i:] denotes chain from
beginning inclusive to i (or -i) exclusive
The bitcoin network
● All bitcoin nodes connect to a common p2p network
● Each node runs the code of bitcoin
● A node can run on a phone, computer, etc.
● Open source code
● Each node connects to its neighbours
● They continuously exchange financial data
● Each node can freely enter the network -- no permission
needed! A “permissionless network”.
● The adversarial assumption: There is no trust on the network!
Each neighbour can lie.
Peer discovery

● Each node stores a list of peers (by IP address)


● When Alice connects to Bob, Bob sends Alice his own known peers
● That way, Alice can learn about new peers
Bootstrapping the p2p network

● Peer-to-peer nodes come “preinstalled” with some peers by IP


/ host
● When running a node, you can specify extra “known peers”
The gossip protocol

● When a node Alice generates some new data...


● Alice broadcasts data to its peers
● Each peer broadcasts this data to its peers
● If a peer has seen this data before, it ignores it
● If this data is new, it broadcasts it to its peers
● That way, the data spreads like an epidemic, until the whole
network learns it
● This process is called diffuse
Financial data

● Financial data is encoded in the form of transactions


● Every transaction is broadcast on the network to everyone using
the gossip protocol
● Financial data on cryptocurrencies are common knowledge
among all participants
Transactions on blockchain.info
Eclipse attacks

● Isolate the some honest nodes in the network effectively causing


a “net split” in two partitions A and B
● If peers in A and peers in B are disjoint and don’t know about
each other, the networks will remain isolated ○ More recent attack:
Erebus
● The connectivity assumption: There is a path between two nodes
on the network If a node broadcasts a message, every other node
will learn it
Contracts

“A contract is a legally binding agreement which recognises and


governs the rights and duties of the parties to the agreement.” -
Wikipedia
A mutually beneficial relationship between equals (Jean-Jacques
Rousseau)
What is a smart contract?

● Computer programs
● Contract code is executed by all full nodes
● The outcome of a smart contract is the same for everyone
● Context: Internal storage, transaction context, most recent blocks
● The code of a smart contract cannot change
Bitcoin programs
● Transaction: a transfer of value in the Bitcoin network
● Each transaction consists of the following main fields:
○ input: a transaction output from which it spends bitcoins:
i. previous transaction address
ii. Index
iii. ScriptSig
○ output: instructions for spending the sent bitcoins:
i. value: amount of bitcoins to send
ii. ScriptPubKey: instructions on how to spend the sent
bitcoins
● To validate a transaction:
○ concatenate ScriptSig of the current transaction with
ScriptPubKey of the referenced transaction
○ check if it successfully compiles with no errors
Bitcoin Script
● Stack-based
● Data in the script is enclosed in <>: <sig>, <pubKey>, etc
● Opcodes: commands or functions
○ Arithmetic, e.g. OP_ABS, OP_ADD
○ Stack, e.g. OP_DROP, OP_SWAP
○ Flow control, e.g. OP_IF, OP_ELSE
○ Bitwise logic, e.g. OP_EQUAL, OP_EQUALVERIFY
○ Hashing, e.g. OP_SHA1, OP_SHA256
○ (Multiple) Signature Verification, e.g. OP_CHECKSIG,
OP_CHECKMULTISIG
○ Locktime, e.g. OP_CHECKLOCKTIMEVERIFY,
OP_CHECKSEQUENCEVERIFY
Bitcoin Script example
Bitcoin’s scripting language limitations

● Lack of Turing-completeness: No loops


● Lack of state: Cannot keep internal state.
● Value-blindness: Cannot denominate the amount being sent
● Blockchain-blindness: Cannot access block header values such as
nonce, timestamp and previous hash block.
● Fees depend on transaction’s length.
Extending Bitcoin functionality: add new
opcodes
● Building a protocol on top of Bitcoin:
○ Pros:
■ Take advantage of the underlying network and mining power.
■ Very low development cost
○ Cons:
■ No flexibility.
■ No SPV clients.
● Build an independent network:
○ Pros:
■ Easy to add and extend new opcodes.
■ Flexibility.
○ Cons:
■ Need to attract miners to sustain the network.
■ Difficult to implement.
Alternative blockchain applications

● Namecoin:
○ Bitcoin fork: Currency NMC
○ Decentralized name registration database: DNS, identities etc
● Colored coins:
○ On top of Bitcoin
○ Allows people to create their own digital currencies
● OmniLayer (formerly Mastercoin)
○ On top of Bitcoin
○ Distributed exchange, smart property, distributed e-commerce, etc
● OpenBazaar
○ On top of Bitcoin
○ Decentralized marketplace
Ethereum
Same principles as Bitcoin

● A peer-to-peer network: connects the participants


● A consensus algorithm: Proof of Work (will move to PoS)
● A digital currency: ether
● A global ledger: the blockchain
○ Addresses: key pair
○ Wallets
○ Transactions: digital signatures
○ Blocks
Ethereum: A universal Replicated State
Machine
● Transaction-based deterministic state machine
○ Global singleton state
○ A virtual machine that applies changes to global state
● A global decentralized computing infrastructure
● Anyone can create their own state transition functions
● Stack-based bytecode language
● Turing-completeness
● Smart contracts
● Decentralized applications
Ethereum accounts

● Global state of Ethereum: accounts


● They interact to each other through transactions (messages)
● A state associated with it and a 20-byte address (160-bit
identifier)
Ethereum accounts
Ethereum accounts
UTXO vs Accounts

● UTXOs pros:
○ Higher degree of privacy
○ Scalability (parallelism, sharding)
● Accounts pros:
○ Space saving
○ Better fungibility
○ Simplicity
○ Efficiency
Two types of accounts

● Personal accounts (what we’ve seen)


● Contract accounts
Ethereum contract account
Ethereum accounts
Ethereum transaction
Ethereum transaction
Ethereum transaction
Ethereum transaction
Ethereum transaction
a transaction about a contract
Smart contract lifecycle
Τransaction for contract creation
Τransaction for contract interaction
Contract method call

● When contract account is activated:


a.Contract code runs
b. It can read / write to internal storage
c. It can send other transactions or call other contracts
● Can’t initiate new transactions on their own
● Can only fire transactions in response to other transactions
received
Messages

● Like a transaction except it is produced by a contract


● Virtual objects
● Exist only in the Ethereum execution environment
● A message leads to the recipient account running its code
● Contracts can have relationships with other contracts
Transactions & messages
Types of transactions
a transaction for contract destruction
Ethereum Virtual Machine

● Series of bytecode instructions (EVM code)


● Each bytecode represents an operation (opcode)
● A quasi Turing complete machine
● Stack-based architecture (1024-depth)
● 32-byte words (256-bit words)
● Crypto primitives
EVM: contract execution

● Three types of storage:


○ Stack
○ Memory (expandable byte array)
○ Storage (key/value store)
● All memory is zero-initialized
● Access: value, sender, data, gas limit and block header
data (depth, timestamp, miner, hash)
Ethereum block
Ethereum block
Ethereum Mining

● Similar to Bitcoin
● Blocks contain: transaction list and most recent state
● Block time: ~12 - 15 seconds
● Proof-of-work: Ethash (designed to be memory-hard)
● Casper: Future transition to proof-of-stake
● Winner of the block: 3 ETH
Ethereum Mining

● Uses a variant of GHOST (Greedy Heaviest Observed Subtree)


protocol to reward stale blocks
● The GHOST protocol rule picks the chain that has had the most
computation done upon it
● Planned hard forks:
○ Frontier, Homestead, and Byzantium (Metropolis phase 1)
○ Next one at 2019: Constantinople (Metropolis phase 2)
Ethereum fees: the phone booth model
Gas: a necessary evil

● Every node on the network:


○ evaluate all transactions
○ store all state
● Halting problem

● Every computation step has a fee


● Is paid in gas
● Gas is the unit used to measure computations
Ethereum transaction
Ethereum transaction
Gas Limit

● All unused gas is refunded at the end of a


transaction
● Out of gas transaction are not refundable
● Blocks have a gas limit
Gas Price

● Measured in gwei (1 × 10^9 Wei)


● Determines how quickly a transaction
will be mined
Transaction Fees
Storage in Ethereum
Computation steps

1. If gas_limit * gas_price > balance then halt


2. Deduct gas_limit * gas_price from balance
3. Set gas = gas_limit
4. Run code deducting from gas
5. After termination return remaining gas to balance
Out of gas exceptions

● State reverts to previous state


● gas_limit * gas_price is still deducted
from balance
Introduction to Solidity
Solidity

● A high level programming language for writing smart contracts on


Ethereum
● Compile code for the Ethereum Virtual Machine
● Syntax looks like JavaScript

● Contracts look like classes / objects


● Static Type (Most types can be cast, e.g bool(x))
● Most of the control structures from JavaScript are available in
Solidity except for switch
Solidity
Pragmas

The pragma keyword is used to enable certain compiler (version)


features or checks. Follows the same syntax used by npm.
Contract
Constructors
Solidity: Variables

● State variables:
○ Contract variables
○ Permanently stored in contract storage
○ Must declare at compilation time
● Local variables
○ Within a function: cannot be accessed outside
○ Complex types: at storage by default
○ Value types: in the stack
○ Function arguments: in memory by default
Types

● The type of each variable needs to be specified (Solidity is a


statically typed language)
● Two types: ○ Value types ○ Reference types
● “undefined” or “null” values does not exist in Solidity
● Variables without a value always have a default value (zero-
state) dependent on its type.
● Solidity follows the scoping rules of C99 (variables are visible
until the end of the smallest {}-block)
Value types
Types: booleans
Types: integers
Types: address
Types: fixed-size byte arrays
Types: Enum
Reference types
Types: arrays
Types: Struct
Types: Mappings
Visibility
Visibility

● public: Public functions can be called from other contracts,


internally and personal accounts. For public state variables an
automatic getter function is being created.
● external: External functions cannot be called internally. Variables
cannot be declared as external.
● Internal: Internal function and variables can be called only
internally. Contracts that inherit another contract can access the
parent’s internal variables and functions.
● private: Private functions and variables can be called only by the
contract in which they are defined and not in derived contract.
Warning: private variables are visible to all observers external to the
blockchain.
Data location
Data location: areas

● Every complex type (arrays, structs, mappings) have a data


location.
● Two types of location: storage and memory.
● As of Solidity version 5.0.0 you must always declare the data
location of
complex types inside functions’ body, arguments and returned
values.
Data location: areas

● Storage:
○ Persistent.
○ All state variables are saved to storage.
○ Function’s complex local values are saved to storage by
default. (Solidity versions >= 5.0.0 force you to declare the data
location).
● Memory: ○ Non-persistent.
○ Function’s arguments and returned values are stored to
memory by default. (Solidity versions >= 5.0.0 force you to declare
the data location for complex types).
Data location: assignment

● storage <-> memory: copy


● state variable <- state variable, storage and memory: copy
● memory <-> memory : reference
● local storage variable <- storage: reference
Fallback function
Fallback function
Solidity: Functions
Solidity: events

● EVM logging mechanism


● Register listeners to events
● Arguments are stored in the transaction log
● An alternative to store data cheaply
Solidity: events
Solidity: structs
Solidity: enum
Solidity: Inheritance

● Multiple inheritance
● One contract is created on the blockchain: codes concatenates
● The general inheritance system is very similar to Python’s
Solidity: Inheritance

● Use `is` keyword to extend a contract


● Derived contracts: access all non-private members, internal
functions and state variables
● Abstract contracts can be used as interfaces
● Functions can be overridden
● Interfaces: functions are not implemented
Solidity: Inheritance
Solidity: Modifiers
Solidity: units and globally available
variables

● Ether Units
○ A literal number can take a suffix of wei, finney, szabo or ether (2
ether == 2000 finney evaluates to true)
● Time Units
○ Suffixes like seconds, minutes, hours, days, weeks and years (1
hours == 60 minutes)
Solidity: units and globally available
variables

● Block and Transaction Properties


○ block.blockhash
○ block.coinbase
○ msg.data
○ msg.gas
○ Msg.value
○ msg.sender
○ now
○ tx.origin
Solidity: units and globally available
variables

● Error Handling
○ assert
○ require
○ revert
● Mathematical and Cryptographic Functions
○ addmod, mulmod
○ Keccak256 (SHA-3), sha256, ripemd160
Solidity: units and globally available
variables

● Address Related
○ <address>.balance
○ <address>.transfer
○ <address>.send
○ <address>.call, <address>.callcode, <address>.delegatecall
● Contract Related
○ this, selfdestruct
Send ether
Send ether
Interacting with other contracts
Interacting with other contracts
Interacting with other contracts
Security and fairness of Smart
Contracts
Known Attacks
DoS: Unbounded operation
DoS: Unbounded operation
DoS: Wallet Griefing
DoS: Wallet Griefing
Forcibly Sending Ether to a Contract

● Exploits
○ misuse of this.balance
○ Complicated (vulnerable) fallback function
● How can you send ether to a contract without firing contact’s
fallback function ?
○ selfdestruct(victim)
○ Contract’s address = hash(sender address, nonce)
○ Anyone can calculate a contract’s address before it is created
(contract addresses generation is deterministic) and send ether to
that address.
Reentrancy
Reentrancy
Reentrancy
Reentrancy
Reentrancy
Reentrancy
Reentrancy
Reentrancy
Re-entrancy in the wild: The DAO
The DAO Attack
Reentrancy: solutions
Checks-Effects-Interactions Pattern

1. Perform checks (e.g sender, value, arguments ect)


2. Update state
3. Interact with other contracts (external function calls or send
ether)
Integer Overflow and Underflow
Integer Overflow and Underflow
Integer Overflow and Underflow
Integer Overflow and Underflow
Integer Overflow and Underflow:
solutions
Delegate call
Delegate call
Delegate call
Delegate call
Use of tx.origin
Use of tx.origin
Use of tx.origin
Use of tx.origin
Pull over push

● Do not transfer ether to users (push) but let the users withdraw
(pull) their funds.
● Isolates each external call into its own transaction.
● Avoids multiple send() calls in a single transaction.
● Reduces problems with gas limits.
● Trade-off between security and user experience.
Pull over push: example
Keep fallback function simple
Front-Running
Front-Running: user
Front-Running: user
Front-Running: miner
Front-Running: example
Front-Running: example
Front-Running: example
Front-Running: example
Front-Running: example
Randomness
Randomness: sources (?)
Randomness: sources (?)
Randomness
Randomness: blockhash
Randomness: blockhash
Randomness: attack pattern
Randomness: intra-transaction
information leak
What about future blocks ?
Is the hash of a block in the future a
good source of randomness against a
malicious miner ?
Randomness: towards safer PRNG

● Commit - reveal schemes


● Example:
○ Casino and player commit each to a random value.
○ Casino and player reveal their random values.
○ Casino XORs the random values to a seed. The seed can be
combined with the hash of a future block.
● RANDAO (decentralized)
On-chain data is public

● Applications (games, auctions, etc) required data to be private up


until some point in time.
● Best strategy: commitment schemes
○ Commit phase: Submit the hash of the value.
○ Reveal phase: Submit the value.
● Be aware of front-running!
Gas Fairness
Gas Fairness
Consensus and Distributed Ledgers via the
Blockchain Data structure
● The Consensus Problem
○ Properties ○ Honest Majority Assumption
● Ledger Consensus
○ Consistency
○ Liveness / Censorship resilience
● Blockchain Properties
○ Blockchain Addressing Notation
■ C[i], C[-i], C[i:j], C[i:], C[j:]
○ Common Prefix
○ Chain Growth
○ Chain Quality
● “Racing attacks”
● Consensus and distributed ledger (what is the relation)
● Difficulty Adjustment
○ Show difficulty graph
● The Bahack attack
Motivation for the consensus layer, I

● A transaction history and/or state of the service needs to be


agreed by all servers.
● Servers may be operated by participants with diverging interests
in terms of the history of transactions and/or state of the service.
Motivation for the Consensus Layer, II
The consensus problem
Consensus : Problem Statement

● A number (say, t) of the participating entities can diverge from


the protocol.
● This has been called Byzantine behaviour in the literature.
● The properties of the protocol are defined in the presence of
this “malicious” coalition of parties that attempts to disrupt the
process for the “honest” parties.
Consensus Properties
Honest Majority is Necessary, I
Honest Majority is Necessary, II

● If the adversary corrupts A0, then output of honest parties


(that belong to A1) should be 1.
● If the adversary corrupts A1, then output of honest parties
(that belong to A0) should be 0.
● If the adversary corrupts no-one, then the output of all
parties should be equal.
Is Honest Majority Sufficient?

● Two important scenarios have been considered in the consensus


literature.
● Point to point channels. No setup.
● Point to point channels. With setup. The setup enables provides
a correlated private initialization string to each participant. It is
assumed to be honestly produced.
Setup and Network

We know consensus can be achieved assuming the above bound


on adversarial parties.
The typical setup and network configuration in classical consensus
protocols
● Setup: a public-key directory
● parties have signing and verification keys for a digital signature
scheme.
● Each party knows every other party’s verification key.
● Network: point-to-point channels
● Synchronous, partial synchronous or asynchronous
Enter Bitcoin (2008-09)

● Important concepts used


● blockchain data structure.
● proof of work (POW).
● both known and studied earlier, but put in combination for a
novel application.
The setup and network configuration in
Bitcoin

● Setup: a random (unpredictable) string


● The blockchain protocol runs without relying on public-key
crypto
● Network: peer-to-peer diffusion
● Synchronous for at least a small subset of the participants
(that may be evolving over time).
The Bitcoin Setting for Consensus

Sometimes also referred to as the “Permissionless” setting.


● The bitcoin setting is a different compared to what has been
considered classically for the consensus problem.
● Communication is by diffusion. (no point-to-point channels).
● Message delivery is assumed but message origins and recipient
list are not specified.
● The protocol setup is not a private correlated setup (digital
signatures are not used to authenticate miners)
● A public setup is assumed (in the form of the genesis block)
The Bitcoin Setting for Consensus
Blockchain
Blockchain Notation
The Bitcoin “backbone”

● The core of the bitcoin protocol


● The chain validation predicate.
● The chain selection rule (max-valid)
● The proof of work function.
● The main protocol loop
● Protocol is executed by “miners.”
Model

● Assume there are n parties running of the protocol


● synchronously.
● each one has a quota of q queries to the function H(.) in
each round. ● A number of t parties are controlled by an
adversary (a malicious coalition).
Basic Properties

● Common Prefix
● Chain Quality
● Chain Growth
Common Prefix, Ι
Common Prefix, ΙΙ
Racing Attacks

Attacher splits from the main chain and tries to overtake the
“honest chain”
=> Common prefix breaks
Intuition why the attack is a small probability event: concentration
bounds help honest parties.
Chain Growth, I
Chain Growth, II
Chain Quality, II
Block withholding attack

Attacker mines privately and releases block at the time an honest


party releases its own block.
Assuming honest propagation favours the adversary, the honest
party block is dropped reducing chain quality
Still over time the adversary may not have enough blocks to
completely eliminate chain quality.
Robust Transaction Ledger - Ledger
Consensus

● It can be shown that the three properties can provide a ledger


with the following characteristics.
● persistence: Transactions are organized in a “log” and honest
nodes agree on it.
● liveness: New transactions are included in the log nodes, after
a suitable period of time.
Establishing a RTL from a Blockchain

● Persistence follows from (strong) Common Prefix.


● (need to exclude k most recent blocks)
● Liveness from Chain Growth and Chain Quality.
● (leave sufficient time for chain to grow and then apply chain
quality to ensure that at least one honest block is included).
Ledger Consensus vs. Consensus

● What is the connection?


● ledger is an ever-going protocol with inputs (e.g.,
transactions) continuously coming from (also) external sources.
● Consensus is a one-shot execution.
● Is it possible to reduce consensus to the ledger? Is it possible
to reduce the ledger to consensus?
Ledger <= Consensus

● (Potentially) simpler:
● run consensus for each set of transactions (blocks) with each
party proposing a set of transactions.
● plain validity is insufficient.
Consensus <= Ledger, I

● Using a ledger (or directly the underlying blockchain) to solve


consensus.
● Let’s focus on binary consensus for simplicity.
Consensus <= Ledger, II
Consensus <= Ledger, III
Consensus <= Ledger, IV
Consensus <= Ledger, V

● Main obstacle (intuitively) the blockchain protocol does not


provide sufficiently high chain quality.
● … we cannot guarantee that we have enough blocks originating
from honest parties.
● How to fix this?
Consensus <= Ledger, VI
2-for-1 POW
Key Lemma

● Lemma. Finding POW solution for either “side” of the POW


protocol is an independent event.
● *note that it works only for a suitable choice of T and T’+
GKL Consensus Protocol #2
Why it works:
Dynamic Availability

So far we dealt with the case where n nodes maintain the


blockchain.
However this number may change over time: new users enter
the system while existing users may go away.
The change over time can be dramatic !
The Bitcoin Blockchain handles this by adjusting the difficulty of
the proof of work algorithm.
Recall: PoW algorithm

int counter;
counter = 0
while Hash( block_header, counter) > Target
increment counter

block_header contains a coinbase transaction which contains an


extraNonce parameter

if transactions remain the same extraNonce has to be modified to


avoid repeating work
Recall: PoW algorithm

int counter;
counter = 0
while Hash( block_header, counter) > Target
increment counter

block_header contains a coinbase transaction which contains an


extraNonce parameter

if transactions remain the same extraNonce has to be modified to


avoid repeating work
Targe Difficulty over time
Target difficulty Now
Hash operations

● Consider a regular PC that can do 30 MHash / sec


● With expectation of 2^{74} hashing operations, mining a block will
require ~ 20 million years.

https://en.bitcoin.it/wiki/Non-specialized_hardware_comparison
Parallelising mining

● Bitcoin’s Proof of Work can be parallelized


Mining pools
● Instead of working separately, work together to solve the
same block.
● By collecting “shares” (small hashes of the block that are
not quite as small as needed) one can prove how much they
contributed.
Current bitcoin mining pools
Adjusting the difficulty
Target recalculation
Bahack’s attack

● The recalculation threshold is essential.


● Without it, an adversary can create a private, artificially
difficult chain that will increase the variance in its block production
rate; overcoming the chain of the honest parties becomes a non-
negligible event.
Understanding the attack : clay pigeons
Clay pigeon shooting game

● Suppose you shoot on targets successively from 10m against


an opponent
● your success probability 0.3 vs. 0.4 that of your opponent.
● You shoot in sequence 1000 targets. The winner is the one
that got the most hits.
● What is your probability of winning?
Chernoff Bounds
Analysis, I
Analysis, II
Analysis, III

● Now you are given a choice: you can decrease the size of the
clay pigeon target by a ratio β and augment your “kills” by
multiplying with 1/β.
● Suppose your accuracy is just linear with β.
● do you accept to play like this (while your opponent will
keep playing in the same way) ?
Analysis, IV
Mining parameters
Mining incentives

A miner is incentivized to mine with 2 ways: (1) Fees and (2)


rewards
Mining fees
Mining rewards

A miner is given a reward, today equal to 12.5 BTC


The reward and the fee are called the coinbase and together can
be claimed by the miner.

Example: fees = 1 BTC, rewards = 12.5 BTC, total coinbase = 13.5


BTC
The coinbase transaction
Coinbase transaction validity
● The induction basis for transaction validity (we have seen the
inductive step when we talked about UTXO evolution)
● Has no inputs, so does not conform to the Law of
Conservation!
● Never forms part of the mempool -- only included in blocks
for the first time
● When a block is confirmed, the coinbase is checked for
validity:
○ It is the first in the block
○ There’s only one of it
○ output value ≤ block reward + block fees
● Hence, a malicious miner cannot generate more money for
themselves
The coinbase transaction

● As it does not have any inputs, scriptSig can be anything for


coinbase
● scriptSig is used for certain block metadata:
○ The block height (this is verified for validity)
○ The name of the mining pool that mined the block
○ Extra entropy (nonce) if the block header nonce (“ctr”) has
been exhausted
○ Signalling for protocol updates (whether a miner is in favour
of an upgrade or not -- more on this in a later lecture)
Money supply in bitcoin
Money supply in bitcoin
Bitcoin’s price

● Extremely volatile
● April 2019: 1 BTC = 4,429 EUR
● mid 2018: 1 BTC = 5,502 EUR
● late 2017: 1 BTC = 17,000 EUR
● beginning 2015: 1 BTC = 208 EUR
● max 2013: 1 BTC = 900 EUR
● min 2013: 1 BTC = 73 EUR
● 2012: 1 BTC = 4 EUR
● 2010: 1 BTC = 0.06 EUR
● 22 May 2010: First real purchase with bitcoin
Market capitalization

Total bitcoin supply: 04 April 2019: 17,626,900 BTC =


$87,655,483,440.00 USD
Market capitalization
Market capitalization
Mining target

Recall the PoW equation: H(x || ctr || previd) < T

Pr*a query yields a valid block+ = T / 2κ


● T is the target
● In bitcoin, κ = 256
● T is the same for all miners
● Block validity requires proof-of-work validation
● Adversarial blocks with insufficient proof-of-work are rejected
as invalid
Difficulty adjustment

● T0 = 2256 - 32
● The target T is not constant but dynamically adjusted
● This is the way the network ensures a rate of 1 block per 10
minutes
● T is adjusted collectively by the network
● Adjustment happens every 2016 blocks (expected 2 weeks)
● The period of 2016 blocks is known as an epoch
● Difficulty is adjusted so that if the previous 2016 blocks had
been generated with the new T, they would have taken exactly 2
weeks
Difficulty adjustment

● T0 = 2256 - 32
● The target T is not constant but dynamically adjusted
● This is the way the network ensures a rate of 1 block per 10
minutes
● T is adjusted collectively by the network
● Adjustment happens every 2016 blocks (expected 2 weeks)
● The period of 2016 blocks is known as an epoch
● Difficulty is adjusted so that if the previous 2016 blocks had
been generated with the new T, they would have taken exactly 2
weeks
The target adjustment equation
Difficulty

● The inverse of the target is known as the


difficulty
difficulty = T0 / T
difficulty0 = 1
Bitcoin denominations

● 1 bitcoin is divisible up to 10-8


● 10-8 bitcoin = 1 satoshi
● 1 satoshi = 0.00000001 BTC
● 1 BTC = 100,000,000
● The bitcoin implementation stores integers in the
output edges, representing the number of satoshis
● Hence, there are no floating-point errors
Mining pools
● Mining gives a high reward per block (£80,000)
● Has a small probability of success
● The variance is high -- I prefer to get £1600 per month than
£80,000 per 4 years
● Miners typically collaborate in mining pools
● If a miner in a pool finds a block, the proceeds are split
among the pool members
● Splitting is pro rata according to the computational power
contributed by each
● Miners that mine outside of pools (very rare) are called solo
● Pools are maintained by a trusted, centralized pool owner
Mining inside a pool

● The pool maintains a different internal target for proof-of-work


Tpool > Tbitcoin
● If a block satisfies Tbitcoin < H(B) < Tpool, it is called a share
● The miners of the pool mine as follows:
○ They include a coinbase tx with output the pool address
○ If H(B) < Tbitcoin , they broadcast the block to the bitcoin
network
○ If H(B) < Tpool, they broadcast the share inside the pool
Pool share verification

Pool owner verifies shares:


● Check that PoW is achieved with Tpool
● Check that coinbase tx pays to the pool address and not some
other address
Pool rewarding

● When a bitcoin block is created, each node in the pool is


rewarded proportionally to the pool blocks they have recently
generated (compared to the total number of pool blocks
generated)
● Node participants pay a participation fee to the owner of the
pool
● Pools are a trusted scheme: Miners trust the pool owner, but
the pool owner does not trust the miners. Miners don’t trust the
other miners in the pool.
● The pool owner can steal money, but they will be detected
Pool rewarding

- Why can’t a pool miner mine shares with the pool address, but
blocks with his own address?

- Why can’t a pool miner mine shares with the pool address, but
blocks with his own address?
- - They don’t know if it will be a share or a block during mining!
After mining is completed, changing the address will invalidate
the PoW.
Ways to mine
CPU: Mining takes place in the CPU
GPU: Mining takes place in the graphics card (high parallelization)
ASIC: Specialized hardware for mining, separate hardware device
Is it worth it to mine? Probably not...

● WIth CPU Core i7: income $0.04 / year


● Με GPU NVIDIA GTX590: income $0.13 / year
● Με GPU ATI 6990: income $0.58 / year
● With specialized hardware AntMiner S5+: ○ Income: $5136 / year
● Electricity cost: $2409 / year (with $0.08 / kWh)
● Pool participation cost: $102.74
● Profit: $2624 / year
● Initial hardware cost: $2307
● Profits the first year: $317
Wallets
Wallets
Full nodes

● Some wallets maintain the whole blockchain


● Full nodes:
○ Keep the whole blockchain history (~187 GB)
○ Keep the whole UTXO
○ Verify each tx ○ Verify each block
○ Relay every tx and block
Full nodes
Merkle trees of transactions
Merkle trees of transactions
Advantages of using a Merkle tree

● Proof-of-work difficulty does not depend on the number of


confirmed transactions
○ Each miner is incentivized to include all transactions they can
and have a non-zero fee
● The PoW difficulty only depends on the target T
○ This allows better control of the mining rate *
● It enables SPV wallets!
SPV

● Simple Payment Verification


● A different type of wallet
● Useful for mobile, laptops etc.
● Doesn’t need to download the whole blockchain ○ Does not
download all transactions
● Much faster
● Keeps only the block headers from genesis till today (C)
● Connects to multiple untrusted servers
● Server is a full node which proves to the SPV wallet each claim
SPV

● The SPV wallet sends to the SPV server the bitcoin addresses they
have
○ But not the private keys!
○ The SPV server knows which transactions to send to the SPV client
○ The bitcoin addresses are shared in the form of a Bloom filter
● The SPV wallet verifies each block’s PoW and authenticated ancestry
○ Keeps a longest chain as usual -- but without transactions
● The SPV wallet verifies each tx it receives
○ Sigs
○ Law of conservation
● The SPV wallet verifies that the tx belongs to the Merkle Tree root of
a block
SPV
SPV Security

● SPV wallets ○ don’t keep a UTXO


○ don’t verify or receive txs they are not interested in
○ don’t verify coinbase validity
● Have the same level of security as a regular full node (under
the honest majority assumption)
● What can a malicious SPV server achieve?
○ Temporary fork to invalid block (invalid coinbase, txs, non-
existing UTXO, double spending...)
Wallet seeds and HD wallets

● An infinite sequence of wallet private keys can be generated


from a single “master private key” (BIP 0032) -- an HD wallet
● A private key can be encoded in the form of a human-readable
seed
● This seed is sufficient to recover all the private keys of a wallet
● Typically backed up on paper and optionally encrypted with
password
Example:
deal smooth awful edit virtual monitor term sign start home
shrimp wrestle
Wallet classification
Hot and cold wallets

● I can have my keys on an Internet-connected computer ○ “Hot


wallet”
○ Easy to use
○ I can always spend my money immediately
● I can keep my private keys offline
○ “Cold wallet”
○ Kept on a computer not connected to the Internet or a hard
drive
○ My keys cannot easily be stolen
○ I can move my keys to a hot wallet when I need to spend it
○ I can see how much money I have using my public keys which
can be kept safely online!
Other ways to store cold wallets

Paper wallet
● Private key is printed on a piece of paper
● Can be kept in a physical safe or a real bank vault
● Can optionally be encrypted with a secret password (which is
remembered) Brain wallet
● Private key is literally SHA256(“my dog’s name is Barbie”) or
some other passphrase
● Full private key can be recovered by memory
● Extremely unsafe! (More than $100,000 stolen due to low
entropy passwords)
Hardware wallets

● Special hardware device used to store private keys


● Cold wallet
● Most popular ones: Trezor and Ledger
● Connects to a computer via USB
● Keys never leave the device
● Device produces signed transaction, sends transaction to
computer
● Addresses you sent to are verified by looking at the screen
● As hardware/software is specialized, much harder to “hack” or
have bugs
● Works safely even if host computer is compromised
● Protected by a pin in case of theft
● Can be backed up into paper and/or other hardware wallets
Wallet classification
Blockchain Incentives
Mining Games

● As we have seen: miners are incentivised via rewards to follow


the protocol.
● Does this ensure that the protocol will be executed?
○ Is the reward mechanism “incentive compatible”?

○ Protocol is dominant strategy: a party will fare best by
following the protocol.
○ Protocol is Nash equilibrium: if all parties follow the protocol,
you cannot do better by deviating.
Dominant Strategies: example
Protocol is Nash Equilibrium, I

● All the participants are rational and want to maximize the utility
they obtain at the end of the execution.
● Utility of a participant is a function that takes as input the
strategies of all the participants and has as output a real number
that represents the gains of this participant at the end of the
execution.
Protocol is Nash Equilibrium, II
Protocol is Nash Equilibrium, III
Protocol is Nash Equilibrium, IV
Generalisation to Coalitions
Is Bitcoin a Nash Equilibrium ?

● What could be the utility in Bitcoin?


● How could utility be defined in a probabilistic protocol?
Absolute Rewards, I
Absolute Rewards, II

● Each block of the adopted chain gives a reward to its


producer.
● Absolute rewards utility. The utility of a coalition is equal to
the number of BTC that it has obtained at the end of the
execution.
Absolute Rewards, III
Relative Rewards, I

● Relative Rewards. The utility of a coalition in Bitcoin is equal to


relative rewards when it wants to maximize the amount of BTC
that it earns divided by the total amount of BTC that all the
participants receive at the end of the execution.
Relative Rewards, II
Utility in probabilistic protocols

● Given the strategies of all the participants, the outcome of the


Bitcoin execution is a random variable. So the utility of a coalition
is also a random variable. How to resolve this?
● Via Expectation: will determine the expected value of utility.
● Via events that happen with high probability.
Bitcoin and Equilibria, I
Bitcoin and Equilibria, II
Selfish Mining, I
Selfish Mining, II
Selfish Mining, III
Selfish Mining, IV
Selfish Mining - case 2a)
Selfish Mining, Case 2a), II
Selfish Mining, Case 2a), III

● More generally: the adversary will be capable of censoring


blocks, if
a. the adversary’s chain gets two blocks ahead of the public
chain.
b. The adversary manages to deliver first its block to the other
parties. When an honest party receives two chains of the same
length then it chooses the first that it received.
Selfish Mining, Analysis, I

● The computational power of the attacker contributes only


towards censoring blocks and not to extend the public ledger.
● So when it implements the attack, the total number of blocks
(expected value) in the public ledger is smaller compared to the
total number of blocks in the case where it follows the protocol.
● If the attacker does not manage to deliver its block first, it loses
the rewards from this block.
Selfish Mining, Analysis, II
● Consider a process operating in “block rounds." Attacker has
probability α to produce the next block. Assume attacker always
wins the network race vs. public blocks.
● Honest play: n rounds result to n blocks. Attacker owns αn
blocks in expectation. Utility (Relative Rewards) = α, (Absolute
Rewards) = α n.
● Selfish play: n rounds result to (1-α)n blocks. Attacker owns αn
of those blocks. Utility (Relative Rewards) = α/(1-α), (Absolute
Rewards) = α n.
● In a static difficulty setting absolute rewards remain the same
but relative rewards increase.
Selfish Mining, Analysis, II
● Consider a process operating in “block rounds." Attacker has
probability α to produce the next block. Assume attacker always
wins the network race vs. public blocks.
● Honest play: n rounds result to n blocks. Attacker owns αn
blocks in expectation. Utility (Relative Rewards) = α, (Absolute
Rewards) = α n.
● Selfish play: n rounds result to (1-α)n blocks. Attacker owns
αn of those blocks. Utility (Relative Rewards) = α/(1-α), (Absolute
Rewards) = α n.
● In a static difficulty setting absolute rewards remain the same
but relative rewards increase.
Bitcoin and Equilibria, III

● In the changing difficulty setting.


○ Selfish mining will impact chain growth and thus the difficulty
recalculation mechanism will lower the difficulty.
○ This means that block production per actual unit of time will
increase.
○ As a result, attacker will also receive higher number of
(absolute) rewards compared to honest play.
Block Reward Zero Attack
Bribery Attack
Mining Pool Games

● To create a pool or join an existing one?


● Assuming cost of verification and pool maintenance is non-
negligible:
○ Optimal solution is a single dictatorial pool.
■ (reason: offset costs with the player that has the lowest
service cost).
STAY TUNED FOR THE UPDATE

You might also like