0% found this document useful (0 votes)
72 views79 pages

Privacy Enhancing Technologies: Department of Computer Science

This document contains slides for CS 6290 Privacy Enhancing Technologies and discusses topics including blockchain technology, smart contracts, Ethereum, writing smart contracts in Solidity, challenges in smart contract design such as privacy and race conditions, and provides an example of a smart contract for a rock paper scissors game on the Ethereum blockchain.

Uploaded by

Ao Ouyang
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)
72 views79 pages

Privacy Enhancing Technologies: Department of Computer Science

This document contains slides for CS 6290 Privacy Enhancing Technologies and discusses topics including blockchain technology, smart contracts, Ethereum, writing smart contracts in Solidity, challenges in smart contract design such as privacy and race conditions, and provides an example of a smart contract for a rock paper scissors game on the Ethereum blockchain.

Uploaded by

Ao Ouyang
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/ 79

CS 6290

Privacy Enhancing Technologies

Department of Computer Science

Slides credit in part from A. Juels, D, Song, A. Miller, E. Ben-Sasson, D.


Dziembowski, A. Judmayer, F. Zhang, I. Eyal, J. Poon, and F. Greenspan
CS6290: Privacy Enhancing Technologies
Contract system evolution

CS6290: Privacy Enhancing Technologies


CS6290: Privacy Enhancing Technologies
Recall: Bitcoin
• Just one application on top of a blockchain: token
exchange
Decentralized Consensus
Money “Blockchain”
Users
Account Balances
Alice: ฿10
Bob: ฿15
Carol: ฿120

CS6290: Privacy Enhancing Technologies


Smart contract
• User-defined programs running on top of a
blockchain
Decentralized Consensus
Money “Blockchain”
Users
Contracts
Storage
Code
Data

CS6290: Privacy Enhancing Technologies


About Ethereum
• Founded by Vitalik Buterin, Gavin
Wood and Jeffrey Wilcke in 2014
• Core: Ethereum Virtual Machine
(“EVM”)
• “general purpose computation”
programming language
• Every node of the network runs
the EVM and executes the same
instructions on blockchain.
• Sometimes described evocatively
as a “world computer”

CS6290: Privacy Enhancing Technologies


Assessed on Feb 2019 https://etherscan.io
Introducing the Ethereum
platform

CS6290: Privacy Enhancing Technologies


Figure by ethereum.org
In-built cryptocurrency

• Ether
• Mined in a way similar to Bitcoin
• Block reward: ~ 3 ETH
• Currently $100+ per ether
• The crypto-fuel for the Ethereum network
• Healthy ecosystem: a form of payment to compensate
the machines for executing the requested operations
• Also, an incentive ensuring that developers write quality
applications (wasteful code costs more)

CS6290: Privacy Enhancing Technologies


General purpose script language

• High-level languages :
Serpent, Solidity, LLL
• Similar to Java script
• Written contracts are
compiled to EVM code
and deployed on EVM
• Each contract has
unique address on EVM
• Execution?
CS6290: Privacy Enhancing Technologies
Code execution

• Deployed contracts (code) are triggered by


transactions
• Transactions specify a TO contract address it sends to
• Record on the blockchain
• EVM executes it with the deployed code
• Code can:
• Send ETH to other contracts / individuals
• Read / write storage
• Call (i.e., start execution in) other contracts

CS6290: Privacy Enhancing Technologies


Code execution
•Executed by all nodes in the Ethereum network
•Ask any node to learn the updated state of the EVM

Ethereum Blockn Blockn+1 Blockn+2 Blockn+3


blockchain

Suppose we have a piece Later, we trigger the code by


of code deployed on this recording a corresponding
block transaction on this block

Consensus code Consensus outputs


