Blockchain
and
Smart Contract Verification
Tezos Japan, DaiLambda, Inc.
Jun FURUSE/古瀬淳, Taipei, 2019-08-29FLOLAC’19
Bit of myself: Past
OCaml researcher and programmer
Studied type system of FP
Like Haskell too
FP in Financial Systems
Derivative modeling
HFT(High Frequency Trading) systems
Bit of myself: Now
NPO to promote Tezos technology in
Japan.
A small company to participate Tezos
core development.
Bit of Tezos
3rd gen. cryptocurrency
(1st: Bitcoin, 2nd: Ethereum, 3rd: many)
Consensus algorithm: Proof of Stake
On Chain Governance
Symbol ꜩ
Written in OCaml
Formal verification
Today’s Agenda
Brief History of Currency
What is Blockchain?
Technical Aspects of Blockchain
Proof of Stake
Bit more about Tezos
Blockchain and Formal Verification
Brief History of Currency
Brief History of Currency
Main theme: “How to trade smoothly?”
Bartering
⇄
Complex Bartering
←
↘ ↗
Birth of Currency
⇄ ⇄
⇅
貝貨
China, 1100 BC
貝貞負貢財貨貫責貪販
貧貶貽賀貲貳貰貸貯貼
買費貿賈賊賃賂賄賑賓
賜質賞賤賠賣賦賚賢賭
購賽賺賻贄贅贇贊贈贏Monetaria moneta
Shell has a built-in value (beauty).
Conditions for Currencies
Scale of value (comparison of values)
Means of exchange (easy to carry)
Means of store of value (never rotten)
Coins
Mintable: Governments can control the money
supply.
China, 800 BC (刀貨, 布貨)
Coins have built-in values as precious
metal.
Seigniorage vs counterfait
Convertible Paper Money
Easier to carry
Assured conversion to gold (or silver, copper)
Total supply is limited to the government’s gold stock
⇄
The medium of the currency has no built-in value.
→ More strict anti-counterfait requirements
The First Convertible Paper Money
交子in China, around 1050
Started as private notes for iron coins.
宋dynasty assured the conversion
between copper coins.
Credit
This is not currency, but optimized trade efficiency
by recording credit/debt using numbers.
Fiat Money
Inconvertible!「法定通貨」
Since 1971, at the end of .
No more support by precious metal, but money stayed as money.
Confusions led to floating exchange rate system.
Governments can control their money supply.
Economy has boosted with more liquidity of currencies.
Bretton Woods Agreements
The First Fiat Money
交子in China, around 1050, again.
The world first convertible paper money
… and soon became the world first fiat
… and lost its value since too many were
printed.
Electronic Money
No more medium. Just numbers in electrons.
Pegged with government currencies.
Very centralized. Manager companies are responsible for
conversion.
Cryptography to prevent forgery and cheating.
The Basis of the Value of Currencies
Less and less:
The value of the medium: Nothing
Convertible with precious metal: No
The physical form as fiat: No
What Makes Money as Money?
Chartalism
Means of paying tax
You have to pay tax or you get arrested.
Radical Theory: Common Knowledge
Common knowledge that it is money.
With it, no need of centralized power!!
Iraqi Swiss dinar (1993-2003)
Somali shillings (1990’s)
Rise of Cryptocurrencies
Since 2009-01-03 (Bitcoin):
Electronic
Decentralized: no central bank
Cryptography to prevent counterfait and cheating
Tracking vs Privacy
Electronic money made tracking much easier.
Powers love tracking.
Public do not like being tracked.
Nowadays, anonymity is another
important condition of currencies.
https://twitter.com/maryhui/status/1138675837165641733
Blockchain Overview
What is Blockchain?
Let’s forget currency for now:
Ledger style DB
Distributed
Open network
Token
Smart contracts
Ledger Style DB
DB by history accumulation
B1 → B2 → B3 → B4 → ..
S0 = ∅
S1 = B1(S0)
Sn = Bn(Sn-1) = Bn(Bn-1(..(B1(S0))))
Examples
Bankbook
Version control system: Git
Distributed DB
Multiple DB nodes, each carries a replica of the DB:
Fault tolerance
Load balancing
Distributed DB: conflicts
How to resolve conflicts?
B
→→
A
x = A
x = A
x = A →→x = B
x = B
x = A
x = B
or
?
? ?
Consensus Algorithm
Algorithm to resolve conflicts between nodes.
Bad news: There is no such algorithm [FLP85].
Every protocol has the possibility of non termination,
even with only one faulty node.
Good news: Paxos
It may not terminate, but practically it is OK.
Voting between nodes
Only for closed network with
fixed nodes.
Closed Network
If you are happy with it, you do not need
“Blockchain”.
Open Network
Permissionless public network,
where anyone can join with a node.
Decentralized, therefore neutral
Almost impossible to hack
Low cost
Problem of Open Network Consensus
Consensus control and inhibition
by Sybil attack: produces fake
identities to dominate the network.
Satoshi Nakamoto and Bitcoin
Prevent Sybil attacks i.e. infinite identity creations:
Requirement of real world resource:
computation power (PoW)
Rewards: incentive to provide the
resource and behave honestly.
The rewards are recorded in the DB.
Birth of cryptocurrency
Cryptocurrencies
A solution to Sybil attacks against open networks.
Smart Contracts
Ledger DB can carry not only account balance,
but any data, even program code.
Code attached to an account is executed when it
receives a transaction.
Automatic execution of financial/non-financial contracts
Distributed application (dAPPs) framework, neutral and cost
efficient without requirement of central DB managers.
Gas cost
Smart contracts cannot run infinitely.
To prevent DoS attacks, the caller
must pay the running cost to the miner:
Gas limit, out of gas
Contract calls fail if its runtime cost exceeds the declared gas cost
or the system gas limit.
VM model
To calculate the gas cost, smart contract language is often
implemented as a VM.
What is Blockchain
Ledger DB
Distributed
Open network
Token for incentives
Smart contracts
Blockchain: Technical Details
Blockchain Network
P2P network with multiple nodes,
each has a replica of the ledger DB.
Reading from the DB
Query past / current state of the ledger to a node.
! ?
→
? !
→
Writing to the DB
Sending operation to a node:
Transactions
Account creations, etc
Operations spread into the P2P network.
→
→
O1
O1
O1
O1
O1
O1
O2
O2
O2
O2
O2
O2
O2
O2
O
Block creation
Block proposer (or miner) chooses operations found
in his node and form a block of them.
The validator release to the network.
O1
O1
O2
O2
O2
O2
B = [ O1, O2 ]
→
B
O1
⇨ B1 = [ O1, O2 ]
→
B
B
B
B
B
B
B
B
B = [ , . . , ]Ov1
Ovm
B
Ledger Update
Each node updates its state by applying .
where
This forms a “blockchain”:
S B
= ∅S0
= ( ) = ( (. . ( ( )). . ))Sn Bn Sn−1 Bn Bn−1 B1 S0
B(S) = ( (. . ( (S)). . ))Ovm
Ovm−1
O1
B = [ , . . , ]O1 Ovm
. . . .S0 →
B1
S1 →
B2
→
Bn−1
Sn →
Bn
Cryptographic Integrity
More precisely, and are digitally signed
to avoid forgery:
where is a raw operation.
where
Digital signing and the hash function are
assumed to be secure.
O B
O = (o, sig (o))nu o
= (b, sig (b))Bn nv b = ([ , . . , ], H( ))Ov1
Ovm
Bn−1
signx H
Conflicts
Chain branches when multiple miners propose more
than one blocks:
B = [ O1, O2 ]
→
B
B →
B'
B'
B' = [ O3, O1 ]
B
B'
B B' V'
↗ →
Bn+1
Sn+1 →
Bn+2
Sn+2 →
Bn+3
Sn+3
. . →
Bn−1
Sn−1 →
Bn
Sn
↘ →
B
′
n+1
S
′
n+1
→
B
′
n+2
S
′
n+2
→
B
′
n+3
S
′
n+3
Attack: Double Spending
You can steal exchanging tokens in the both branches:
↗
↗ →
Bn+1
Sn+1 →
Bn+2
Sn+2 →
Bn+3
Sn+3
. . →
Bn−1
Sn−1 →
Bn
Sn
↘ →
B
′
n+1
S
′
n+1
→
B
′
n+2
S
′
n+2
→
B
′
n+3
S
′
n+3
↘
Proof of Work (PoW)
Blocks must be with an answer to a hash puzzle :
is generated from .
is a weak hash function.
The nodes choose the longer chain, which used more
computation power (or gathered votes):
Q
= ( , sig ( ), ) where  ( ) =Bn bn nv bn An H
′
An Qn
Qn bn
(⋅)H
′
. . →
Bn
Sn →
Bn+1
Sn+1 →
Bn+2
Sn+2 →
Bn+3
Sn+3 →
Bn+4
Sn+4
↘
B
′
n+1
S
′
n+1
→
B
′
n+2
S
′
n+2
Incentivize Miners
The cost of solving hash puzzles is covered by
rewards.
Block reward , newly minted.
Transaction fee: in ,
set and paid by the issuer of
By proposing a block , the validator can earn
r
f o = (raw operation,  f )
o
B
r + Σo∈B fo
Nakamoto Consensus
Rewards are only available in the branch. No incentive to bet on
shorter branches.
Longer branches might be overridden by shorter ones, but the
probability decreases exponentially as it grows.
User sends tokens to Exchange at to change them to USD.
Exchange pays out the USD after to User in return, when it
is sure cannot be taken over.
. . → . . →. .Sn−1 →
Bn
Sn →
Bn+1
Sn+1 →
Bn+2
→
Bn+6
Sn+6
Bn
Bn+6
Bn
51% Attack
Someone with more than 50% of computation power
can take over the chain to perform double spending.
⬇
. . → . .Sn−1 →
Bn
Sn →
Bn+1
→
Bn+6
Sn+6
. . → . .Sn−1 →
Bn
Sn →
Bn+1
→
Bn+6
Sn+6
↘ . .S
′
n−1
→
B
′
n
S
′
n →
B
′
n+1
→
B
′
n+6
S
′
n+6
→
B
′
n+7
S
′
n+7
→
B
′
n+8
S
′
n+8
51% Attacks are Real
Minor PoW blockchains, which requires less hash
power, are targets of 51% attacks:
Verge (XVG), 2M USD (2018-04 and 2018-05)
Bitcoin Gold (BTG), 18M USD (2018-05)
Monacoin (MONA), 90K USD (2018-05)
ZenCash (ZEN) 700K USD (2018-06)
Blockchain: Technical Details
Typical PoW
Operation injection
Block creation of operations, and upload
Ledger update by blocks
Branching by conflicts
PoW to reduce and choose branches
51% attacks
Proof of Stake and Tezos
PoW is Energy Inefficient
Bitcoin uses 73.12T Wh to maintain its network per year.
Which is 3.6B USD/y.
Equivalent with the electricity consumption of Austria.
Equivalent with the consumption of 6.7M households in US.
https://digiconomist.net/bitcoin-energy-consumption
Risk of Centralization
Miners tend to concentrate:
PoW is less profitable in regions with higher electricity fee.
Concentration of mining powers, i.e. mining pools, makes PoW
more efficient.
Centralization damages the network security.
Incentive Misalignment of PoW
Stakeholders and miners are largely different, and
their incentives are different.
Most of the token owners are not miners,
miners are not obliged to keep their positions in PoW.
Miners want to maximize their mining rewards. This may work
against the interests of token owners.
Proof of Stake (PoS)
PoS: Another Solution to Sybil Attack:
Block mining right based not on computation power but on the
stake (how much you have)
The past stake in the DB is fixed. Sybil attack is prevented.
Mining right is assigned only to long-term stakeholders.
51% attack is still possible, but you need to own half of the token
supply for enough long.
Raspberry PI 3, 2watts
for Tezos
PoS: Eco-Friendly + Decentralization
No competition of solving puzzles:
Mining → “Baking”
No special hardware required:
No concentration for efficiency required.
Antminer S9, 1350watts
for Bitcoin
PoS: Aligned Incentives
Miners ⊂ Stakeholders
You have to hold your position long enough
to participate the consensus.
Mining right is delegatable.
You can participate the network by delegating your
right to get some of rewards, not risking your stake.
Possible Attacks to PoS
Double spending by branching with past stake:
Nothing at stake attacks
Long range attacks
   Exchange the stake with goods
