A Deep Dive Into Bitcoin and Bitcoin Scripts
A Deep Dive Into Bitcoin and Bitcoin Scripts
Saravanan Vijayakumaran
1 / 59
Bitcoin Mining
Preventing Spam in Public Databases
• A database you own where anyone in the world can add entries?
Your email inbox
• Hashcash was proposed in 1997 to prevent spam
• Protocol
• Suppose an email client wants to send email to an email server
• Client and server agree upon a cryptographic hash function H
• Email server sends the client a challenge string c
c
Server Client
ckx
• Client needs to find a string x such that H(ckx) begins with k zeros
• Since H has pseudorandom outputs, probability of success in a
single trial is
2n−k 1
= k
2n 2
• The x corresponding to c is considered proof-of-work (PoW)
• PoW is difficult to generate but easy to verify
3 / 59
Bitcoin Mining (1/2)
• Process of adding new blocks to the blockchain
• Nodes which want to perform transactions broadcast them
• Miners collect some of these transactions into a candidate block
nVersion
Block Header hashPrevBlock
hashMerkleRoot
Number of nTime
Transactions n nBits
Coinbase nNonce
Transaction
Regular
Transaction 1
Regular
Transaction 2
..
.
Regular
Transaction n − 1
t0 t1 t2
4 / 59
Bitcoin Mining (2/2)
nVersion
Block Header hashPrevBlock
hashMerkleRoot
Number of nTime
Transactions n nBits
Coinbase nNonce
Transaction
Regular
Transaction 1
Regular
Transaction 2
..
.
Regular
Transaction n − 1
| ·{z
T = 0x 00 · · 00} FFFFF
| ·{z
· · FFFFF}
16 times 48 times
5 / 59
Why is Mining Hard?
Target value Fraction of
T SHA256d outputs ≤ T
1
0x7FFFF
| {z · · · FFFF}
FFFF 2
63 times
1
0x0FFFF
| {z · · · FFFF}
FFFF 16
63 times
1
| ·{z
0x00 · · 00} FFFFF
| ·{z
· · FFFFF}
264
16 times 48 times
T +1
Pr [SHA256d output ≤ T ] ≈
2256
6 / 59
Why should anyone mine blocks?
• Successful miner gets rewarded in bitcoins
• Every block contains a coinbase transaction which creates
12.5 bitcoins
• Each miner specifies his own address as the destination of the
new coins
• Every miner is competing to solve their own PoW puzzle
• Miners also collect the transaction fees in the block
7 / 59
Block Addition Workflow
• Nodes broadcast transactions
• Miners accept valid transactions and reject invalid ones (solves double spending)
• Miners try extending the latest block
Candidate
Block A
Candidate
Block C
Candidate
Block C 0
8 / 59
What if two miners solve the puzzle at the same time?
Solution
Blockfrom Block
miner
N + 1A N +2
Solution
Stalefrom
miner
blockB
B
B
A
MB
A B
A MA B
B
A A
A B B
nVersion
hashPrevBlock
hashMerkleRoot
nTime
nBits
nNonce
tsum
Tnew = ×T
14 × 24 × 60 × 60
10 / 59
Bitcoin Payment Workflow
• Merchant shares address out of band (not using Bitcoin P2P)
• Customer broadcasts transaction t which pays the address
• Miners collect broadcasted transactions into a candidate block
Block Header
Number of
Transactions n
Coinbase
Transaction
Regular
Transaction 1
Regular
Transaction 2
..
.
Regular
Transaction n − 1
11 / 59
Bitcoin Transaction Format
Coinbase Transaction Format
Pre-SegWit
Block Format
Coinbase Transaction
Output Format
Block Header
Amount x1 nValue
Number of Output 0
Challenge Script C1 scriptPubkeyLen
Transactions n
scriptPubkey
Coinbase
Transaction
Regular Amount x2
Output 1
Transaction 1 Challenge Script C2
Regular
Transaction 2
..
.
Regular
Transaction n − 1
13 / 59
Transaction ID
Regular Transaction
nVersion
Number of Inputs N
hash
n
Input 0 scriptSigLen
scriptSig
nSequence
..
.
hash
n
Double
Input N − 1 scriptSigLen
SHA-256 Tx ID
scriptSig
Hash
nSequence
Number of Outputs M
nValue
Output 0 scriptPubkeyLen
scriptPubkey
..
.
nValue
Output M − 1 scriptPubkeyLen
scriptPubkey
nLockTime
14 / 59
Regular Transaction Format
Pre-SegWit
Input Format
Previous Regular Tx Regular Transaction
with Tx ID = I1 hash
n
Tx ID = I1
Input 0 scriptSigLen
One or more Output Index = 0
Response Script R1 scriptSig
inputs nSequence
Amount x1 Tx ID = I1
Output 0 Output Index = 1 Input 1
Challenge Script C1
Response Script R2
Amount x2
Output 1 Challenge Script C2 Tx ID = I2
Output Index = 0 Input 2
Response Script R3 Output Format
Amount x3
Output 0 Amount y2
Challenge Script C3 Output 1
Challenge Script C5
2
OP_3 OP_ADD
3
OP_ADD 2
17 / 59
Challenge/Response Script Execution
Remaining Script Stack State
x1
x2
<Challenge Script> ..
.
xn
y1
y2
..
.
ym
x
OP_HASH256 0x20 S OP_EQUAL
H(x)
0x20 S OP_EQUAL
S
OP_EQUAL H(x)
0 or 1
20 / 59
Pay to Public Key
Digital Signatures
Message
Decision on
Signer (Message, Signature) Verifier Signature Validity
Signer’s Signer’s
Private Key Public Key
Easy
Hard
22 / 59
Pay to Public Key
• Challenge script: 0x21 <Public Key> OP_CHECKSIG
• Response script: <Signature>
Remaining Script Stack State
<Signature>
<Public Key> OP_CHECKSIG
<Public Key>
OP_CHECKSIG <Signature>
True/False
23 / 59
Signatures Protect Transactions
Message for
Regular Transaction Input 0 signatures
nVersion nVersion
0x02 0x02
hash0 hash0
n0 n0 Input 0
Input 0
scriptSigLen0 prevScriptPubkeyLen0 Fields
scriptSig0 prevScriptPubkey0
nSequence0 nSequence0
hash1 hash1
n1 n1 Input 1
Input 1 scriptSigLen1 0x00 Fields
scriptSig1 nSequence1
nSequence1 0x02
0x02 nValue0
Output 0
nValue0 scriptPubkeyLen0
Fields
Output 0 scriptPubkeyLen0 scriptPubkey0
scriptPubkey0 nValue1
nValue1 scriptPubkeyLen1 Output 1
Fields
Output 1 scriptPubkeyLen1 scriptPubkey1
scriptPubkey1 nLockTime
nLockTime nHashType
24 / 59
Pay to Public Key Hash
Pay to Public Key Hash Address
• To receive bitcoins, a challenge script needs to be specified
• P2PKH addresses encode P2PKH challenge scripts
• Example: 1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm
26 / 59
Base58 Encoding
1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm
l
0091B24BF9F5288532960AC687ABB035127B1D28A50074FFE0
RIPEMD-160
Prefix address
version byte
BkR
Double
SHA-256
Extract first C4
k
four bytes
BkRkC4
Base58
Encoding P2PKH Address
28 / 59
Why Hash the Public Key?
Point Addition
ECDLP
P2PK Solve
Private key
Address ECDLP
Find Find
P2PKH Solve
RIPEMD-160 SHA-256 Private key
Address ECDLP
preimage preimage
29 / 59
P2PKH Transaction
• Challenge script
OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY
OP_CHECKSIG
Base58
P2PKH Address Decoding
BkRkC4
Discard last
four bytes
BkR
Discard address R
PubKeyHash
version prefix byte
30 / 59
P2PKH Script Execution (1/2)
Remaining Script Stack State
<Public Key>
OP_DUP OP_HASH160
<Signature>
<PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
<Public Key>
OP_HASH160 <Public Key>
<PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG <Signature>
31 / 59
P2PKH Script Execution (2/2)
Remaining Script Stack State
<PubKeyHashCalc>
<Public Key>
<Signature>
<PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
<PubKeyHash>
<PubKeyHashCalc>
<Public Key>
OP_EQUALVERIFY OP_CHECKSIG
<Signature>
<Public Key>
<Signature>
OP_CHECKSIG
True/False
32 / 59
Multi-Signature
m-of-n Multi-Signature Scripts
• m-of-n multisig challenge script specifies n public keys
• Example: m = 2 and n = 3
• Challenge script
• Response script
OP_0 <Sig1> <Sig2>
34 / 59
2-of-3 Multisig Script Execution
Remaining Script Stack State
<Sig2>
OP_2 <PubKey1> <Sig1>
<PubKey2> <PubKey3> OP_3 OP_CHECKMULTISIG <Empty Array>
3
<PubKey3>
<PubKey2>
<PubKey1>
2
OP_CHECKMULTISIG
<Sig2>
<Sig1>
<Empty Array>
True/False
35 / 59
Pay to Script Hash
Pay to Script Hash Script
• Allows specification of arbitrary scripts as payment destinations
• Challenge script
37 / 59
P2SH Multisig Script Execution (1/2)
Remaining Script Stack State
OP_0 <Sig1>
<OP_1 <PubKey1> <PubKey2> OP_2 OP_CHECKMULTISIG>
OP_HASH160 <RedeemScriptHash> OP_EQUAL
<Sig1>
<OP_1 <PubKey1> <PubKey2> OP_2 OP_CHECKMULTISIG> <Empty Array>
OP_HASH160 <RedeemScriptHash> OP_EQUAL
<RedeemScriptHashCalc>
<Sig1>
<Empty Array>
<RedeemScriptHash> OP_EQUAL
<RedeemScriptHash>
<RedeemScriptHashCalc>
<Sig1>
OP_EQUAL <Empty Array>
38 / 59
P2SH Multisig Script Execution (2/2)
Remaining Script Stack State
<Sig1>
<Empty Array>
OP_1 <PubKey1> <PubKey2> OP_2 OP_CHECKMULTISIG
2
<PubKey2>
<PubKey1>
1
OP_CHECKMULTISIG
<Sig1>
<Empty Array>
True/False
39 / 59
Pay to Script Hash Address
Redeem Script SHA-256
RIPEMD-160
Prefix address
version byte
BkR
Double
SHA-256
Extract first C4
k
four bytes
BkRkC4
Base58
Encoding P2SH Address
40 / 59
Null Data
Null Data Script
• Challenge script
OP_RETURN <Data>
Length(<Data>) ≤ 80 bytes
• OP_RETURN terminates script execution immediately
• No valid response script exists
• Null data outputs are unspendable
• Any bitcoins locked by a null data challenge script are lost forever
• Mainly used to timestamp data
42 / 59
Smart Contracts
Smart Contracts
• Computer protocols which help execution/enforcement of regular
contracts
• Minimize trust between interacting parties
• Hypothetical example: Automatic fine for noise pollution
• Campus community hall parties use loudspeakers
• Party organizers pay bitcoin security deposit
• If noise rules violated, deposit distributed to nearby residents
• Two actual examples
• Escrow
• Micropayments
44 / 59
Smart Contracts
Escrow
Problem Setup
• Alice wants to buy a rare book from Bob
• Alice and Bob live in different cities
• Bob promises to ship the book upon receiving Bitcoin payment
• Alice does not trust Bob
• Alice proposes an escrow contract involving a third party Carol
46 / 59
Escrow Contract
• Alice requests public keys from Bob and Carol
• Alice pays x bitcoins to a 2-of-3 multisig output
OP_2 <PubKeyA> <PubKeyB> <PubKeyC> OP_3 OP_CHECKMULTISIG
47 / 59
Smart Contracts
Micropayments
Problem Setup
• Bitcoin transaction fees make small payments expensive
• Micropayments contract can aggregate small payments
• Alice offers proofreading and editing services online
• She accepts bitcoins as payments
• Clients email documents to Alice
• Alice replies with typos and grammatical errors
• Alice charges a fixed amount of bitcoins per edited page
• To avoid clients refusing payment, Alice uses micropayments
contract
• Suppose Bob wants a 100 page document edited
• Alice charges 0.0001 BTC per page
• Bob expects to pay a maximum of 0.01 BTC to Alice
49 / 59
Micropayments Contract (1/3)
Creating Refund Transaction
50 / 59
Micropayments Contract (2/3)
Getting Paid for First Page Edits
51 / 59
Micropayments Contract (3/3)
Getting Paid for Second Page, Third Page . . .
document
Request public key
• She creates a transaction e2 which
unlocks t1 and pays her 0.0002 BTC Send PubKeyA
Create PubKeyB
and 0.0098 BTC to Bob Create t1
Create t2
Send t2 with B’s sig
• Alice signs e2 and sends it to Bob
Send t2 with A’s sig
along with the second page edits Broadcast
t1
n
t1 confirmatio
• If Bob refuses to sign e2 , then Alice
Send document
terminates the contract.
Alice broadcasts e1 and receives Send e1 with A’s
sig and page 1 edits
0.0001 BTC.
sig
• If Bob signs e2 and returns it to Alice, Send e1 with B’s
Send e2 with A’s
sig and page
then Alice is guaranteed 0.0002 2 edits
Broadcast e
• She has to finish before the refund 100
confirmation
transaction lock time expires e100
52 / 59
Key Takeaways
• Smart contracts reduce the need for trust
• Bitcoin’s scripting language enables some smart contracts
• Not powerful enough to express complex contracts
53 / 59
What about SegWit?
Transaction ID
Regular Transaction
nVersion
Number of Inputs N
hash
n
Input 0 scriptSigLen
scriptSig
nSequence
..
.
hash
n
Double
Input N − 1 scriptSigLen
SHA-256 Tx ID
scriptSig
Hash
nSequence
Number of Outputs M
nValue
Output 0 scriptPubkeyLen
scriptPubkey
..
.
nValue
Output M − 1 scriptPubkeyLen
scriptPubkey
nLockTime
55 / 59
Refund Protocol
• Alice wants to teach Bob about transactions
• Bob does not own any bitcoins
• Alice decides to transfer some bitcoins to Bob
• Alice does not trust Bob
• She wants to ensure refund
56 / 59
Refund Protocol
Transaction t1
with TXID i1
Transaction t2
Input unlocking
Input 0 Input with hash = i1 and
x bitcoins from Input 0
n = 0 unlocking the
Alice’s UTXO
2-of-2 multisig output in t1
Output locked by
Output returning
Output 0 2-of-2 multisig Output 0
funds to Alice
challenge script
1. Create t1
2. Create t2
th A’s sig
3. Send t2 wi
4. Send t wi
2 th B’s sig 5. Broadcas
t t1
ion
t1 confirmat
6. Broadcas
t t2
ion
t2 confirmat
57 / 59
Exploiting Transaction Malleability
Bob Alice Network
1. Create t1
2. Create t2
th A’s sig
3. Send t2 wi
4. Send t wi
2 th B’s sig 5. Broadcast t
1
tt
5. Broadcas 1
6. Broadca
st t10
ion
t 10 confirmat
58 / 59
Bitcoin Script Learning Resources
• Code https://github.com/bitcoin/bitcoin/
(src/script directory)
• Stackoverflow https://bitcoin.stackexchange.com/
• Forum https://bitcointalk.org/
• IRC https://en.bitcoin.it/wiki/IRC_channels
• Books
• Princeton book http://bitcoinbook.cs.princeton.edu/
• Mastering Bitcoin, Andreas Antonopoulos
• Notes
• https://www.ee.iitb.ac.in/~sarva/bitcoin.html
59 / 59