Blockchain Academy
A community for technologists looking to learn more
about crypto and Blockchain technology
Blockchain AcademyOded Noam Jan 25, 2018
How to Be a
Smart-Contract Engineer
Blockchain AcademyOded Noam Jan 26, 2018
Agenda
0.Background
1.What are Smart Contracts
2.How are They Different from Regular Software
3.Principles of Smart Contract Engineering
About Me
The Promise of
Smart Contracts
Smart Contracts:
First time Introduction
Computer code as contract
Can enforce itself
Smart Contracts
Over Blockchain
Oded Naom Blockchain Academy
Replicated state machine
Payments Ledger
Turing complete VM
Decentralized back-end for applications
Replicated State
Machine
State
1
State
2
State
3
State
4
Transaction in
Consensus
Transaction in
Consensus
Transaction in
Consensus
But Why?
Why is the Internet so great?
DAO: Decentralized
Autonomous
Organizations
Oded Naom Blockchain Academy
Robust
Fair
Democratic
Disruptive
Unclear standing
The building block:
Decentralized Apps
Oded Naom Blockchain Academy
Email. WWW. BitTorrent. Bitcoin.
Critical mass problem
Trivial Use Case:
Escrow Services
ESCROW ESCROW
ESCROW ESCROW
Trivial Use Case:
Escrow Services
contract AssetBuyEscrow {
ERC721Interface public asset;
uint256 public tokenId;
address public seller;
address public buyer;
modifier onlySeller() {
require(msg.sender == seller);
_;
}
function AssetBuyEscrow(ERC721Interface _asset, uint256 _tokenId) public {
require(_asset != address(0));
require(_tokenId != 0);
asset = _asset;
tokenId = _tokenId;
seller = msg.sender;
_asset.transfer(this, _tokenId);
}
function buyerApprove() public {
require(buyer == address(0));
buyer = msg.sender;
}
function sellerApprove() public onlySeller {
require(buyer != address(0));
payout();
}
function payout() private {
asset.transfer(buyer, tokenId); // send asset to buyer
selfdestruct(seller); // delete contract and send stored ETH to seller
}
}
Smart Contracts
Aren’t Software
Readability
Oded Naom Blockchain Academy
Coder’s Mental model → Code → User’s Mental Model
Convoluted code makes bad contract
Test and formal verifications are important
Immutability
Oded Naom Blockchain Academy
Bug-free code?
Cannot be overruled by court
Security
Oded Naom Blockchain Academy
Huge targets
Don’t give yourself special rights
Liability
Oded Naom Blockchain Academy
No liability on infrastructure
Custody → Liability
Don’t give yourself special rights!
Principles of Smart
Contract Engineering
Measure Twice,
Cut Once
Oded Naom Blockchain Academy
Design properly
High quality code
Unit + integration tests + coverage
TDD
Sanity checks
Code reviews + audits
Formal Verification
Oded Naom Blockchain Academy
“what it does” vs “how it does it”
https://github.com/pirapira/ethereum-formal-verification-overview
no silver bullet
FV tools example
contract BinarySearch {
///@why3
/// requires { arg_data.length < UInt256.max_uint256 }
/// requires { 0 <= to_int arg_begin <= to_int arg_end <= arg_data.length }
/// requires { forall i j: int. 0 <= i <= j < arg_data.length -> to_int arg_data[i] <= to_int arg_data[j] }
/// variant { to_int arg_end - to_int arg_begin }
/// ensures {
/// to_int result < UInt256.max_uint256 -> (to_int arg_begin <= to_int result < to_int arg_end && to_int arg_data[to_int
result] = to_int arg_value)
/// }
/// ensures {
/// to_int result = UInt256.max_uint256 -> (forall i: int. to_int arg_begin <= i < to_int arg_end -> to_int arg_data[i] <>
to_int arg_value)
/// }
function find(uint[] data, uint begin, uint end, uint value) internal returns (uint ret) {
...
}
}
Practical example
(uses experimental solc features)
1 pragma experimental SMTChecker;
2 pragma solidity ^0.4.19;
3
4 contract hello {
5
6 function setState(uint _newState) public payable {
7 assert(1==1);
8 assert(1==2);
9 if (state == _newState) return;
10 state = _newState;
11 }
12
13 uint state;
14 }
Keep it Simple
Oded Naom Blockchain Academy
Short code
Avoid obfuscated optimizations
(but build and test with optimizer)
Minimize on-chain functionality
Off-Chain Logic
Oded Naom Blockchain Academy
Smart contract complements application back-end
Only public commitments are on-chain
… But verify correctness of important off-chain calculations
Off-Chain Logic: example
pragma solidity ^0.4.19;
contract SqrtDemo {
function calcSqrt(uint256 _number) public pure
returns (uint256 _result) {
uint256 b = 1;
while ( b ** 2 <= _number) {
b <<= 1;
}
b >>= 1;
uint256 ans = b;
b >>= 1;
while (b > 0) {
if ( (ans|b) ** 2 <= _number) {
ans |= b;
}
b >>= 1;
}
return ans;
}
}
pragma solidity ^0.4.19;
contract SqrtDemo {
function calcSqrtWithHint(uint256 _number, uint256 _hint) public pure
returns (uint256 _result) {
assert(_hint ** 2 <= _number);
assert((_hint+1) ** 2 > _number);
return _hint;
}
}
Secrets
Oded Naom Blockchain Academy
No secrets on chain
Random seeds are exposed
Anyone can simulate run (and debug) your cod
Secrets (example)
contract rps
{
mapping (string => mapping(string => int)) payoffMatrix;
address player1;
address player2;
string public player1Choice;
string public player2Choice;
modifier notRegisteredYet()
{
if (msg.sender == player1 || msg.sender == player2)
throw;
else
_
}
modifier sentEnoughCash(uint amount)
{
if (msg.value < amount)
throw;
else
_
}
function rps()
{ // constructor
payoffMatrix["rock"]["rock"] = 0;
payoffMatrix["rock"]["paper"] = 2;
payoffMatrix["rock"]["scissors"] = 1;
payoffMatrix["paper"]["rock"] = 1;
payoffMatrix["paper"]["paper"] = 0;
payoffMatrix["paper"]["scissors"] = 2;
payoffMatrix["scissors"]["rock"] = 2;
payoffMatrix["scissors"]["paper"] = 1;
payoffMatrix["scissors"]["scissors"] = 0;
}
/}
function getWinner() constant returns (int x)
{
return payoffMatrix[player1Choice][player2Choice];
}
function play(string choice) returns (int w)
{
if (msg.sender == player1)
player1Choice = choice;
else if (msg.sender == player2)
player2Choice = choice;
if (bytes(player1Choice).length != 0 && bytes(player2Choice).length != 0)
{
int winner = payoffMatrix[player1Choice][player2Choice];
if (winner == 1)
player1.send(this.balance);
else if (winner == 2)
player2.send(this.balance);
else
{
player1.send(this.balance/2);
player2.send(this.balance);
}
// unregister players and choices
player1Choice = "";
player2Choice = "";
player1 = 0;
player2 = 0;
return winner;
}
else
return -1;
}
Secrets (example)
Security
Oded Naom Blockchain Academy
Risk assessment
Good auditors
Stay updated
Continue reviewing after going live
Be open and transparent
Bug bounties
Maintenance /
Ongoing Security
Oded Naom Blockchain Academy
Updatable code vs liability
Circuit breaker
Timelock + circuit breaker
Off-chain monitors
Further reading
https://github.com/ConsenSys/smart-contract-best-practices
https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security/
http://chriseth.github.io/notes/talks/safe_solidity/
Blockchain AcademyOded Noam
Questions?
Jan 26, 2018
Blockchain AcademyOded Noam Jan 26, 2018