⤴ 
→ → → → →
↘ Branch using the past stake
→ → → → → Make the above chain inactive
Tezos Consensus
Countermeasures against the attacks.
For nothing at stake attacks
Endorsement
Security deposit
For nothing at stake attack
Checkpoints
Endorsement
Based on Nakamoto Consensus with endorsement.
For each block level , 32 endorsers are chosen:
Each endorse one block of and sign.
Branches with more endorsements win.
The attacker must control much more accounts.
i
Bij , . . ,Bi1 Bin
. . → . .Sn−1 →
Bn
Sn →
Bn+1
→
Bn+6
Sn+6
↘ . .S
′
n−1
→
B
′
n
S
′
n →
B
′
n+1
→
B
′
n+6
S
′
n+6
→
B
′
n+7
S
′
n+7
→
B
′
n+8
S
′
n+8
Security Deposit
Security deposit for mining and endorsement.
Branching attempt is punished by slashing the deposit and
rewards.
Double minings/endorsements in the same level
Deposit is returned when reorg becomes impossible (15 days)
  ↕ Branching attempt by the same validator is punished.
  
. . . .→
Bn−1
Sn−1 →
Bn
Sn →
Bn+1
Sn+1 →
Bn+2
. .↘
B
′
n+1
S
′
n+1
→
B
′
n+2
Checkpoints
Record block hashes periodically outside of the
chain:
     
H(B)
https://www.news.com
Tezos’s block hash at is , BKveMfA..n H( )Bn
. . → S →. . →. . →. . →. . →. . →. . → S→
Bn
Sn
     . . →. . →. . →. . →. . →. . →↘ →
B
′
n
S
′
n S
″
PoS and Tezos
PoW has energy inefficiency and incentive unalignment
PoS: Mining right proportional to the stake against Sybil attack
Eco friendly
Incentive is aligned
Attack against PoS: Branching by past stake and solutions in
Tezos (and other protocols):
Endorsements
Security deposit to prevent intentional branching
Checkpoints
Other Tezos Highlights
Other Tezos Highlights
Basic philosophy
Liquid PoS
On chain governance
Formal verification
Philosophy of Tezos
Blockchain protocol for stakeholders
Safety is the first priority
(Virtual) Pure PoS
All the stakeholders can propose blocks.
Direct democracy.
Problem: it does not scale:
Not all stakeholders can run mining facilities 27h/7d
Slowed down for waiting stakeholders without mining facilities
Delegated PoS
Blocks are proposed only by small num of delegates.
Stakeholders can vote to select delegates.
Indirect democracy.
Pros:
Highly efficient thanks to the small number of miners.
ex. EOS: 21 super nodes.
Stakeholders can receive rewards via voting.
Easier to implement consensus algorithm like PBFT.
Cons: Network get centralized: less secure.
Liquid PoS (Tezos)
All the stakeholders can propose blocks,
or they may delegate their rights to other miners.
“Protocol is owned not only by selected validators,
  but by all the stakeholders.”