+ Consensus inputs =
(algorithm) (EVM state update)
CS6290: Privacy Enhancing Technologies
Gas system
• We cannot tell whether or not a deployed code will
run infinitely
• Waste computing resources
• Might damage system robustness
• Ethereum solution: charge fee per computational
step (gas)
• e.g. adding two numbers costs 3 gas, calculating a
hash costs 30 gas, and sending a transaction costs
21000 gas
• Special gas fees also apply to storage operations
• Currently, the gas price is around 2 * 10-9 ether
(https://ethgasstation.info)
CS6290: Privacy Enhancing Technologies
Gas limit
• Specify the maximum amount of gas the sender is
willing to buy in a transaction
• The code processing stops If the gas used exceeds this
limit during execution
• The sender still has to pay for the performed computation
• Gas limit also applies to each block
• Similar to the maximum block size in Bitcoin
• Voting mechanism (can upvote/downvote gas limit by
0.0976% every block)

CS6290: Privacy Enhancing Technologies


Writing Ethereum Smart Contract

• Programming language: Solidity


• Contract-oriented
• Syntax similar to Javascript
• A contract is similar to a class
• State variables
• Functions
• Function Modifiers
• Events
• Types: integer, string, array, mapping…

CS6290: Privacy Enhancing Technologies


Set up contract parameters and
data structures
(pseudocode)
Init:
Tend := 28 February 2018, $ticket := 1, pool := {}, pot :=
0
The lottery purchase function
Function TicketPurchase(): on the contract.
On receiving $amt from some party P: Triggered when some party P
Assert $amt = $ticket, balance[P] ≥ $amt sends a corresponding
balance[P] := balance[P] - $ticket transaction on the blockchain
pot := pot + $ticket
pool := pool ∪ P
Each contract has a timer that is
Contract timer: T either based on the block index
or the real-world time
If T > Tend then:
𝑅 When certain condition is
W ֚ pool
satisfied, this part automatically
balance[W] := balance[W] + pot
executes
CS6290: Privacy Enhancing Technologies
Solidity
• A contract-oriented, high-level language for implementing smart
contracts
• Targets the Ethereum Virtual Machine (EVM)
• Syntax at https://solidity.readthedocs.io/

CS6290: Privacy Enhancing Technologies


Browser-solidity
• An useful integrated development environment
(IDE) with solidity
• Design and run smart contract on a Java VM
environment
• Debugging
• Easier for beginners
• Will not consume “real” money
• Need not to set up your local EVM
▪ E.g., ethereumjs-testrpc https://github.com/ethereumjs/testrpc
• https://remix.ethereum.org/

CS6290: Privacy Enhancing Technologies


Ethereum Smart Contract
Designing

CS6290: Privacy Enhancing Technologies


Key Challenges in Smart
Contract Design
• Smart Contracts in Ethereum can be trusted for
correctness and availability, but not privacy
• Blockchain resources are expensive
• Race conditions and temporary forks
• You need to be considerate
• Obscure and counterintuitive VM rules
• Programming in Ethereum is not developer-friendly yet

CS6290: Privacy Enhancing Technologies


Elements of a Smart Contract
Application
• The smart contract itself
• Client code for the parties in the contract
• Protocol narrations
• What happens in the ordinary case, where all parties are
honest?
• What are the attacks / edge cases that your smart
contract defends against?
• What are attacks that your smart contract *does not*
defend against?

CS6290: Privacy Enhancing Technologies


Application I:
Rock Paper Scissors
using Hash Commitments and Collateral

CS6290: Privacy Enhancing Technologies


Rock Paper Scissors
Intended behavior:
• Any two parties sign up to play, deposit $1
• Each party chooses Rock, Paper, Scissors
• Both parties reveal their choice
• Winner gets $2

Threat model: the other party is malicious


Goals: an honest party is guaranteed an equal or
better payoff distribution

CS6290: Privacy Enhancing Technologies


Problem 1: Race conditions
• What happens when 3 players try to sign up at
once?
• Which two players are involved
• How to handle the deposit of the remaining player

• You need to specify a rule for the contract to follow!

• Or, this design flaw on the contract might cause


money leaks
• What if we send more than $1000?

CS6290: Privacy Enhancing Technologies


Problem 2: Front running!
• Whoever goes second in the game can always win
• The front runner’s choice is leaked on the blockchain
• The Ethereum blockchain is publicly visible

• Record hash commitment of the choice on the


blockchain instead!
• The player goes second cannot learn the choice
• Reveal the choice once both two players have
committed their choices

CS6290: Privacy Enhancing Technologies


Problem 3: Fairness!
• Whoever reveals second in the game can quit
• I’m going to flee because I’m losing
• You can never trace me because I’m just no-one with a
pseudonymous address

• Solution: collateral deposits


• I will have your deposited money instead!
• But how much is suitable for advance deposit?
• Game theory [CCS’ 17]

CS6290: Privacy Enhancing Technologies


Application II: Utility Token
for Games
Booming Token Economy

• Economic systems facilitated


or executed with tokens
• Decisions are made through
token supply & demand
• Participants act upon
incentives
• Big names: Bitcoin, Ethereum,
Ripple, EOS, IOTA, OmiseGO,
Maker, Filecoin …
Security Token vs. Utility Token
▪ Security token
• Ownership rights or share of a
company
• Subject to stricter regulation
requirements
▪ Utility token
• For dedicated service access
• Currently less regulation is imposed
▪ No definite distinction between the two
Our narrative – a utility token for
games
▪ Reviving game arcade
• Retain existing players
• Attract new players
▪ Use token to unlock barriers in the past
• Arcade operators may attract players from wider
demographic range
• Players may have more gaming choices with token rewards
• Potentially attract more game developers to join this
tokenized model
Our narrative – a utility token for
games
▪ Players get token rewards while playing
• Every X rounds
• Every X achievement
• Every X “coin” in
▪ Players consume tokens to enhance gaming
experience
• In-game level up
• In-game power boost
• Special cosmetic badges
• Unique themes
• More in-game stash
• …
Basic version purely based on
public chain
▪ Architecture
Balance checking
(via Ethereum wallet)
Public chain player
(Token contract)

Transaction
Game playing
Sending & querying

Game
Arcade server
Transaction machine
relaying
Assumptions
▪ The game arcade is trusted
• Game machine has a private key built in
• Game machine can sign transaction with the private key
• The arcade has a local server to relay transactions from
machines
Assumptions
▪ We do not consider the performance/cost issues
• TX delay – how long it takes for the transaction result to
return
• TX rate – how frequent the machine generate transaction
• TX fee – how much it costs the arcade to run the system
Our Contract Design
▪ ERC20 token
• Other standards: ERC223, ERC621, ERC827,etc.

▪ Token rewarding
• Authorized game machines can reward players

▪ Token consumption
• Authorized game machines can consume token for
players to enhance gaming experience
ERC20 – the most widely
adopted standard

Source extracted on Sep 21st 2018 at https://coinmarketcap.com/tokens/views/all/


ERC20 – dissecting the
specification
Alice Bob Carol
ERC20 – dissecting the
specification
totalSupply() Alice Bob Carol
returns the total 100
token supply
ERC20 – dissecting the
specification
balanceOf() Alice Bob Carol
returns the balance 100
of a specified account
10 20 70
ERC20 – dissecting the
specification
allowance() Alice Bob Carol
returns the amount 100
which one account is
allowed to withdraw 10 20 70
from another 0 0 0 0 0 0
ERC20 – dissecting the
specification
transfer() Alice Bob Carol
transfers specified 100
amount of tokens to 2
specified account from 10
12 18
20 70
the caller 0 0 0 0 0 0
ERC20 – dissecting the
specification
approve() Alice Bob Carol
allows one account 100
to withdraw from the
caller account up to 12 18 70
a specified amount 0 0 0 0 020 0
ERC20 – dissecting the
specification
transferFrom() Alice Bob Carol
transfers specified 100
amount of token from 10 10
one address to another, 12 28
18 70
60
subject to the allowance 0 0 0 0 10
20 0

12
Start with some reference
implementation

▪ Don’t write the smart contract code from scratch


• A glut of ERC20 templates out there
▪We start with the template from OpenZeppelin
• https://github.com/OpenZeppelin/openzeppelin-solidity
▪Our tutorial code and document can be found at
• https://github.com/CongGroup/SecDev2018-tutorial
A quick go through of ERC20
implementation
▪ data members and events

use the SafeMath library


A quick go through of ERC20
implementation
▪ constructor – only called once when the contract is
deployed
A quick go through of ERC20
implementation
▪ getters – no transaction is required for calling them
A quick go through of ERC20
implementation
▪ transfer
A quick go through of ERC20
implementation
▪ approve + transferFrom
Token rewarding

Rewarding condition is triggered.


Sign a rewarding transaction
bearing player’s address
Signed Signed
Public chain transaction transaction
Arcade Game In-game
GameToken state update
server machine
contract Rewarding Rewarding
event event
Update
displayed play
balance
For simplicity, we consider the rewarded
token is transferred from the machine Player
to the player check balance in mobile wallet
Token consumption

Check player’s balance and


sign a consumption transaction
bearing player’s address
Signed Signed
Public chain transaction transaction
Arcade Game
GameToken
server machine
contract Consumption Consumption
event event
Update
balance & buy an item
game state
Similarly, we consider the consumed
token is transferred from the player to Player
the machine check balance in mobile wallet
Reward and consume function in
contract
▪ events, data fields and modifiers
Reward and consume function in
contract
▪ access control
Reward and consume function in
contract
▪ reward and consume
Hands-on: compile and deploy
the contract
▪ Goal: compile and deploy the GameToken contract
to Kovan testnet
▪ Tools
• Google chrome
• MetaMask – A web-based Ethereum wallet
• Remix – A web-based IDE for develop and deploy smart
contract
Hands-on: prepare the contract
▪ Downloads the GameToken contract at
https://github.com/CongGroup/SecDev2018-
tutorial

▪ Copy & paste the code to Remix


Hands-on: compile the contract
▪ Click Start to compile
• Make sure Enable Optimization is checked
▪ Upon successful compilation,
you will see something like this
Hands-on: deploy the contract

▪ Deploy the contract with constructor arguments


• Total supply (uint)
• Token name (string)
• Token symbol(string)
• Decimals (uint)
▪ Example arguments
• 10000, “GameToken”, “GTN”, 3
Hands-on: deploy the contract
▪ A MetaMask window will prompt up asking for
confirmation
Hands-on: deploy the contract
▪ Check and play with the deployed contract in
Remix
▪ Deployed contract can also be checked on
Etherscan via the contract’s address
From contract to blockchain
application
▪ Smart contracts only live on blockchain
▪ An outside application can interact with them via a
set of API
▪ Ethereum JSON-RPC API
From contract to blockchain
application
▪ Example API
eth_getBalance - Returns the balance of the account of given address.
Parameters Example

eth_sendTransaction - Creates new message call transaction or a contract creation


Parameters Example
From contract to blockchain
application
▪ The API requests (essentially transactions) are
handled by a blockchain node, which for Ethereum
runs a client like Geth or Parity
▪ We need to trust the node for
• Handling and relaying request faithfully
• Broadcasting the transactions to the network
• Notifying us the events emitted from the transactions
▪ Alternatively, one can broadcast transactions to
multiple nodes that are not necessarily fully trusted
From contract to blockchain
application
▪ In previous hands-on session, the transactions for
deploying contracts are relayed by MetaMask to a
public Ethereum node cluster (Infura).

https://www.slideshare.net/Kenneth_hu/20180711-metamask
From contract to blockchain
application
▪ In our case, the game arcade server will run a
local Ethereum node

Machine
Arcade
Public chain server
(Ethereum node)
Machine
When deployed to the real
Ethereum mainnet
▪ Transaction speed matters
• Players desire the token to take effect instantaneously

▪ Transaction rate is also a concern


• Multiple machines can reward and consume at the same
time

▪ Transaction fee should be minimized


• Game arcades don’t want high operation cost for the
token system
Public chain alone is not enough

A single DApp can bring


ETH price is still too high for daily operation
down the whole network

https://www.coindesk.com/ethereum-price/
How to solve the performance
and cost issue?
▪ This is generally referred to as blockchain
scalability problem
▪ General directions
• Layer 1 – Sharding
▪ Redesign base-layer blockchain protocol
▪ Each TX is only seen and processed by a small shard of nodes
▪ Examples: Zilliqa, Prysmatic Labs Ethereum 2.0
• Layer 2
▪ State channels
▪ Sidechains (aka parachains, childchains)
Scaling technique – state
channels
▪ One-to-one channel for bulk off-chain transactions
• Final settlement on-chain
▪ Example: Lightning Network, Raiden Network,
Counterfactual

https://cdn-images-1.medium.com/max/2000/1*YjHwvs76f1-CgGx43SwvEw.png
Scaling technique – sidechains
▪ A separate chain running in parallel to the main chain
• Independent consensus (e.g., PoA) and configurations
• Data/states can be exchanged between the two chains
▪ Examples: Plasma, POA Network, Parity Bridge, (Polkadot, Cosmos)

We follow this direction!

https://cdn-images-1.medium.com/max/1600/0*gHDyU65BfvNG-VHn.png
Solution: consortium chain
▪ Game arcades maintain an Ethereum-compatible
consortium chain
• We will bridge the consortium chain with the public chain
▪ Rationale
• We can reuse previously developed components
▪ GameToken contract
▪ Server application
• More flexibility in upgrading and adding new features
• Different games arcades can naturally form a consortium
Solution: consortium chain
▪ The consortium chain can be configured with
• low TX delay – e.g., 1 second block interval
• high TX rate – e.g., unlimited block gas limit
• zero TX fee – e.g., zero transaction gas price
Solution: consortium chain
▪ Game machines only interact with the
consortium chain
▪ Token rewarding and consumption only occur on
consortium chain

machine arcade arcade machine


server server
eth node eth node
machine machine
Consortium chain
Solution: consortium chain +
cross-chain bridge
▪ Players can exchange tokens between the two
chains via the bridge
• “Burn” on one chain, “mint” on the other

110
Total balance of A: 100
A: 110
100 A: 10
Public Consortium
Bridge
chain chain
Solution: consortium chain +
cross-chain bridge
▪ We use Proof-of-Authority (PoA) consortium chain
• Only a set of validators can propose and write blocks
• Each game arcade can run a validator
• Wrongdoing validators can be voted out
• Less de-centralized than PoW, PoS
▪ Example PoA consensus algorithms
• AuthorityRound (Aura)
• Clique
• Tendermint
Solution: consortium chain +
cross-chain bridge
▪ Each validator additionally plays the role of a bridge
• Cross-chain state transfer requires multisig from bridges
• An exchange is approved when a required number of
bridges have signed

Bridge
(validator)
Public Consortium
chain PoA chain
Bridge
(validator)
Multi-sig bridging – the
straightforward way
player A One public transactions
Multiple transaction
Contract pseudo code
exchange n token
hash = H(A | n | txHash)
bridge B1
Contract pseudo code
voter[hash].push( B1
B3)
B2
balance[A] -= n
bridge B2
Enough?
Exchange event
A, n, txHash bridge B3
balance[A] += n

Public chain Consortium chain


Multi-sig bridging – the more
economic way
player A One public transaction
Contract pseudo code
exchange n token
Contract pseudo code for all sig in signatures:
bridge B1
verify(sig, A | n | txHash)
balance[A] -= n

Exchange event
A, n, txHash
bridge B2
All verified?

signatures.push( B2
B3 )
B1
bridge B3
Enough? balance[A] += n

Consortium chain Public chain


Already implemented and
deployed by
Related References
• Konstantinos Christidis and Michael Devetsikiotis. “Blockchains and Smart
Contracts for the Internet of Things”, IEEE Access, 2016.
• The ZILLIQA Technical Whitepaper. Online at
https://docs.zilliqa.com/whitepaper.pdf
• The Ethereum White Paper. Online at
https://github.com/ethereum/wiki/wiki/White-Paper
• The Solidity Programming Language for Ethereum. Online at
https://solidity.readthedocs.io/en/v0.5.4/
• The Ethereum Yellow Paper. Online at
https://ethereum.github.io/yellowpaper/paper.pdf
• ERC20 Token Standard. Online at
https://theethereum.wiki/w/index.php/ERC20_Token_Standard
• Adam Back, Matt Corallo, et al. “Enabling Blockchain Innovations with Pegged
Sidechains”, 2014

You might also like