How to be a smart contract engineer

  • 1.
    Blockchain Academy A communityfor technologists looking to learn more about crypto and Blockchain technology Blockchain AcademyOded Noam Jan 25, 2018
  • 2.
    How to Bea Smart-Contract Engineer Blockchain AcademyOded Noam Jan 26, 2018
  • 3.
    Agenda 0.Background 1.What are SmartContracts 2.How are They Different from Regular Software 3.Principles of Smart Contract Engineering
  • 4.
  • 5.
  • 6.
    Smart Contracts: First timeIntroduction Computer code as contract Can enforce itself
  • 7.
    Smart Contracts Over Blockchain OdedNaom Blockchain Academy Replicated state machine Payments Ledger Turing complete VM Decentralized back-end for applications
  • 8.
  • 9.
  • 10.
    Why is theInternet so great?
  • 11.
    DAO: Decentralized Autonomous Organizations Oded NaomBlockchain Academy Robust Fair Democratic Disruptive Unclear standing
  • 12.
    The building block: DecentralizedApps Oded Naom Blockchain Academy Email. WWW. BitTorrent. Bitcoin. Critical mass problem
  • 13.
    Trivial Use Case: EscrowServices ESCROW ESCROW ESCROW ESCROW
  • 14.
    Trivial Use Case: EscrowServices contract AssetBuyEscrow { ERC721Interface public asset; uint256 public tokenId; address public seller; address public buyer; modifier onlySeller() { require(msg.sender == seller); _; } function AssetBuyEscrow(ERC721Interface _asset, uint256 _tokenId) public { require(_asset != address(0)); require(_tokenId != 0); asset = _asset; tokenId = _tokenId; seller = msg.sender; _asset.transfer(this, _tokenId); } function buyerApprove() public { require(buyer == address(0)); buyer = msg.sender; } function sellerApprove() public onlySeller { require(buyer != address(0)); payout(); } function payout() private { asset.transfer(buyer, tokenId); // send asset to buyer selfdestruct(seller); // delete contract and send stored ETH to seller } }
  • 15.
  • 16.
    Readability Oded Naom BlockchainAcademy Coder’s Mental model → Code → User’s Mental Model Convoluted code makes bad contract Test and formal verifications are important
  • 17.
    Immutability Oded Naom BlockchainAcademy Bug-free code? Cannot be overruled by court
  • 18.
    Security Oded Naom BlockchainAcademy Huge targets Don’t give yourself special rights
  • 19.
    Liability Oded Naom BlockchainAcademy No liability on infrastructure Custody → Liability Don’t give yourself special rights!
  • 20.
  • 21.
    Measure Twice, Cut Once OdedNaom Blockchain Academy Design properly High quality code Unit + integration tests + coverage TDD Sanity checks Code reviews + audits
  • 22.
    Formal Verification Oded NaomBlockchain Academy “what it does” vs “how it does it” https://github.com/pirapira/ethereum-formal-verification-overview no silver bullet
  • 23.
    FV tools example contractBinarySearch { ///@why3 /// requires { arg_data.length < UInt256.max_uint256 } /// requires { 0 <= to_int arg_begin <= to_int arg_end <= arg_data.length } /// requires { forall i j: int. 0 <= i <= j < arg_data.length -> to_int arg_data[i] <= to_int arg_data[j] } /// variant { to_int arg_end - to_int arg_begin } /// ensures { /// to_int result < UInt256.max_uint256 -> (to_int arg_begin <= to_int result < to_int arg_end && to_int arg_data[to_int result] = to_int arg_value) /// } /// ensures { /// to_int result = UInt256.max_uint256 -> (forall i: int. to_int arg_begin <= i < to_int arg_end -> to_int arg_data[i] <> to_int arg_value) /// } function find(uint[] data, uint begin, uint end, uint value) internal returns (uint ret) { ... } }
  • 24.
    Practical example (uses experimentalsolc features) 1 pragma experimental SMTChecker; 2 pragma solidity ^0.4.19; 3 4 contract hello { 5 6 function setState(uint _newState) public payable { 7 assert(1==1); 8 assert(1==2); 9 if (state == _newState) return; 10 state = _newState; 11 } 12 13 uint state; 14 }
  • 25.
    Keep it Simple OdedNaom Blockchain Academy Short code Avoid obfuscated optimizations (but build and test with optimizer) Minimize on-chain functionality
  • 26.
    Off-Chain Logic Oded NaomBlockchain Academy Smart contract complements application back-end Only public commitments are on-chain … But verify correctness of important off-chain calculations
  • 27.
    Off-Chain Logic: example pragmasolidity ^0.4.19; contract SqrtDemo { function calcSqrt(uint256 _number) public pure returns (uint256 _result) { uint256 b = 1; while ( b ** 2 <= _number) { b <<= 1; } b >>= 1; uint256 ans = b; b >>= 1; while (b > 0) { if ( (ans|b) ** 2 <= _number) { ans |= b; } b >>= 1; } return ans; } } pragma solidity ^0.4.19; contract SqrtDemo { function calcSqrtWithHint(uint256 _number, uint256 _hint) public pure returns (uint256 _result) { assert(_hint ** 2 <= _number); assert((_hint+1) ** 2 > _number); return _hint; } }
  • 28.
    Secrets Oded Naom BlockchainAcademy No secrets on chain Random seeds are exposed Anyone can simulate run (and debug) your cod
  • 29.
    Secrets (example) contract rps { mapping(string => mapping(string => int)) payoffMatrix; address player1; address player2; string public player1Choice; string public player2Choice; modifier notRegisteredYet() { if (msg.sender == player1 || msg.sender == player2) throw; else _ } modifier sentEnoughCash(uint amount) { if (msg.value < amount) throw; else _ } function rps() { // constructor payoffMatrix["rock"]["rock"] = 0; payoffMatrix["rock"]["paper"] = 2; payoffMatrix["rock"]["scissors"] = 1; payoffMatrix["paper"]["rock"] = 1; payoffMatrix["paper"]["paper"] = 0; payoffMatrix["paper"]["scissors"] = 2; payoffMatrix["scissors"]["rock"] = 2; payoffMatrix["scissors"]["paper"] = 1; payoffMatrix["scissors"]["scissors"] = 0; } /} function getWinner() constant returns (int x) { return payoffMatrix[player1Choice][player2Choice]; } function play(string choice) returns (int w) { if (msg.sender == player1) player1Choice = choice; else if (msg.sender == player2) player2Choice = choice; if (bytes(player1Choice).length != 0 && bytes(player2Choice).length != 0) { int winner = payoffMatrix[player1Choice][player2Choice]; if (winner == 1) player1.send(this.balance); else if (winner == 2) player2.send(this.balance); else { player1.send(this.balance/2); player2.send(this.balance); } // unregister players and choices player1Choice = ""; player2Choice = ""; player1 = 0; player2 = 0; return winner; } else return -1; } Secrets (example)
  • 30.
    Security Oded Naom BlockchainAcademy Risk assessment Good auditors Stay updated Continue reviewing after going live Be open and transparent Bug bounties
  • 31.
    Maintenance / Ongoing Security OdedNaom Blockchain Academy Updatable code vs liability Circuit breaker Timelock + circuit breaker Off-chain monitors
  • 32.
  • 33.
  • 34.