Unlimited number of validators: ex. Tezos: 500 bakers
Slower than DPoS but more decentralized i.e. securer.
Stakeholders can receive rewards through delegation.
Liquid Democracy
https://medium.com/organizer-sandbox/liquid-democracy-true-democracy-for-the-21st-
century-7c66f5e53b6f
Tezos and On Chain Governance
What is Governance in Blockchain
“How to fork (upgrade) protocols?”
Soft/Hard fork
Soft fork
Backward compatible
Hard fork
Backward incompatible:
Past valid blocks may become
invalid under the new protocol.
Risk of Hard Fork
A hard fork of a protocol may cause
a hard fork of the community.
Ethereum and Ethereum Classic hard fork after DAO incident
Hard fork of Bitcoin Cash and “hash war”
Goal of the Governance
Smooth evolution of blockchain protocol
without community hard fork.
On Chain Governance
Protocol upgrade is implemented in protocol itself,
and all the processes are recorded on chain:
Protocol upgrade proposal
Test of proposal
Vote to upgrade
Automatic upgrade of nodes
Protocol defines how itself is to be upgraded.
“Protocol is owned not by developers but by
stakeholders.”
Tezos: Protocol Separation
Define the target of on chain governance:
Shell
Network, storage, etc. Not the target, since their change only
cause soft forks.
Protocol
Semantics of transactions and how to reach consensus.
The target of on chain governance, since their change triggers
hard fork.
Tezos: On Chain Governance
90 day cycle of governance:
Code of proposals uploaded
First vote: select one of them
Second vote: test it or not
Test phase
Final vote: upgrade or not
Automatic node upgrade
Liquid democracy
voting right is weighted by stakes, and delegatable just like
LPoS.
Tezos: Governance History
“Athens”: Tezos’s first protocol upgrade.
Just changes of few constant parameters.
2019-05-21: Passed the final vote
2019-05-30: Activated
“Babylon”: and
others.
2019-08-29: Passed the first 2 votes. Now in the test phase
Improved consensus algorithm
Other Tezos Highlights
Basic philosophy
Liquid PoS
On chain governance
Formal verification ← Coming soon
Formal Verification in Tezos
What is Blockchain (again)
Ledger DB
Distributed
Open network
Token for incentives
Smart contracts
Safety Requirements of Blockchain
As a consequence of introduction of token rewards
for open distributed DB:
Speculative money flows in.
System must be open source.
Security holes are immediate targets for theft.
Blockchain must have very high level of security.
Safety of Smart Contracts
Smart contracts must be also very secure.
Past incidents around smart contracts:
The DAO (3.6M ETH, 15% of circulation, 50M USD stolen)
Parity vulnerability#1 (150K ETH, 32M USD stolen)
Parity vulnerability#2 (513K ETH, 160M USD frozen)
High level of security is required here too.
The DAO
contract user {
do_deposit()
{
bank.deposit(100);
}
do_withdraw()
{
bank.withdraw();
}
}
contract bank {
deposit()
{
map[SENDER] += AMOUNT;
}
withdraw()
{
send(SENDER, map[SENDER]);
map[SENDER] = 0;
}
}
The DAO
contract attack {
do_deposit()
{
bank.deposit(100);
}
do_withdraw()
{
bank.withdraw();
}
default()
{
bank.withdraw();
}
}
contract bank {
deposit()
{
map[SENDER] += AMOUNT;
}
withdraw()
{
send(SENDER, map[SENDER]);
map[SENDER] = 0;
}
}
Blockchain is a Big Pile of Components
Protocol: consensus, incentive design, transaction semantics
Smart contract: semantics, compiler
Cryptographic algorithms
P2P networking
Storage
All of these components must be secure.
How to Secure Blockchain
Test
Important but not enough.
Formal verification
The way to go.
Software Test
Run a system under given conditions
to see everything goes fine.
Run and see, then repeat. Easy.
Testable only few corner cases
No guarantee for the untested cases.
Formal Verification
Mathematically prove programs have good/bad
properties.
Property is assured for all the cases,
if proven.
Proving is generally much harder than
tests.
Formal Verification Methods
Static typing
Model checking
Theorem proving
Static Type Checking
Express properties of values and expressions in types.
Restrict program compositions to those typable,
to assure the properties hold for the entire program.
Pros: automatic if type inference is
available.
Cons: relatively weak expressive power.
Model Checking
Abstract a program to a finite state transition system,
then check it satisfies the properties we want.
Pros: automatic. A counterexample is given at failure.
Cons: Hard to provide a good modeling.
Theorem Proving
Prove the property of program directly,
using proof assistant such as Coq:
Pros: most powerful
Cons: Writing a proof can be very hard.
Formal Verification for Blockchain
Formal verification is used for critical systems such
as:
Aerospace industry
Nuclear plants
Blockchain is also a critical system. It must be
formally verified.
It is also an ideal target of formal verification:
No hardware. Open source.
Smart contract is a programming language.
Tezos and Formal Verification
Statically typed smart contracts
both at VM and high level language levels
Modeling of smart contract interpreter using Coq,
and correctness proofs of smart contracts using it.
Correctness of cryptographic primitives
Incoming:
Correctness proof of sparse Merkle tree storage using F*.
Certified compiler of smart contracts.
etc.
Michelson: Tezos Smart Contract VM
Stack VM
Purely functional: no side effects
No mutable variables
Transactions are not side effects. Re-entrancy bug is impossible.
With strong static typing
No runtime type mismatch like "hello" + 10
Different numeric types for currency, , , ꜩ.
Arbitrary precision and . No overflow / underflow
VM level data structures: Lists, sets, maps, options
ℕ ℤ
ℕ ℤ
Michelson interpreter
Implements the semantics of Michelson in node:
Purely functional: no side effects
Secured by GADTs (Guarded Algebraic Data Types)
VM state (code and stack) construction is assured well-typed in
the VM type system.
Evaluation (state-to-state transition) preserves the well-
typedness.
Mi-Cho-Coq: VM modeling in Coq
Michelson is reimplemented in Coq proof assistant.
Provides framework to prove correctness around Michelson.
Found documentation bugs in the specification.
https://gitlab.com/nomadic-labs/mi-cho-coq/
Smart Contract Correctness Proofs
Using Mi-Cho-Coq.
例:
An operation to the account is performed only when enough
number of signatures of registered users are attached.
multi-sig contract
https://gitlab.com/nomadic-labs/mi-cho-coq/blob/master/src/contracts_coq/multisig.v
HACL*: Verified Cryptography
Formally verified cryptographic functions in F*.
ChaCha20, Salsa20, HMAC, SHA-256, SHA-512, Ed25519, etc.
F* compiles down to fast C code.
Properties proved:
Memory safety
Correctness of the algorithm
Secret independence: immune to the side channel attacks
https://github.com/project-everest/hacl-star
F*
Functional language with refinement types,
developed by Microsoft:
Compatible syntax with OCaml
Some verifications can be done automatically by Z3
Extraction to OCaml, F#, C, WASM, ASM
https://www.fstar-lang.org/
On Going Projects
They are just I know so far:
Sparse Merkle tree for storage.
The correctness of tree operations will be verified by F*
Certified compiler of smart contract
Prove the correctness of compilation from higher level language
to Michelson
DSL for contracts in Tezos. Verification using deductive
program verification platform.
Plebeia
Archetype
Why3
Tezos and Formal Verification
Blockchain is a critical system.
Test is important, but FV is also required.
All components should be verified.
Tezos is a very good target to perform FV.
Tezos Hands on
Calicurum
Preparation
Docker images install
Git repository
Basic transaction
Try tezos­client
Account creation
Token transactions
Introduction to smart contract
Basic concepts of Tezos smart contracts
compiler
Contract compilation, deploy, and call
LIGO
Preparation
Prep #1: Docker and images
Install
Linux users: configure so that you can run docker command
without sudo: ( )
Install 2 docker images
Check images are working:
Docker
details
$ docker pull dailambda/tezos­handson:2019­08 ↩  
$ docker pull dailambda/ligo:2019­08 ↩ 
$ docker run dailambda/tezos­handson:2019­08 ↩  
hello tezos 
$ docker run dailambda/ligo:2019­08 ↩  
hello tezos
Prep #2: Clone Git repository
Contents
tezos­handson­node
A sandboxed node for hands-on
tezos­client
. You can do everything with it.
ligo
compiler
contracts/
Camligo contract samples
$ git clone https://gitlab.com/dailambda/docker­tezos­hands­on ­
b tezos­hands­on­2019­08 ↩  
$ cd docker­tezos­hands­on ↩ 
Command line wallet
LIGO
If you dare want to build Docker
images…
Sources are available in
docker­node/ and docker­ligo/ of the repo.
Are You Ready?
Usual Tezos Development…
We usually start a Tezos node connecting to the test
network called “Alpha net”:
↪↪
Tezos Network
But it takes time to sync your node to the network…
Today, We Use Sandbox
↪↪
Closed in your computuer. No external net access required.
No need to sync with the test/main network.
No need to buy real Tezos tokens.
You can reset the environment easily.
Sandboxed Environment for Hands-on
Let’s start it:
and keep it running.
Note: The node uses TCP port 18732.
Reset, if something goes wrong:
$ ./tezos­handson­node ↩ 
# Stop tezos­handson­node, then  
$ rm ­rf .tezos­handson­node .tezos­handson­client ↩  
$ ./tezos­handson­node
Start-up Example
$ ./tezos­handson­node  
Starting /home/tezzy/tezos//tezos­node run ­­data­dir 
/home/tezzy/.tezos­handson­node ­­no­bootstrap­peers ­­private­
mode ­­sandbox /home/tezzy/.tezos­handson­node/sandbox.json ­­
connections=0 
Waiting the node startup... 
Aug 20 05:15:37 ­ node.main: Starting the Tezos node... 
.. 
Aug 20 05:15:38 ­ node.main: The Tezos node is now running! 
Node is up. 
Activating Alpha protocol... 
.. 
Injected BLChsc7x64kH
Check it is working
Open a new terminal, then:
$ ./tezos­client bootstrapped ↩  
Current head: BLNeoW9n94mD (timestamp: .. 
Bootstrapped.
ICO Commitments
Tezos fundraiser donors receive commitment
information to activate their Tezos accounts in
Mainnet.
In this hands-on, 2 dummy commitment files are
prepared:
$ ls commitments/ 
tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF.json 
tz1X4maqF9tC1Yn4jULjHRAyzjAtc25Z68TX.json
Account Activation
Careful of typo.
tz1xx..xx is the name (public key hash) of the account.
alice is an alias, which you can choose what ever you want.
It may take several ten seconds.
$ ./tezos­client activate account alice with  
     commitments/tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF.json ↩  
.. 
Operation successfully injected in the node. 
.. 
The operation has only been included 0 blocks ago. 
.. 
Account alice (tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF) activated 
with ꜩ27182818.28459.
What Happend?!
I do explain.
$ ./tezos­client activate account alice with 
commitments/tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF.json  
Node is bootstrapped, ready for injecting operations. 
Operation successfully injected in the node. 
Operation hash is 
'oo6rb94mw9Z4rKexQhYDnSZeXXWmcZ65vcz77KTDTcGstYYeeuC' 
Waiting for the operation to be included... 
Operation found in block: 
BKqArov5fNKzptY81CLsacSTTPh7tPmCXoqeQ4pNzKCP6GtGiro (pass: 2, 
offset: 0) 
This sequence of operations was run: 
  Genesis account activation: 
    Account: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... +ꜩ20000000 
1. Check the connected node
The node must be well sync’ed with the network:
The sandbox is always bootstrapped, so no problem.
Node is bootstrapped, ready for injecting operations.
→
→
O1
O1
O1
O1
O1
O1
O2
O2
O2
O2
O2
O2
O2
O2
2. Inject the operation to the network
Operation ooyyy..yyy for the
account activation was injected
to the network:
Waiting the operation is taken for a new block.
Operation successfully injected in the node. 
Operation hash is 'ooyyy..yyy' 
Waiting for the operation to be included...
B1 = [ O1, O2 ]
→
B
B
B
B
B
B
B
B
3. The Op. is now in a new block
There is a validator in the sandbox.
Detected the validator took the
operation and made a new block
Bzzz..zzz:
tz1Mawer.. registered in the genesis block is now
activated.
Operation found in block: Bzzz..zzz (pass: 2, offset: 0) 
This sequence of operations was run: 
  Genesis account activation: 
    Account: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... +ꜩ20000000
4. You may wait for more blocks.
The block may be still overridden by the consensus.
Under Nakamoto consensus, longer you wait, the
certainity incrases exponentially.
In this hands-on, there is no point to wait.
The operation has only been included 0 blocks ago. 
We recommend to wait more. 
Use command 
  tezos­client wait for 
oo6rb94mw9Z4rKexQhYDnSZeXXWmcZ65vcz77KTDTcGstYYeeuC to be 
included ­­confirmations 30 ­­branch 
BL26XEjqN4uKAnEC52z6ijj3XibpbcM4ysPLUfcJqkMccyHriV3 
and/or an external block explorer. 
Account alice (tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF) activated 
with ꜩ20000000.
Operation Processing in Tezos
The same as we saw for the activation:
Make an operation.
Upload the operation to the P2P network.
A validator makes a block with the operation.
The block is uploaded to the P2P network.
The certainity of the operation increases as the chain grows.
Account Query
How much do I have?
Ask the blockchain:
alice is an alias of
tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF.
Therefore,
$ ./tezos­client get balance for alice ↩  
20000000 ꜩ
$ ./tezos­client get balance for 
tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ↩  
20000000 ꜩ
Balance of the others
Tezos accounts are not anonymous.
You can check the balance of other’s. For example,
tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV:
Hard to type? The account name is found in file
accounts.txt:
$ ./tezos­client get balance for  
      tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ↩  
0.000001 ꜩ
$ cat accounts.txt ↩  
tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV
Account Alias
You can give an alias to an account:
$ ./tezos­client add address jun  
        tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ↩  
 
$ ./tezos­client get balance for jun ↩  
0.000001 ꜩ
Accounts known by tezos­client
alice’s secret key (sk) is known. It is your account.
jun’s secret key is not available. It is not yours.
Keep your secret key secret!!
Once known, your account is owned by others.
$ ./tezos­client list known addresses ↩  
jun: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLq.. 
alice: tz1MawerETND6bqJqx8GV3YHUrvMBCD.. (unencrypted sk known)
Sending tokens
Send some to jun
Thanks! It prints lots:
I do explain.
$ ./tezos­client transfer 100 from alice to jun ↩ 
$ ./tezos­client transfer 100 from alice to jun ↩  
Node is bootstrapped, ready for injecting operations. 
Estimated gas: 10200 units (will add 100 for safety) 
Estimated storage: no bytes added 
Operation successfully injected in the node. 
Operation hash is 'ooJZ1U114ibPfikZNrDSfmqg8Tcs9CzshL4w1vvsDa35DdB72bN' 
Waiting for the operation to be included... 
Operation found in block: BL6H8145DMyPeXBQBc2JPRKpVstJSYkhgyGSFFhEJQGAfYweQ8u (pass: 3, offset: 0) 
This sequence of operations was run: 
  Manager signed operations: 
    From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Fee to the baker: ꜩ0.001258 
    Expected counter: 1 
    Gas limit: 10000 
    Storage limit: 0 bytes 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001258 
      fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001258 
    Revelation of manager public key: 
      Contract: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      Key: edpkuSR6ywqsk17myFVRcw2eXhVib2MeLc9D1QkEQb98ctWUBwSJpF 
      This revelation was successfully applied 
      Consumed gas: 10000 
  Manager signed operations: 
    From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Fee to the baker: ꜩ0.001186 
    Expected counter: 2 
    Gas limit: 10300 
    Storage limit: 0 bytes 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001186 
      fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001186 
    Transaction: 
      Amount: ꜩ100 
      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      To: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV 
      This transaction was successfully applied 
      Consumed gas: 10200 
      Balance updates: 
        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ100 
        tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ... +ꜩ100 
 
The operation has only been included 0 blocks ago. 
We recommend to wait more. 
Use command 
  tezos­client wait for ooJZ1U114ibPfikZNrDSfmqg8Tcs9CzshL4w1vvsDa35DdB72bN to be included ­­confirmations 30 ­­branch BLpBxE6wFBQcvNPyUg7sdodpZN3Xra2qGAAJXPG7Z7i9EM94ivj 
and/or an external block explorer.
1. Check the connected node
Waiting for the node to be bootstrapped before injection... 
Current head: BL.. (timestamp: .., validation: ..) 
Node is bootstrapped, ready for injecting operations.
2. Gas estimation
    and operation injection
Estimated gas: 10200 units (will add 100 for safety) 
Estimated storage: no bytes added 
Operation successfully injected in the node. 
Operation hash is 'oOOO..OOO' 
Waiting for the operation to be included...
3. The operation is now in a new block
Let’s see more details here.
Operation found in block: BL6H8145DMyPeXBQBc2JPRKpVstJSYkhgyGSFFhEJQGAfYweQ8u (pass: 3, offset: 0) 
This sequence of operations was run: 
  Manager signed operations: 
    From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Fee to the baker: ꜩ0.001258 
    Expected counter: 1 
    Gas limit: 10000 
    Storage limit: 0 bytes 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001258 
      fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001258 
    Revelation of manager public key: 
      Contract: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      Key: edpkuSR6ywqsk17myFVRcw2eXhVib2MeLc9D1QkEQb98ctWUBwSJpF 
      This revelation was successfully applied 
      Consumed gas: 10000 
  Manager signed operations: 
    From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Fee to the baker: ꜩ0.001186 
    Expected counter: 2 
    Gas limit: 10300 
    Storage limit: 0 bytes 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001186 
      fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001186 
    Transaction: 
      Amount: ꜩ100 
      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      To: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV 
      This transaction was successfully applied 
      Consumed gas: 10200 
3.1 Revealation the public key
The public key edpkuSR6ywqsk.. of alice must be
revealed to the blockchain, so that others can verify
alice’s operation with it:
  Manager signed operations: 
    From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Fee to the baker: ꜩ0.001258     Fee to the validator 
    Expected counter: 1 
    Gas limit: 10000 
    Storage limit: 0 bytes 
    Balance updates:        Fee is paid to the validator. 
      tz1MawerETND6bqJqx8GV3YHUrvM ........... ­ꜩ0.001258 
      fees(tz1ddb9NMYHZi5UzPdzTZMY95zgv,6) ... +ꜩ0.001258 
    Revelation of manager public key: 
      Contract: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      Key: edpkuSR6ywqsk17myFVRcw2eXhVib2MeLc9D1QkEQb98.. 
      This revelation was successfully applied 
      Consumed gas: 10000
3.2 The transaction
  Manager signed operations: 
    From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Fee to the baker: ꜩ0.001186                Fee to the validator 
    Expected counter: 2 
    Gas limit: 10300 
    Storage limit: 0 bytes 
    Balance updates:                  Fee is paid to the validator. 
      tz1MawerETND6bqJqx8GV3YHUrvM ........... ­ꜩ0.001186 
      fees(tz1ddb9NMYHZi5UzPdzTZMY..zgv,6) ... +ꜩ0.001186 
    Transaction: 
      Amount: ꜩ100                    The amount of the transaction 
      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      To: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV 
      This transaction was successfully applied 
      Consumed gas: 10200 
      Balance updates: 
        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ100   alice pays 
        tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ... +ꜩ100   to jun
4. You may wait for more blocks.
The operation has only been included 0 blocks ago. 
We recommend to wait more. 
Use command 
  tezos­client wait for ooZZZ..ZZZ to be included ­­
confirmations 30 ­­branch B.. 
and/or an external block explorer.
Check the balance
The token was really transferred? Check it:
The balance of alice should decrease by 100tz + the
fee paid for the validator.
$ ./tezos­client get balance for alice ↩  
19999899.997556 ꜩ 
$ ./tezos­client get balance for jun ↩  
100.000001 ꜩ
You cannot steal jun’s token
Since you do not know his secret key:
alice’s secret key is known by tezos­client.
It is stored in .tezos­handson­client:
$ ./tezos­client transfer 100 from jun to alice ↩  
Error: 
  Unknown secret key for tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV
$ cat .tezos­handson­client/secret_keys ↩  
[ { "name": "alice", 
    "value": "unencrypted:edsk3NDQq5Cmix9H15GkcoVhWo.." } ]
Gas, Storage, and Fee of Tezos
Who wants to issue opreations in Tezos must propose:
Cost Estimation
Gas limit
How much CPU power is required.
Storage limit
How much additional storage is required.
Incentive to the validator
Fee
Paid by the issuer to the validator, if the op. is taken into the new
block.
What Validator Does
Compare the cost estimation and the fee:
Fee > Cost estimation
Take the operation into the new block to receive the fee.
Cost estimation > Fee
Operation will not be used for the new block.
Operation issuer should:
Propose proper fee
Operations with too low fee are never taken into the blockchain.
Should not cheat the validator with too low cost estimate
The operation fails and the fee is taken by the validator,
if actual operation cost exceeds the estimate.
Build your new account
Create a pair of secret and public keys. Easy:
$ ./tezos­client gen keys alice2
$ ./tezos­client list known addresses 
alice2: tz1M9ZZccgEAgtDGMu8R7xniFt.. (unencrypted sk known) 
jun: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV 
alice: tz1MawerETND6bqJqx8GV3YHUrv.. (unencrypted sk known)
Burn: fee to add storage
Sending from alice to alice2 10000ꜩ fails:
Additional storage is required to record the new
account to the blockchain. 0.257ꜩ is required to burn.
$ ./tezos­client transfer 10000 from alice to alice2 
Fatal error: 
  The operation will burn ꜩ0.257 which is higher than the 
configured burn cap (ꜩ0). 
   Use `­­burn­cap 0.257` to emit this operation. 
Exiting
$ ./tezos­client transfer 10000 from alice to alice2  
      ­­burn­cap 0.257 
... 
      Balance updates: 
        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ10000 
        tz1cMEsG9mvL8zyiGHppcCjcz1Et65zwidfg ... +ꜩ10000 
        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ0.257   Burn
Smart Contract
How Tezos Smart Contracts Work
Accounts KTxxx..xxx can have smart contracts.
Contract state
Balance
Code
Persistent storage
Trigger
Code is executed at each transaction to the contract.
Tezos Contract is Pure Function
Input
Parameter given at the transaction.
Storage contents
Global constants
(current account balance, amount of the transaction, the source of the transaction, etc)
Output
Operations (transactions, call of other smart contracts, etc.)
New storage contents
No side effects
Immutable. Purely functional.
Michelson
for Tezos smart contracts, and its language.
VM but high level:
Statically typed
, with arbitrary precision. No overflow.
Data types (options, lists, sets, map)
Cryptographic primitives
But bit hard to read and write…
Stack VM
 
# Return to the source 
 
parameter unit; 
storage unit; 
 
code { 
       CDR ; 
       NIL operation ; 
       AMOUNT; 
       PUSH mutez 0; 
       IFCMPEQ 
         { } 
         { 
           SOURCE ; 
           CONTRACT unit ; 
           ASSERT_SOME ; 
           AMOUNT ; 
           UNIT ; 
           TRANSFER_TOKENS ; 
           CONS ; 
         }; 
       PAIR; 
     } 
 
ℕ ℤ
CameLIGO
Today, we use
high level language for Tezos smart contracts.
Compiler
LIGO code is compiled down to Michelson
2 syntaxes
PascaLIGO (Pascal like) and CamLIGO (OCaml like)
Cheat sheet and samples
Samples are under ./contracts
Still very new and glitchy, but already usable.
LIGO(http://ligolang.org)
https://gitlab.com/dailambda/mligo_contracts/blob/master/cheat-sheet.md
Disclaimer
to talented OCaml programmers
CamLIGO is not OCaml.
No recursions: let rec
Type inference is not fully automatic: ([] : int list)
Pattern match is not real pattern match.
No nested patterns: Some (Some x)
No constants in patterns. 1::[]
The First CamLIGO Contract
Replace the storage by the parameter string:
Puzzled?
Relax. I do explain.
let main (parameter : string) (storage : string) = 
  ( ([] : operation list),  parameter )
Function Definition
Arguments must be type-annotated:
(parameter : string)
Arguments are white space separated:
let f (x : ty1) (y : ty2) = ..
❌let f ( (x : ty1), (y : ty2) ) = ..
let function_name (arg1 : type1) ... (argn : typen) = 
  code
let main (parameter : string) (storage : string) = 
  ( ([] : operation list),  parameter )
Contract Entrypoint
A function with 2 arguments of:
Parameter: here, parameter
Storage value: here, storage
returns a tuple (..., ...) of:
List of operations: here, empty: [] (with type annotation)
New storage value: here, parameter
let main (parameter : string) (storage : string) = 
  ( ([] : operation list),  parameter )
Compilation
Place the contract code at contracts/first.mligo
Specify the entrypoint function name main
If you made no mistake, the code should be compiled
down to a Michelson code contracts/first.tz.
$ ./ligo compile­contract contracts/first.mligo main ↩ 
let main (parameter : string) (storage : string) = 
  ( ([] : operation list),  parameter )
Look of Michelson Code
Puzzled?
No worry, I do not explain.
{ parameter string ; 
  storage string ; 
  code { {} ; 
         { { { { DUP } ; CAR } ; 
             { { { { DIP { DUP } ; SWAP } } ; CDR } ; 
               { { { DIP { DUP } ; SWAP } ; NIL operation } ; PAIR } ; 
               {} ; 
               DIP { { DIP { DIP { DIP { {} } } } ; DROP } } } ; 
             {} ; 
             DIP { { DIP { DIP { {} } } ; DROP } } } ; 
           DIP { { DIP { {} } ; DROP } } } } }
Contract Deployment
first: Alias of the contract
for alice: Manager is alice
transferring 0 from alice: Initial balance is 0 paid by alice
running contracts/first.tz: The Michelson code
­­init '"initial value"': The initial storage value
­­burn­cap 0.506: For registration network fee
$ ./tezos­client originate contract  
        first for alice  
        transferring 0 from alice  
        running contracts/first.tz  
        ­­init '"initial value"'  
        ­­burn­cap 0.506 ↩ 
Did not work for you?
Few things you should check:
Check typo
Your account alias is alice?
Quotes are important: '"initial value"'
Got "Error: At line 1 character 0, blahblah
Limitation of Docker.
Please place first.tz under the directory with ligo.
Got “Fatal error” about the burn cap? Asked more?
Longer initial storage string costs you more.
If you are successful
I do explain.
$ ./tezos­client originate contract first for alice transferring 0 from alice running contracts/first.tz ­­init '"initial value"' ­­burn­cap 0.506 ↩  
Node is bootstrapped, ready for injecting operations. 
Estimated gas: 16275 units (will add 100 for safety) 
Estimated storage: 506 bytes added (will add 20 for safety) 
Operation successfully injected in the node. 
Operation hash is 'ooe54u2xReWTmbV6eWeKZf3SbWNRMGcFdyuVKDU5UpjYtM1EVDU' 
Waiting for the operation to be included... 
Operation found in block: BLCmgqwqMShuD38WYFabrD8o8XRf9Xp7W5ZyUkjQYYiK7ULF8qv (pass: 3, offset: 0) 
This sequence of operations was run: 
  Manager signed operations: 
    From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
    Fee to the baker: ꜩ0.002139 
    Expected counter: 3 
    Gas limit: 16375 
    Storage limit: 526 bytes 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ............ ­ꜩ0.002139 
      fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,10) ... +ꜩ0.002139 
    Origination: 
      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      For: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      Credit: ꜩ0 
      Script: 
        { parameter string ; 
          storage string ; 
          code { {} ; 
                 { { { DUP ; CAR } ; 
                     { { { DUUP } ; CDR } ; 
                       { { DUUP ; NIL operation } ; PAIR } ; 
                       {} ; 
                       DIP { { DIP { DIP { DIP { {} } } } ; DROP } } } ; 
                     {} ; 
                     DIP { { DIP { DIP { {} } } ; DROP } } } ; 
                   DIP { { DIP { {} } ; DROP } } } } } 
        Initial storage: "initial value" 
        No delegate for this contract 
        This origination was successfully applied 
        Originated contracts: 
          KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS 
        Storage size: 249 bytes 
        Paid storage size diff: 249 bytes 
        Consumed gas: 16275 
        Balance updates: 
          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ0.249 
          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ0.257 
 
New contract KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS originated. 
The operation has only been included 0 blocks ago. 
We recommend to wait more. 
Use command 
  tezos­client wait for ooe54u2xReWTmbV6eWeKZf3SbWNRMGcFdyuVKDU5UpjYtM1EVDU to be included ­­confirmations 30 ­­branch BLTSxQK35VsHuFpvyFJRWkcvxZi2CEmigLvc3FWBarDPXZrFAEP 
and/or an external block explorer. 
Contract memorized as first.
Deploy Result
Gas limit: 16374, Storage limit 526 bytes
Proposing fee to the validator: ꜩ0.002139
The contract is owned by alice (tz1Mawer..)
The initial balance (credit) is ꜩ0
Michelson code and the initial value "initial value"
The originated contract address is KT1NmLBE..
Actual cost: Gas: 16275, Storage: 249 bytes
Network fee for the new storage: ꜩ0.249
Network fee for the contract origination: ꜩ0.257
The wallet knows the new contract
Not addresses but contracts this time.
$ ./tezos­client list known contracts ↩  
first: KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS 
jun: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV 
alice: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF
Check the state of the contract
$ ./tezos­client get script code for first ↩  
{ parameter string ; 
  storage string ; 
  code { .. } } 
 
$ ./tezos­client get script storage for first ↩  
"initial value" 
 
$ ./tezos­client get balance for first ↩  
0 ꜩ
Call the Smart Contract
Same as the simple transaction we did,
but specify the parameter with ­­arg
$ ./tezos­client transfer 0 from alice to first  
     ­­arg '"hello"' ↩  
.. 
    Transaction: 
      Amount: ꜩ0 
      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF 
      To: KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS 
      Parameter: "hello" 
      This transaction was successfully applied 
      Updated storage: "hello" 
      Storage size: 241 bytes 
      Consumed gas: 15762 
..
Did not work for you?
Check typo
Your account alias is alice?
Commands are designed intentionally long to avoid mistakes.
Got “Fatal error” about the burn cap?
Extending the storage size costs you:
$ ./tezos­client transfer 0 from alice to first  
    ­­arg '"I am creative and give a very long string!"' ↩  
Fatal error: 
  The operation will burn ꜩ0.029 which is higher than the 
configured burn cap (ꜩ0). 
   Use `­­burn­cap 0.029` to emit this operation.
Let’s check the result
$ ./tezos­client get script storage for first ↩  
"whatever you sent" 
 
$ ./tezos­client get balance for first ↩  
100 ꜩ       Non 0 if you transfer some tokens.
Congratulations!
You are now a Tezos engineer.
Smarter Contracts
Returning Operations
By returning non empty operation list, smart
contracts can send tokens to other addresses, and call
other smart contracts.
Smarter Contracts: Boomerang
If someone sends non-zero token, return it to the
source. Otherwise, do nothing.
Function arguments:
Storage: nothing
Parameter: nothing
In ML, we use type unit for the type of no specific
data. () is the value of the type: ( () : unit )
Smarter Contracts: Global Constants
Global constants to use:
amount: The amount of transaction
source: The address which initiated the transaction.
Smater Contracts: functions for ops.
Functions to create operations:
Operation.transaction
: 'a ­> tez ­> 'a contract ­> operation
Transfer token to the specified contract with a parameter,
ex. Operation.transfer () 10tz contract
Operation.get_contract
: address ­> _ contract Obtain the contract of the given
address.
Type annotation is required to specify the contract type.
ex. (Operation.get_contract adrs : unit contract)
Smater Contracts: Boomelang
Conditional
if e1 then e2 else e3
Non empty list
[ 1 ; 2 ; 3 ]
Local definition
let v = e1 in e2    Bind the result of e1 to variable v.
let main (param : unit) (storage: unit) = 
  let ops =  
    if amount = 0tz then  
      ([] : operation list)  
    else  
      [ Operation.transaction () amount  
          (Operation.get_contract source : unit contract) ] 
  in 
  ( ops, () ) 
Compile+Deploy
$ ./ligo compile­contract contracts/boomerang.mligo main 
 
$ ./tezos­client originate contract boomerang for alice  
    transferring 0 from alice running contracts/boomerang.tz  
    ­­burn­cap 0.745
Then Call!
Check the token was returned to alice.
$ ./tezos­client transfer 10 from alice to boomerang 
    Balance updates: 
      tz1MawerETND6bqJqx8GV3YHUrvMBCD.. ............ ­ꜩ0.004347 
      fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoM95zgv,15) ... +ꜩ0.004347 
    Transaction: 
      .. 
      Balance updates: 
        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ10 
        KT1Lw7gDyYr2MFUVJLyA2sQuCSjsc1krcAkb ... +ꜩ10 
    Internal operations: 
      Transaction: 
        .. 
        Balance updates: 
          KT1Lw7gDyYr2MFUVJLyA2sQuCSjsc1krcAkb ... ­ꜩ10 
          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... +ꜩ10 
Advanced Excersize
Simple banking: bank
Parameter type
unit
Storage type
Table of deposits, (address, tez) map: you can lookup the
balance of each address.
Behaviour
If transaction amount is not 0tz, update the sender’s balance in the map.
If amount is 0tz, send the balance of the sender recorded in the map. Then,
reset the balance of sender of the map.
Hints
を参考に。
Global constants
amount, sender
The transferred amount is 0 or not:
amount = 0tz かamount <> 0tz
Map operations:
Map.find_opt, Map.update, Map.remove
Branching by the result of Map.find_opt:
Use pattern match:
match result with None ­> .. | Some tez ­> ..
./contracts/cheat-sheet.md
Hints
Deployment
You can give the initial empty map value by ­­init '{}'
Call
You will need ­­burn­cap when the call makes the size of map
Yet Another Advanced Excersize
The DAO attack used a contract attacker with the
following behavior:
The initial balance is 100tz
If received 0tz, transact 10tz to bank
If received non 0tz,
If its balance exceeds 200tz, do nothing.
Otherwise, transact 0tz to bank
If transactions are implemented as function calls (in
Ethereum), attacker can steal tokens from bank
more than attacker’s deposit. Is the same possible
in Tezos?

Blockchain and Formal verification (English)

  • 1.
    Blockchain and Smart Contract Verification TezosJapan, DaiLambda, Inc. Jun FURUSE/古瀬淳, Taipei, 2019-08-29FLOLAC’19
  • 2.
    Bit of myself:Past OCaml researcher and programmer Studied type system of FP Like Haskell too FP in Financial Systems Derivative modeling HFT(High Frequency Trading) systems
  • 3.
    Bit of myself:Now NPO to promote Tezos technology in Japan. A small company to participate Tezos core development.
  • 4.
    Bit of Tezos 3rdgen. cryptocurrency (1st: Bitcoin, 2nd: Ethereum, 3rd: many) Consensus algorithm: Proof of Stake On Chain Governance Symbol ꜩ Written in OCaml Formal verification
  • 5.
    Today’s Agenda Brief Historyof Currency What is Blockchain? Technical Aspects of Blockchain Proof of Stake Bit more about Tezos Blockchain and Formal Verification
  • 6.
  • 7.
    Brief History ofCurrency Main theme: “How to trade smoothly?”
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
    Conditions for Currencies Scaleof value (comparison of values) Means of exchange (easy to carry) Means of store of value (never rotten)
  • 13.
    Coins Mintable: Governments cancontrol the money supply. China, 800 BC (刀貨, 布貨) Coins have built-in values as precious metal. Seigniorage vs counterfait
  • 14.
    Convertible Paper Money Easierto carry Assured conversion to gold (or silver, copper) Total supply is limited to the government’s gold stock ⇄ The medium of the currency has no built-in value. → More strict anti-counterfait requirements
  • 15.
    The First ConvertiblePaper Money 交子in China, around 1050 Started as private notes for iron coins. 宋dynasty assured the conversion between copper coins.
  • 16.
    Credit This is notcurrency, but optimized trade efficiency by recording credit/debt using numbers.
  • 17.
    Fiat Money Inconvertible!「法定通貨」 Since 1971,at the end of . No more support by precious metal, but money stayed as money. Confusions led to floating exchange rate system. Governments can control their money supply. Economy has boosted with more liquidity of currencies. Bretton Woods Agreements
  • 18.
    The First FiatMoney 交子in China, around 1050, again. The world first convertible paper money … and soon became the world first fiat … and lost its value since too many were printed.
  • 19.
    Electronic Money No moremedium. Just numbers in electrons. Pegged with government currencies. Very centralized. Manager companies are responsible for conversion. Cryptography to prevent forgery and cheating.
  • 20.
    The Basis ofthe Value of Currencies Less and less: The value of the medium: Nothing Convertible with precious metal: No The physical form as fiat: No What Makes Money as Money?
  • 21.
    Chartalism Means of payingtax You have to pay tax or you get arrested.
  • 22.
    Radical Theory: CommonKnowledge Common knowledge that it is money. With it, no need of centralized power!! Iraqi Swiss dinar (1993-2003) Somali shillings (1990’s)
  • 23.
    Rise of Cryptocurrencies Since2009-01-03 (Bitcoin): Electronic Decentralized: no central bank Cryptography to prevent counterfait and cheating
  • 24.
    Tracking vs Privacy Electronicmoney made tracking much easier. Powers love tracking. Public do not like being tracked. Nowadays, anonymity is another important condition of currencies. https://twitter.com/maryhui/status/1138675837165641733
  • 25.
  • 26.
    What is Blockchain? Let’sforget currency for now: Ledger style DB Distributed Open network Token Smart contracts
  • 27.
    Ledger Style DB DBby history accumulation B1 → B2 → B3 → B4 → .. S0 = ∅ S1 = B1(S0) Sn = Bn(Sn-1) = Bn(Bn-1(..(B1(S0)))) Examples Bankbook Version control system: Git
  • 28.
    Distributed DB Multiple DBnodes, each carries a replica of the DB: Fault tolerance Load balancing
  • 29.
    Distributed DB: conflicts Howto resolve conflicts? B →→ A x = A x = A x = A →→x = B x = B x = A x = B or ? ? ?
  • 30.
    Consensus Algorithm Algorithm toresolve conflicts between nodes. Bad news: There is no such algorithm [FLP85]. Every protocol has the possibility of non termination, even with only one faulty node.
  • 31.
    Good news: Paxos Itmay not terminate, but practically it is OK. Voting between nodes Only for closed network with fixed nodes.
  • 32.
    Closed Network If youare happy with it, you do not need “Blockchain”.
  • 33.
    Open Network Permissionless publicnetwork, where anyone can join with a node. Decentralized, therefore neutral Almost impossible to hack Low cost
  • 34.
    Problem of OpenNetwork Consensus Consensus control and inhibition by Sybil attack: produces fake identities to dominate the network.
  • 35.
    Satoshi Nakamoto andBitcoin Prevent Sybil attacks i.e. infinite identity creations: Requirement of real world resource: computation power (PoW) Rewards: incentive to provide the resource and behave honestly. The rewards are recorded in the DB. Birth of cryptocurrency
  • 36.
    Cryptocurrencies A solution toSybil attacks against open networks.
  • 37.
    Smart Contracts Ledger DBcan carry not only account balance, but any data, even program code. Code attached to an account is executed when it receives a transaction. Automatic execution of financial/non-financial contracts Distributed application (dAPPs) framework, neutral and cost efficient without requirement of central DB managers.
  • 38.
    Gas cost Smart contractscannot run infinitely. To prevent DoS attacks, the caller must pay the running cost to the miner: Gas limit, out of gas Contract calls fail if its runtime cost exceeds the declared gas cost or the system gas limit. VM model To calculate the gas cost, smart contract language is often implemented as a VM.
  • 39.
    What is Blockchain LedgerDB Distributed Open network Token for incentives Smart contracts
  • 40.
  • 41.
    Blockchain Network P2P networkwith multiple nodes, each has a replica of the ledger DB.
  • 42.
    Reading from theDB Query past / current state of the ledger to a node. ! ? → ? ! →
  • 43.
    Writing to theDB Sending operation to a node: Transactions Account creations, etc Operations spread into the P2P network. → → O1 O1 O1 O1 O1 O1 O2 O2 O2 O2 O2 O2 O2 O2 O
  • 44.
    Block creation Block proposer(or miner) chooses operations found in his node and form a block of them. The validator release to the network. O1 O1 O2 O2 O2 O2 B = [ O1, O2 ] → B O1 ⇨ B1 = [ O1, O2 ] → B B B B B B B B B = [ , . . , ]Ov1 Ovm B
  • 45.
    Ledger Update Each nodeupdates its state by applying . where This forms a “blockchain”: S B = ∅S0 = ( ) = ( (. . ( ( )). . ))Sn Bn Sn−1 Bn Bn−1 B1 S0 B(S) = ( (. . ( (S)). . ))Ovm Ovm−1 O1 B = [ , . . , ]O1 Ovm . . . .S0 → B1 S1 → B2 → Bn−1 Sn → Bn
  • 46.
    Cryptographic Integrity More precisely,and are digitally signed to avoid forgery: where is a raw operation. where Digital signing and the hash function are assumed to be secure. O B O = (o, sig (o))nu o = (b, sig (b))Bn nv b = ([ , . . , ], H( ))Ov1 Ovm Bn−1 signx H
  • 47.
    Conflicts Chain branches whenmultiple miners propose more than one blocks: B = [ O1, O2 ] → B B → B' B' B' = [ O3, O1 ] B B' B B' V' ↗ → Bn+1 Sn+1 → Bn+2 Sn+2 → Bn+3 Sn+3 . . → Bn−1 Sn−1 → Bn Sn ↘ → B ′ n+1 S ′ n+1 → B ′ n+2 S ′ n+2 → B ′ n+3 S ′ n+3
  • 48.
    Attack: Double Spending Youcan steal exchanging tokens in the both branches: ↗ ↗ → Bn+1 Sn+1 → Bn+2 Sn+2 → Bn+3 Sn+3 . . → Bn−1 Sn−1 → Bn Sn ↘ → B ′ n+1 S ′ n+1 → B ′ n+2 S ′ n+2 → B ′ n+3 S ′ n+3 ↘
  • 49.
    Proof of Work(PoW) Blocks must be with an answer to a hash puzzle : is generated from . is a weak hash function. The nodes choose the longer chain, which used more computation power (or gathered votes): Q = ( , sig ( ), ) where  ( ) =Bn bn nv bn An H ′ An Qn Qn bn (⋅)H ′ . . → Bn Sn → Bn+1 Sn+1 → Bn+2 Sn+2 → Bn+3 Sn+3 → Bn+4 Sn+4 ↘ B ′ n+1 S ′ n+1 → B ′ n+2 S ′ n+2
  • 50.
    Incentivize Miners The costof solving hash puzzles is covered by rewards. Block reward , newly minted. Transaction fee: in , set and paid by the issuer of By proposing a block , the validator can earn r f o = (raw operation,  f ) o B r + Σo∈B fo
  • 51.
    Nakamoto Consensus Rewards areonly available in the branch. No incentive to bet on shorter branches. Longer branches might be overridden by shorter ones, but the probability decreases exponentially as it grows. User sends tokens to Exchange at to change them to USD. Exchange pays out the USD after to User in return, when it is sure cannot be taken over. . . → . . →. .Sn−1 → Bn Sn → Bn+1 Sn+1 → Bn+2 → Bn+6 Sn+6 Bn Bn+6 Bn
  • 52.
    51% Attack Someone withmore than 50% of computation power can take over the chain to perform double spending. ⬇ . . → . .Sn−1 → Bn Sn → Bn+1 → Bn+6 Sn+6 . . → . .Sn−1 → Bn Sn → Bn+1 → Bn+6 Sn+6 ↘ . .S ′ n−1 → B ′ n S ′ n → B ′ n+1 → B ′ n+6 S ′ n+6 → B ′ n+7 S ′ n+7 → B ′ n+8 S ′ n+8
  • 53.
    51% Attacks areReal Minor PoW blockchains, which requires less hash power, are targets of 51% attacks: Verge (XVG), 2M USD (2018-04 and 2018-05) Bitcoin Gold (BTG), 18M USD (2018-05) Monacoin (MONA), 90K USD (2018-05) ZenCash (ZEN) 700K USD (2018-06)
  • 54.
    Blockchain: Technical Details TypicalPoW Operation injection Block creation of operations, and upload Ledger update by blocks Branching by conflicts PoW to reduce and choose branches 51% attacks
  • 55.
    Proof of Stakeand Tezos
  • 56.
    PoW is EnergyInefficient Bitcoin uses 73.12T Wh to maintain its network per year. Which is 3.6B USD/y. Equivalent with the electricity consumption of Austria. Equivalent with the consumption of 6.7M households in US. https://digiconomist.net/bitcoin-energy-consumption
  • 57.
    Risk of Centralization Minerstend to concentrate: PoW is less profitable in regions with higher electricity fee. Concentration of mining powers, i.e. mining pools, makes PoW more efficient. Centralization damages the network security.
  • 58.
    Incentive Misalignment ofPoW Stakeholders and miners are largely different, and their incentives are different. Most of the token owners are not miners, miners are not obliged to keep their positions in PoW. Miners want to maximize their mining rewards. This may work against the interests of token owners.
  • 59.
    Proof of Stake(PoS) PoS: Another Solution to Sybil Attack: Block mining right based not on computation power but on the stake (how much you have) The past stake in the DB is fixed. Sybil attack is prevented. Mining right is assigned only to long-term stakeholders. 51% attack is still possible, but you need to own half of the token supply for enough long.
  • 60.
    Raspberry PI 3,2watts for Tezos PoS: Eco-Friendly + Decentralization No competition of solving puzzles: Mining → “Baking” No special hardware required: No concentration for efficiency required. Antminer S9, 1350watts for Bitcoin
  • 61.
    PoS: Aligned Incentives Miners⊂ Stakeholders You have to hold your position long enough to participate the consensus. Mining right is delegatable. You can participate the network by delegating your right to get some of rewards, not risking your stake.
  • 62.
    Possible Attacks toPoS Double spending by branching with past stake: Nothing at stake attacks Long range attacks    Exchange the stake with goods ⤴  → → → → → ↘ Branch using the past stake → → → → → Make the above chain inactive
  • 63.
    Tezos Consensus Countermeasures againstthe attacks. For nothing at stake attacks Endorsement Security deposit For nothing at stake attack Checkpoints
  • 64.
    Endorsement Based on NakamotoConsensus with endorsement. For each block level , 32 endorsers are chosen: Each endorse one block of and sign. Branches with more endorsements win. The attacker must control much more accounts. i Bij , . . ,Bi1 Bin . . → . .Sn−1 → Bn Sn → Bn+1 → Bn+6 Sn+6 ↘ . .S ′ n−1 → B ′ n S ′ n → B ′ n+1 → B ′ n+6 S ′ n+6 → B ′ n+7 S ′ n+7 → B ′ n+8 S ′ n+8
  • 65.
    Security Deposit Security depositfor mining and endorsement. Branching attempt is punished by slashing the deposit and rewards. Double minings/endorsements in the same level Deposit is returned when reorg becomes impossible (15 days)   ↕ Branching attempt by the same validator is punished.    . . . .→ Bn−1 Sn−1 → Bn Sn → Bn+1 Sn+1 → Bn+2 . .↘ B ′ n+1 S ′ n+1 → B ′ n+2
  • 66.
    Checkpoints Record block hashesperiodically outside of the chain:       H(B) https://www.news.com Tezos’s block hash at is , BKveMfA..n H( )Bn . . → S →. . →. . →. . →. . →. . →. . → S→ Bn Sn      . . →. . →. . →. . →. . →. . →↘ → B ′ n S ′ n S ″
  • 67.
    PoS and Tezos PoWhas energy inefficiency and incentive unalignment PoS: Mining right proportional to the stake against Sybil attack Eco friendly Incentive is aligned Attack against PoS: Branching by past stake and solutions in Tezos (and other protocols): Endorsements Security deposit to prevent intentional branching Checkpoints
  • 68.
  • 69.
    Other Tezos Highlights Basicphilosophy Liquid PoS On chain governance Formal verification
  • 70.
    Philosophy of Tezos Blockchainprotocol for stakeholders Safety is the first priority
  • 71.
    (Virtual) Pure PoS Allthe stakeholders can propose blocks. Direct democracy. Problem: it does not scale: Not all stakeholders can run mining facilities 27h/7d Slowed down for waiting stakeholders without mining facilities
  • 72.
    Delegated PoS Blocks areproposed only by small num of delegates. Stakeholders can vote to select delegates. Indirect democracy. Pros: Highly efficient thanks to the small number of miners. ex. EOS: 21 super nodes. Stakeholders can receive rewards via voting. Easier to implement consensus algorithm like PBFT. Cons: Network get centralized: less secure.
  • 73.
    Liquid PoS (Tezos) Allthe stakeholders can propose blocks, or they may delegate their rights to other miners. “Protocol is owned not only by selected validators,   but by all the stakeholders.” Unlimited number of validators: ex. Tezos: 500 bakers Slower than DPoS but more decentralized i.e. securer. Stakeholders can receive rewards through delegation.
  • 74.
  • 75.
    Tezos and OnChain Governance
  • 76.
    What is Governancein Blockchain “How to fork (upgrade) protocols?” Soft/Hard fork Soft fork Backward compatible Hard fork Backward incompatible: Past valid blocks may become invalid under the new protocol.
  • 77.
    Risk of HardFork A hard fork of a protocol may cause a hard fork of the community. Ethereum and Ethereum Classic hard fork after DAO incident Hard fork of Bitcoin Cash and “hash war” Goal of the Governance Smooth evolution of blockchain protocol without community hard fork.
  • 78.
    On Chain Governance Protocolupgrade is implemented in protocol itself, and all the processes are recorded on chain: Protocol upgrade proposal Test of proposal Vote to upgrade Automatic upgrade of nodes Protocol defines how itself is to be upgraded. “Protocol is owned not by developers but by stakeholders.”
  • 79.
    Tezos: Protocol Separation Definethe target of on chain governance: Shell Network, storage, etc. Not the target, since their change only cause soft forks. Protocol Semantics of transactions and how to reach consensus. The target of on chain governance, since their change triggers hard fork.
  • 80.
    Tezos: On ChainGovernance 90 day cycle of governance: Code of proposals uploaded First vote: select one of them Second vote: test it or not Test phase Final vote: upgrade or not Automatic node upgrade Liquid democracy voting right is weighted by stakes, and delegatable just like LPoS.
  • 81.
    Tezos: Governance History “Athens”:Tezos’s first protocol upgrade. Just changes of few constant parameters. 2019-05-21: Passed the final vote 2019-05-30: Activated “Babylon”: and others. 2019-08-29: Passed the first 2 votes. Now in the test phase Improved consensus algorithm
  • 82.
    Other Tezos Highlights Basicphilosophy Liquid PoS On chain governance Formal verification ← Coming soon
  • 83.
  • 84.
    What is Blockchain(again) Ledger DB Distributed Open network Token for incentives Smart contracts
  • 85.
    Safety Requirements ofBlockchain As a consequence of introduction of token rewards for open distributed DB: Speculative money flows in. System must be open source. Security holes are immediate targets for theft. Blockchain must have very high level of security.
  • 86.
    Safety of SmartContracts Smart contracts must be also very secure. Past incidents around smart contracts: The DAO (3.6M ETH, 15% of circulation, 50M USD stolen) Parity vulnerability#1 (150K ETH, 32M USD stolen) Parity vulnerability#2 (513K ETH, 160M USD frozen) High level of security is required here too.
  • 87.
    The DAO contract user{ do_deposit() { bank.deposit(100); } do_withdraw() { bank.withdraw(); } } contract bank { deposit() { map[SENDER] += AMOUNT; } withdraw() { send(SENDER, map[SENDER]); map[SENDER] = 0; } }
  • 88.
    The DAO contract attack{ do_deposit() { bank.deposit(100); } do_withdraw() { bank.withdraw(); } default() { bank.withdraw(); } } contract bank { deposit() { map[SENDER] += AMOUNT; } withdraw() { send(SENDER, map[SENDER]); map[SENDER] = 0; } }
  • 89.
    Blockchain is aBig Pile of Components Protocol: consensus, incentive design, transaction semantics Smart contract: semantics, compiler Cryptographic algorithms P2P networking Storage All of these components must be secure.
  • 90.
    How to SecureBlockchain Test Important but not enough. Formal verification The way to go.
  • 91.
    Software Test Run asystem under given conditions to see everything goes fine. Run and see, then repeat. Easy. Testable only few corner cases No guarantee for the untested cases.
  • 92.
    Formal Verification Mathematically proveprograms have good/bad properties. Property is assured for all the cases, if proven. Proving is generally much harder than tests.
  • 93.
    Formal Verification Methods Statictyping Model checking Theorem proving
  • 94.
    Static Type Checking Expressproperties of values and expressions in types. Restrict program compositions to those typable, to assure the properties hold for the entire program. Pros: automatic if type inference is available. Cons: relatively weak expressive power.
  • 95.
    Model Checking Abstract aprogram to a finite state transition system, then check it satisfies the properties we want. Pros: automatic. A counterexample is given at failure. Cons: Hard to provide a good modeling.
  • 96.
    Theorem Proving Prove theproperty of program directly, using proof assistant such as Coq: Pros: most powerful Cons: Writing a proof can be very hard.
  • 97.
    Formal Verification forBlockchain Formal verification is used for critical systems such as: Aerospace industry Nuclear plants Blockchain is also a critical system. It must be formally verified. It is also an ideal target of formal verification: No hardware. Open source. Smart contract is a programming language.
  • 98.
    Tezos and FormalVerification Statically typed smart contracts both at VM and high level language levels Modeling of smart contract interpreter using Coq, and correctness proofs of smart contracts using it. Correctness of cryptographic primitives Incoming: Correctness proof of sparse Merkle tree storage using F*. Certified compiler of smart contracts. etc.
  • 99.
    Michelson: Tezos SmartContract VM Stack VM Purely functional: no side effects No mutable variables Transactions are not side effects. Re-entrancy bug is impossible. With strong static typing No runtime type mismatch like "hello" + 10 Different numeric types for currency, , , ꜩ. Arbitrary precision and . No overflow / underflow VM level data structures: Lists, sets, maps, options ℕ ℤ ℕ ℤ
  • 100.
    Michelson interpreter Implements thesemantics of Michelson in node: Purely functional: no side effects Secured by GADTs (Guarded Algebraic Data Types) VM state (code and stack) construction is assured well-typed in the VM type system. Evaluation (state-to-state transition) preserves the well- typedness.
  • 101.
    Mi-Cho-Coq: VM modelingin Coq Michelson is reimplemented in Coq proof assistant. Provides framework to prove correctness around Michelson. Found documentation bugs in the specification. https://gitlab.com/nomadic-labs/mi-cho-coq/
  • 102.
    Smart Contract CorrectnessProofs Using Mi-Cho-Coq. 例: An operation to the account is performed only when enough number of signatures of registered users are attached. multi-sig contract https://gitlab.com/nomadic-labs/mi-cho-coq/blob/master/src/contracts_coq/multisig.v
  • 103.
    HACL*: Verified Cryptography Formallyverified cryptographic functions in F*. ChaCha20, Salsa20, HMAC, SHA-256, SHA-512, Ed25519, etc. F* compiles down to fast C code. Properties proved: Memory safety Correctness of the algorithm Secret independence: immune to the side channel attacks https://github.com/project-everest/hacl-star
  • 104.
    F* Functional language withrefinement types, developed by Microsoft: Compatible syntax with OCaml Some verifications can be done automatically by Z3 Extraction to OCaml, F#, C, WASM, ASM https://www.fstar-lang.org/
  • 105.
    On Going Projects Theyare just I know so far: Sparse Merkle tree for storage. The correctness of tree operations will be verified by F* Certified compiler of smart contract Prove the correctness of compilation from higher level language to Michelson DSL for contracts in Tezos. Verification using deductive program verification platform. Plebeia Archetype Why3
  • 106.
    Tezos and FormalVerification Blockchain is a critical system. Test is important, but FV is also required. All components should be verified. Tezos is a very good target to perform FV.
  • 107.
  • 108.
    Calicurum Preparation Docker images install Gitrepository Basic transaction Try tezos­client Account creation Token transactions Introduction to smart contract Basic concepts of Tezos smart contracts compiler Contract compilation, deploy, and call LIGO
  • 109.
  • 110.
    Prep #1: Dockerand images Install Linux users: configure so that you can run docker command without sudo: ( ) Install 2 docker images Check images are working: Docker details $ docker pull dailambda/tezos­handson:2019­08 ↩   $ docker pull dailambda/ligo:2019­08 ↩  $ docker run dailambda/tezos­handson:2019­08 ↩   hello tezos  $ docker run dailambda/ligo:2019­08 ↩   hello tezos
  • 111.
    Prep #2: CloneGit repository Contents tezos­handson­node A sandboxed node for hands-on tezos­client . You can do everything with it. ligo compiler contracts/ Camligo contract samples $ git clone https://gitlab.com/dailambda/docker­tezos­hands­on ­ b tezos­hands­on­2019­08 ↩   $ cd docker­tezos­hands­on ↩  Command line wallet LIGO
  • 112.
    If you darewant to build Docker images… Sources are available in docker­node/ and docker­ligo/ of the repo.
  • 113.
  • 114.
    Usual Tezos Development… Weusually start a Tezos node connecting to the test network called “Alpha net”: ↪↪ Tezos Network But it takes time to sync your node to the network…
  • 115.
    Today, We UseSandbox ↪↪ Closed in your computuer. No external net access required. No need to sync with the test/main network. No need to buy real Tezos tokens. You can reset the environment easily.
  • 116.
    Sandboxed Environment forHands-on Let’s start it: and keep it running. Note: The node uses TCP port 18732. Reset, if something goes wrong: $ ./tezos­handson­node ↩  # Stop tezos­handson­node, then   $ rm ­rf .tezos­handson­node .tezos­handson­client ↩   $ ./tezos­handson­node
  • 117.
  • 118.
    Check it isworking Open a new terminal, then: $ ./tezos­client bootstrapped ↩   Current head: BLNeoW9n94mD (timestamp: ..  Bootstrapped.
  • 119.
    ICO Commitments Tezos fundraiserdonors receive commitment information to activate their Tezos accounts in Mainnet. In this hands-on, 2 dummy commitment files are prepared: $ ls commitments/  tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF.json  tz1X4maqF9tC1Yn4jULjHRAyzjAtc25Z68TX.json
  • 120.
    Account Activation Careful oftypo. tz1xx..xx is the name (public key hash) of the account. alice is an alias, which you can choose what ever you want. It may take several ten seconds. $ ./tezos­client activate account alice with        commitments/tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF.json ↩   ..  Operation successfully injected in the node.  ..  The operation has only been included 0 blocks ago.  ..  Account alice (tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF) activated  with ꜩ27182818.28459.
  • 121.
    What Happend?! I doexplain. $ ./tezos­client activate account alice with  commitments/tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF.json   Node is bootstrapped, ready for injecting operations.  Operation successfully injected in the node.  Operation hash is  'oo6rb94mw9Z4rKexQhYDnSZeXXWmcZ65vcz77KTDTcGstYYeeuC'  Waiting for the operation to be included...  Operation found in block:  BKqArov5fNKzptY81CLsacSTTPh7tPmCXoqeQ4pNzKCP6GtGiro (pass: 2,  offset: 0)  This sequence of operations was run:    Genesis account activation:      Account: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... +ꜩ20000000 
  • 122.
    1. Check theconnected node The node must be well sync’ed with the network: The sandbox is always bootstrapped, so no problem. Node is bootstrapped, ready for injecting operations.
  • 123.
    → → O1 O1 O1 O1 O1 O1 O2 O2 O2 O2 O2 O2 O2 O2 2. Inject theoperation to the network Operation ooyyy..yyy for the account activation was injected to the network: Waiting the operation is taken for a new block. Operation successfully injected in the node.  Operation hash is 'ooyyy..yyy'  Waiting for the operation to be included...
  • 124.
    B1 = [ O1, O2 ] → B B B B B B B B 3. The Op.is now in a new block There is a validator in the sandbox. Detected the validator took the operation and made a new block Bzzz..zzz: tz1Mawer.. registered in the genesis block is now activated. Operation found in block: Bzzz..zzz (pass: 2, offset: 0)  This sequence of operations was run:    Genesis account activation:      Account: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... +ꜩ20000000
  • 125.
    4. You maywait for more blocks. The block may be still overridden by the consensus. Under Nakamoto consensus, longer you wait, the certainity incrases exponentially. In this hands-on, there is no point to wait. The operation has only been included 0 blocks ago.  We recommend to wait more.  Use command    tezos­client wait for  oo6rb94mw9Z4rKexQhYDnSZeXXWmcZ65vcz77KTDTcGstYYeeuC to be  included ­­confirmations 30 ­­branch  BL26XEjqN4uKAnEC52z6ijj3XibpbcM4ysPLUfcJqkMccyHriV3  and/or an external block explorer.  Account alice (tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF) activated  with ꜩ20000000.
  • 126.
    Operation Processing inTezos The same as we saw for the activation: Make an operation. Upload the operation to the P2P network. A validator makes a block with the operation. The block is uploaded to the P2P network. The certainity of the operation increases as the chain grows.
  • 127.
  • 128.
    How much doI have? Ask the blockchain: alice is an alias of tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF. Therefore, $ ./tezos­client get balance for alice ↩   20000000 ꜩ $ ./tezos­client get balance for  tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ↩   20000000 ꜩ
  • 129.
    Balance of theothers Tezos accounts are not anonymous. You can check the balance of other’s. For example, tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV: Hard to type? The account name is found in file accounts.txt: $ ./tezos­client get balance for         tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ↩   0.000001 ꜩ $ cat accounts.txt ↩   tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV
  • 130.
    Account Alias You cangive an alias to an account: $ ./tezos­client add address jun           tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ↩     $ ./tezos­client get balance for jun ↩   0.000001 ꜩ
  • 131.
    Accounts known bytezos­client alice’s secret key (sk) is known. It is your account. jun’s secret key is not available. It is not yours. Keep your secret key secret!! Once known, your account is owned by others. $ ./tezos­client list known addresses ↩   jun: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLq..  alice: tz1MawerETND6bqJqx8GV3YHUrvMBCD.. (unencrypted sk known)
  • 132.
  • 133.
    Send some tojun Thanks! It prints lots: I do explain. $ ./tezos­client transfer 100 from alice to jun ↩  $ ./tezos­client transfer 100 from alice to jun ↩   Node is bootstrapped, ready for injecting operations.  Estimated gas: 10200 units (will add 100 for safety)  Estimated storage: no bytes added  Operation successfully injected in the node.  Operation hash is 'ooJZ1U114ibPfikZNrDSfmqg8Tcs9CzshL4w1vvsDa35DdB72bN'  Waiting for the operation to be included...  Operation found in block: BL6H8145DMyPeXBQBc2JPRKpVstJSYkhgyGSFFhEJQGAfYweQ8u (pass: 3, offset: 0)  This sequence of operations was run:    Manager signed operations:      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Fee to the baker: ꜩ0.001258      Expected counter: 1      Gas limit: 10000      Storage limit: 0 bytes      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001258        fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001258      Revelation of manager public key:        Contract: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        Key: edpkuSR6ywqsk17myFVRcw2eXhVib2MeLc9D1QkEQb98ctWUBwSJpF        This revelation was successfully applied        Consumed gas: 10000    Manager signed operations:      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Fee to the baker: ꜩ0.001186      Expected counter: 2      Gas limit: 10300      Storage limit: 0 bytes      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001186        fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001186      Transaction:        Amount: ꜩ100        From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        To: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV        This transaction was successfully applied        Consumed gas: 10200        Balance updates:          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ100          tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ... +ꜩ100    The operation has only been included 0 blocks ago.  We recommend to wait more.  Use command    tezos­client wait for ooJZ1U114ibPfikZNrDSfmqg8Tcs9CzshL4w1vvsDa35DdB72bN to be included ­­confirmations 30 ­­branch BLpBxE6wFBQcvNPyUg7sdodpZN3Xra2qGAAJXPG7Z7i9EM94ivj  and/or an external block explorer.
  • 134.
    1. Check theconnected node Waiting for the node to be bootstrapped before injection...  Current head: BL.. (timestamp: .., validation: ..)  Node is bootstrapped, ready for injecting operations.
  • 135.
    2. Gas estimation    and operation injection Estimated gas: 10200 units (will add 100 for safety)  Estimated storage: no bytes added  Operation successfully injected in the node.  Operation hash is 'oOOO..OOO'  Waiting for the operation to be included...
  • 136.
    3. The operationis now in a new block Let’s see more details here. Operation found in block: BL6H8145DMyPeXBQBc2JPRKpVstJSYkhgyGSFFhEJQGAfYweQ8u (pass: 3, offset: 0)  This sequence of operations was run:    Manager signed operations:      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Fee to the baker: ꜩ0.001258      Expected counter: 1      Gas limit: 10000      Storage limit: 0 bytes      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001258        fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001258      Revelation of manager public key:        Contract: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        Key: edpkuSR6ywqsk17myFVRcw2eXhVib2MeLc9D1QkEQb98ctWUBwSJpF        This revelation was successfully applied        Consumed gas: 10000    Manager signed operations:      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Fee to the baker: ꜩ0.001186      Expected counter: 2      Gas limit: 10300      Storage limit: 0 bytes      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ........... ­ꜩ0.001186        fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,6) ... +ꜩ0.001186      Transaction:        Amount: ꜩ100        From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        To: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV        This transaction was successfully applied        Consumed gas: 10200 
  • 137.
    3.1 Revealation thepublic key The public key edpkuSR6ywqsk.. of alice must be revealed to the blockchain, so that others can verify alice’s operation with it:   Manager signed operations:      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Fee to the baker: ꜩ0.001258     Fee to the validator      Expected counter: 1      Gas limit: 10000      Storage limit: 0 bytes      Balance updates:        Fee is paid to the validator.        tz1MawerETND6bqJqx8GV3YHUrvM ........... ­ꜩ0.001258        fees(tz1ddb9NMYHZi5UzPdzTZMY95zgv,6) ... +ꜩ0.001258      Revelation of manager public key:        Contract: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        Key: edpkuSR6ywqsk17myFVRcw2eXhVib2MeLc9D1QkEQb98..        This revelation was successfully applied        Consumed gas: 10000
  • 138.
    3.2 The transaction   Manager signed operations:      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Fee to the baker: ꜩ0.001186               Fee to the validator      Expected counter: 2      Gas limit: 10300      Storage limit: 0 bytes      Balance updates:                  Fee is paid to the validator.        tz1MawerETND6bqJqx8GV3YHUrvM ........... ­ꜩ0.001186        fees(tz1ddb9NMYHZi5UzPdzTZMY..zgv,6) ... +ꜩ0.001186      Transaction:        Amount: ꜩ100                    The amount of the transaction        From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        To: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV        This transaction was successfully applied        Consumed gas: 10200        Balance updates:          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ100   alice pays          tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV ... +ꜩ100   to jun
  • 139.
    4. You maywait for more blocks. The operation has only been included 0 blocks ago.  We recommend to wait more.  Use command    tezos­client wait for ooZZZ..ZZZ to be included ­­ confirmations 30 ­­branch B..  and/or an external block explorer.
  • 140.
    Check the balance Thetoken was really transferred? Check it: The balance of alice should decrease by 100tz + the fee paid for the validator. $ ./tezos­client get balance for alice ↩   19999899.997556 ꜩ  $ ./tezos­client get balance for jun ↩   100.000001 ꜩ
  • 141.
    You cannot stealjun’s token Since you do not know his secret key: alice’s secret key is known by tezos­client. It is stored in .tezos­handson­client: $ ./tezos­client transfer 100 from jun to alice ↩   Error:    Unknown secret key for tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV $ cat .tezos­handson­client/secret_keys ↩   [ { "name": "alice",      "value": "unencrypted:edsk3NDQq5Cmix9H15GkcoVhWo.." } ]
  • 142.
    Gas, Storage, andFee of Tezos Who wants to issue opreations in Tezos must propose: Cost Estimation Gas limit How much CPU power is required. Storage limit How much additional storage is required. Incentive to the validator Fee Paid by the issuer to the validator, if the op. is taken into the new block.
  • 143.
    What Validator Does Comparethe cost estimation and the fee: Fee > Cost estimation Take the operation into the new block to receive the fee. Cost estimation > Fee Operation will not be used for the new block. Operation issuer should: Propose proper fee Operations with too low fee are never taken into the blockchain. Should not cheat the validator with too low cost estimate The operation fails and the fee is taken by the validator, if actual operation cost exceeds the estimate.
  • 144.
    Build your newaccount Create a pair of secret and public keys. Easy: $ ./tezos­client gen keys alice2 $ ./tezos­client list known addresses  alice2: tz1M9ZZccgEAgtDGMu8R7xniFt.. (unencrypted sk known)  jun: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV  alice: tz1MawerETND6bqJqx8GV3YHUrv.. (unencrypted sk known)
  • 145.
    Burn: fee toadd storage Sending from alice to alice2 10000ꜩ fails: Additional storage is required to record the new account to the blockchain. 0.257ꜩ is required to burn. $ ./tezos­client transfer 10000 from alice to alice2  Fatal error:    The operation will burn ꜩ0.257 which is higher than the  configured burn cap (ꜩ0).     Use `­­burn­cap 0.257` to emit this operation.  Exiting $ ./tezos­client transfer 10000 from alice to alice2         ­­burn­cap 0.257  ...        Balance updates:          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ10000          tz1cMEsG9mvL8zyiGHppcCjcz1Et65zwidfg ... +ꜩ10000          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ0.257   Burn
  • 146.
  • 147.
    How Tezos SmartContracts Work Accounts KTxxx..xxx can have smart contracts. Contract state Balance Code Persistent storage Trigger Code is executed at each transaction to the contract.
  • 148.
    Tezos Contract isPure Function Input Parameter given at the transaction. Storage contents Global constants (current account balance, amount of the transaction, the source of the transaction, etc) Output Operations (transactions, call of other smart contracts, etc.) New storage contents No side effects Immutable. Purely functional.
  • 149.
    Michelson for Tezos smartcontracts, and its language. VM but high level: Statically typed , with arbitrary precision. No overflow. Data types (options, lists, sets, map) Cryptographic primitives But bit hard to read and write… Stack VM   # Return to the source    parameter unit;  storage unit;    code {         CDR ;         NIL operation ;         AMOUNT;         PUSH mutez 0;         IFCMPEQ           { }           {             SOURCE ;             CONTRACT unit ;             ASSERT_SOME ;             AMOUNT ;             UNIT ;             TRANSFER_TOKENS ;             CONS ;           };         PAIR;       }    ℕ ℤ
  • 150.
    CameLIGO Today, we use highlevel language for Tezos smart contracts. Compiler LIGO code is compiled down to Michelson 2 syntaxes PascaLIGO (Pascal like) and CamLIGO (OCaml like) Cheat sheet and samples Samples are under ./contracts Still very new and glitchy, but already usable. LIGO(http://ligolang.org) https://gitlab.com/dailambda/mligo_contracts/blob/master/cheat-sheet.md
  • 151.
    Disclaimer to talented OCamlprogrammers CamLIGO is not OCaml. No recursions: let rec Type inference is not fully automatic: ([] : int list) Pattern match is not real pattern match. No nested patterns: Some (Some x) No constants in patterns. 1::[]
  • 152.
    The First CamLIGOContract Replace the storage by the parameter string: Puzzled? Relax. I do explain. let main (parameter : string) (storage : string) =    ( ([] : operation list),  parameter )
  • 153.
    Function Definition Arguments mustbe type-annotated: (parameter : string) Arguments are white space separated: let f (x : ty1) (y : ty2) = .. ❌let f ( (x : ty1), (y : ty2) ) = .. let function_name (arg1 : type1) ... (argn : typen) =    code let main (parameter : string) (storage : string) =    ( ([] : operation list),  parameter )
  • 154.
    Contract Entrypoint A functionwith 2 arguments of: Parameter: here, parameter Storage value: here, storage returns a tuple (..., ...) of: List of operations: here, empty: [] (with type annotation) New storage value: here, parameter let main (parameter : string) (storage : string) =    ( ([] : operation list),  parameter )
  • 155.
    Compilation Place the contractcode at contracts/first.mligo Specify the entrypoint function name main If you made no mistake, the code should be compiled down to a Michelson code contracts/first.tz. $ ./ligo compile­contract contracts/first.mligo main ↩  let main (parameter : string) (storage : string) =    ( ([] : operation list),  parameter )
  • 156.
    Look of MichelsonCode Puzzled? No worry, I do not explain. { parameter string ;    storage string ;    code { {} ;           { { { { DUP } ; CAR } ;               { { { { DIP { DUP } ; SWAP } } ; CDR } ;                 { { { DIP { DUP } ; SWAP } ; NIL operation } ; PAIR } ;                 {} ;                 DIP { { DIP { DIP { DIP { {} } } } ; DROP } } } ;               {} ;               DIP { { DIP { DIP { {} } } ; DROP } } } ;             DIP { { DIP { {} } ; DROP } } } } }
  • 157.
    Contract Deployment first: Aliasof the contract for alice: Manager is alice transferring 0 from alice: Initial balance is 0 paid by alice running contracts/first.tz: The Michelson code ­­init '"initial value"': The initial storage value ­­burn­cap 0.506: For registration network fee $ ./tezos­client originate contract           first for alice           transferring 0 from alice           running contracts/first.tz           ­­init '"initial value"'           ­­burn­cap 0.506 ↩ 
  • 158.
    Did not workfor you? Few things you should check: Check typo Your account alias is alice? Quotes are important: '"initial value"' Got "Error: At line 1 character 0, blahblah Limitation of Docker. Please place first.tz under the directory with ligo. Got “Fatal error” about the burn cap? Asked more? Longer initial storage string costs you more.
  • 159.
    If you aresuccessful I do explain. $ ./tezos­client originate contract first for alice transferring 0 from alice running contracts/first.tz ­­init '"initial value"' ­­burn­cap 0.506 ↩   Node is bootstrapped, ready for injecting operations.  Estimated gas: 16275 units (will add 100 for safety)  Estimated storage: 506 bytes added (will add 20 for safety)  Operation successfully injected in the node.  Operation hash is 'ooe54u2xReWTmbV6eWeKZf3SbWNRMGcFdyuVKDU5UpjYtM1EVDU'  Waiting for the operation to be included...  Operation found in block: BLCmgqwqMShuD38WYFabrD8o8XRf9Xp7W5ZyUkjQYYiK7ULF8qv (pass: 3, offset: 0)  This sequence of operations was run:    Manager signed operations:      From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF      Fee to the baker: ꜩ0.002139      Expected counter: 3      Gas limit: 16375      Storage limit: 526 bytes      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ............ ­ꜩ0.002139        fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoMub195zgv,10) ... +ꜩ0.002139      Origination:        From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        For: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        Credit: ꜩ0        Script:          { parameter string ;            storage string ;            code { {} ;                   { { { DUP ; CAR } ;                       { { { DUUP } ; CDR } ;                         { { DUUP ; NIL operation } ; PAIR } ;                         {} ;                         DIP { { DIP { DIP { DIP { {} } } } ; DROP } } } ;                       {} ;                       DIP { { DIP { DIP { {} } } ; DROP } } } ;                     DIP { { DIP { {} } ; DROP } } } } }          Initial storage: "initial value"          No delegate for this contract          This origination was successfully applied          Originated contracts:            KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS          Storage size: 249 bytes          Paid storage size diff: 249 bytes          Consumed gas: 16275          Balance updates:            tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ0.249            tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ0.257    New contract KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS originated.  The operation has only been included 0 blocks ago.  We recommend to wait more.  Use command    tezos­client wait for ooe54u2xReWTmbV6eWeKZf3SbWNRMGcFdyuVKDU5UpjYtM1EVDU to be included ­­confirmations 30 ­­branch BLTSxQK35VsHuFpvyFJRWkcvxZi2CEmigLvc3FWBarDPXZrFAEP  and/or an external block explorer.  Contract memorized as first.
  • 160.
    Deploy Result Gas limit:16374, Storage limit 526 bytes Proposing fee to the validator: ꜩ0.002139 The contract is owned by alice (tz1Mawer..) The initial balance (credit) is ꜩ0 Michelson code and the initial value "initial value" The originated contract address is KT1NmLBE.. Actual cost: Gas: 16275, Storage: 249 bytes Network fee for the new storage: ꜩ0.249 Network fee for the contract origination: ꜩ0.257
  • 161.
    The wallet knowsthe new contract Not addresses but contracts this time. $ ./tezos­client list known contracts ↩   first: KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS  jun: tz1TGu6TN5GSez2ndXXeDX6LgUDvLzPLqgYV  alice: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF
  • 162.
    Check the stateof the contract $ ./tezos­client get script code for first ↩   { parameter string ;    storage string ;    code { .. } }    $ ./tezos­client get script storage for first ↩   "initial value"    $ ./tezos­client get balance for first ↩   0 ꜩ
  • 163.
    Call the SmartContract Same as the simple transaction we did, but specify the parameter with ­­arg $ ./tezos­client transfer 0 from alice to first        ­­arg '"hello"' ↩   ..      Transaction:        Amount: ꜩ0        From: tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF        To: KT1NmLBEGeKrppHESUK9KEkHjj6i4677J3cS        Parameter: "hello"        This transaction was successfully applied        Updated storage: "hello"        Storage size: 241 bytes        Consumed gas: 15762  ..
  • 164.
    Did not workfor you? Check typo Your account alias is alice? Commands are designed intentionally long to avoid mistakes. Got “Fatal error” about the burn cap? Extending the storage size costs you: $ ./tezos­client transfer 0 from alice to first       ­­arg '"I am creative and give a very long string!"' ↩   Fatal error:    The operation will burn ꜩ0.029 which is higher than the  configured burn cap (ꜩ0).     Use `­­burn­cap 0.029` to emit this operation.
  • 165.
    Let’s check theresult $ ./tezos­client get script storage for first ↩   "whatever you sent"    $ ./tezos­client get balance for first ↩   100 ꜩ       Non 0 if you transfer some tokens.
  • 166.
  • 167.
    Smarter Contracts Returning Operations Byreturning non empty operation list, smart contracts can send tokens to other addresses, and call other smart contracts.
  • 168.
    Smarter Contracts: Boomerang Ifsomeone sends non-zero token, return it to the source. Otherwise, do nothing. Function arguments: Storage: nothing Parameter: nothing In ML, we use type unit for the type of no specific data. () is the value of the type: ( () : unit )
  • 169.
    Smarter Contracts: GlobalConstants Global constants to use: amount: The amount of transaction source: The address which initiated the transaction.
  • 170.
    Smater Contracts: functionsfor ops. Functions to create operations: Operation.transaction : 'a ­> tez ­> 'a contract ­> operation Transfer token to the specified contract with a parameter, ex. Operation.transfer () 10tz contract Operation.get_contract : address ­> _ contract Obtain the contract of the given address. Type annotation is required to specify the contract type. ex. (Operation.get_contract adrs : unit contract)
  • 171.
    Smater Contracts: Boomelang Conditional if e1 then e2 else e3 Nonempty list [ 1 ; 2 ; 3 ] Local definition let v = e1 in e2    Bind the result of e1 to variable v. let main (param : unit) (storage: unit) =    let ops =       if amount = 0tz then         ([] : operation list)       else         [ Operation.transaction () amount             (Operation.get_contract source : unit contract) ]    in    ( ops, () ) 
  • 172.
  • 173.
    Then Call! Check thetoken was returned to alice. $ ./tezos­client transfer 10 from alice to boomerang      Balance updates:        tz1MawerETND6bqJqx8GV3YHUrvMBCD.. ............ ­ꜩ0.004347        fees(tz1ddb9NMYHZi5UzPdzTZMYQQZoM95zgv,15) ... +ꜩ0.004347      Transaction:        ..        Balance updates:          tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... ­ꜩ10          KT1Lw7gDyYr2MFUVJLyA2sQuCSjsc1krcAkb ... +ꜩ10      Internal operations:        Transaction:          ..          Balance updates:            KT1Lw7gDyYr2MFUVJLyA2sQuCSjsc1krcAkb ... ­ꜩ10            tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF ... +ꜩ10 
  • 174.
    Advanced Excersize Simple banking:bank Parameter type unit Storage type Table of deposits, (address, tez) map: you can lookup the balance of each address. Behaviour If transaction amount is not 0tz, update the sender’s balance in the map. If amount is 0tz, send the balance of the sender recorded in the map. Then, reset the balance of sender of the map.
  • 175.
    Hints を参考に。 Global constants amount, sender Thetransferred amount is 0 or not: amount = 0tz かamount <> 0tz Map operations: Map.find_opt, Map.update, Map.remove Branching by the result of Map.find_opt: Use pattern match: match result with None ­> .. | Some tez ­> .. ./contracts/cheat-sheet.md
  • 176.
    Hints Deployment You can givethe initial empty map value by ­­init '{}' Call You will need ­­burn­cap when the call makes the size of map
  • 177.
    Yet Another AdvancedExcersize The DAO attack used a contract attacker with the following behavior: The initial balance is 100tz If received 0tz, transact 10tz to bank If received non 0tz, If its balance exceeds 200tz, do nothing. Otherwise, transact 0tz to bank If transactions are implemented as function calls (in Ethereum), attacker can steal tokens from bank more than attacker’s deposit. Is the same possible in Tezos?