Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

4 The Blockchain Academy Europe - Transactions - Blocks

Download as pdf or txt
Download as pdf or txt
You are on page 1of 108

Bitcoin and Blockchain Technology:

Addresses, Transactions, and Blocks


Ferdinando M. Ametrano
https://www.ametrano.net/about/
Table of Contents
1. Addresses and Wallet Import Formats
2. TxIns, TxOs, UTxOs
3. Bitcoin Script Language
4. Transaction Scripts
5. Odds and Sods
6. Blocks
7. Historical Transactions
2/108
Bitcoin Base58 Encoding
• Binary digits: 01
• Decimal digits: 0123456789
• Hexadecimal digits: 0123456789ABCDEF

Base58 digits: all alphanumeric characters (numbers, uppercase,


and lowercase) omitting 0 (zero), O (capital o), I (capital i) and l
(lower case L)
123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijk
mnopqrstuvwxy
3/108
Parsimonious Large Number Representation
Larger digit set available
↓↓
less digits required to represent large numbers

e.g. 16^5-2:
11111111111111111110 Binary
1048574 Decimal
FFFFE Hex
6Nhs Base58

4/108
Base58Check Encoding
1. Payload
Double SHA256 Checksum Calculation
2. [Prefix +] Payload [+ Suffix] =
a. ExtPayload
ExtPayload
b. SHA256(ExtPayload)
c. SHA256(SHA256(ExtPayload))
d. Checksum = first 4 bytes of the
3. ExtPayload + Checksum
previous step
4. Base58 encoding

The Base58Check decoding stage will first use the checksum to


detect possible errors in ExtPayload before actual decoding
5/108
Base58 Representation of
Public/private Keys

Base58 is used for compact representation of


Bitcoin Public/private keys:

• Address: 𝑄 in Base58 representation


• Wallet Import Format: 𝑞 in Base58 representation
6/108
From Uncompressed Public Key to Address (1/4)

Given the private key


0x18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725

1. Start from the associated Public Key point in


uncompressed representation (65 bytes: 1
byte for the x04 prefix, 32 bytes for the X
coordinate, 32 bytes for the Y coordinate)
04
50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6

7/108
From Uncompressed Public Key to Address (2/4)
2. Perform SHA256 hashing on the Public Key
600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408

3. Perform RIPEMD160 hashing on the result of SHA256


010966776006953D5567439E5E39F86A0D273BEE
Note: step 2-3 are often defined as HASH160
HASH160(PubKey) := SHA256(RIPEMD160(PubKey))

4. Add version byte in front of HASH160 (0x00 for Main


Network) to obtain the extended HASH160
00010966776006953D5567439E5E39F86A0D273BEE
The leading zeros, while irrelevant digits for a number, are retained
through the following conversions and will lead to a leading 1 in the resulting address

8/108
From Uncompressed Public Key to Address (3/4)

Base58Check encoding steps:


5. SHA256 hash on the extended HASH160
445C7A8007A93D8733188288BB320A8FE2DEBD2AE1B47F0F50BC10BAE845C094

6. SHA256 hash on the result of the previous step


D61967F63C7DD183914A4AE452C9F6AD5D462CE3D277798075B107615C1A8A30

7. Take the first 4 bytes of the second SHA256 hash as


address checksum
D61967F6

9/108
From Uncompressed Public Key to Address (4/4)
8. Add the 4 checksum bytes from stage 7 at the end
of extended HASH160
00010966776006953D5567439E5E39F86A0D273BEED61967F6

9. Convert into a base58 string using Base58 encoding


16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM

The bitcoin address is the Base58 encoding of the


HASH160 of a Public key; it starts with 1 because of the
0x00 prefix.
https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses
10/108
From Compressed Public Key to Address
Using the same private key as in the previous slide
0x18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725

• Start from the associated Public Key in compressed


representation (33 bytes: 1 byte x02 or x03, 32 bytes
corresponding to the X coordinate)
02
50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352

• Arrive to a Base58 encoded address


1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs

Again: the address is the Base58 encoding of the HASH160 of a


Public key; it starts with 1 because of the 0x00 prefix.
11/108
Private Key (Uncompressed) WIF
Given a private key
0x0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D

1. Extended private key (80 prefix, no suffix)


0x800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D

2. 4 bytes checksum added


0x800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D507A5B8D

3. Base58 encode is 51 characters; it always starts with 5, because of the


0x80 prefix
5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ

The uncompressed property does not refer to the private key: it is the public
key point derived from uncompressed WIF that must be uncompressed
12/108
Private Key (Compressed) WIF
Using the same private key as in the previous slide
0x0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D
1. Extended private key (0x80 prefix, 0x01 suffix)
0x800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D01
2. 4 bytes checksum added
0x800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D01A62019D2
3. Base58 encode is 52 characters (longer than uncompressed WIF because
of the 0x01 suffix); it always starts with K or L, because of the 0x80 prefix
KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617

The compressed property does not refer to the private key: it is the public
key derived from compressed WIF that must be compressed

13/108
Addresses/Keys Version Types
Network Usage Version type Leading symbol(s)
Mainnet Pubkey hash (address) 00 1
Mainnet prvkey (uncompressed WIF) 80 5
Mainnet prvkey (compressed WIF) 80 K or L
Testnet Pubkey hash (address) 6F m or n
Testnet prvkey (uncompressed WIF) EF 9
Testnet prvkey (compressed WIF) EF c

14/108
Relation Between Keys, Addresses, and WIF
1. prvkey <––Base58Encoding––> WIF
2. prvkey ––EC Multiplication––> PubKey
3. PubKey ––HASH160––> PubKeyHash
4. PubKeyHash <––Base58Encoding––> address

• EC multiplication and hash functions are one-way


• Quantum computers will be able to factor private keys
from public keys, but not to invert hash functions

15/108
Homework
With the private key obtained with the previous homework:
1. Calculate the uncompressed WIF
2. Calculate the compressed WIF
3. Calculate the address from uncompressed Public key
4. Calculate the address from compressed Public key
Check PrvKeyToWIFCompressed.py, PrvKeyToWIFUncompressed.py, and PubKeyToAddress.py in the scripts
folder at https://github.com/dginst/BitcoinBlockchainTechnology

Verify your results at www.bitaddress.org (Wallet Details)

16/108
Table of Contents
1. Addresses and Wallet Import Formats
2. TxIns, TxOs, UTxOs
3. Bitcoin Script Language
4. Transaction Scripts
5. Odds and Sods
6. Blocks
7. Historical Transactions
17/108
Transactions
• Txs can be created by any means, even offline
• Txs can be propagated to the network even by non
secure channels
• Nodes will validate Txs before propagating them
further
• Txs consume one or more transaction inputs (TxIns)
and generate one or more transaction outputs (TxOs)
• Coinbase transactions have no TxIns
18/108
TxOs and UTxO Pool
• TxOs are amount of bitcoins, recorded on the blockchain
and associated to addresses
• Blockchain has neither accounts nor balances
• A given address usually has its associated bitcoins as
(possibly many) TxOs scattered over (possibly many) blocks
• TxOs can only be spent once and fully as indivisible chunks
• bitcoins only exist as unspent TxOs (UTxOs)
• The UTxO pool is the LevelDB database cache used to
record all current UTxOs

19/108
Unspent TxOs: Electrum Testnet
• 2 UTxO (2BTC + 1BTC) on the address
tb1qhd92h3tac67u2merxvyu3nen6cgf5y2k8q24hd
• 1 UTxO each (2.999991 and 43.597368) on two other addresses
• Balance includes all of them

20/108
TxIns reference and spend UTxOs

• Software can empower the user with coin control, i.e. picking TxIns

21/108
TxOs Locking Puzzle
• Every TxO is locked by a mathematical puzzle
(encumbrance)
• To spend the TxO, the corresponding TxIn must
provide the solution to (i.e. unlock) the puzzle
• Unlocking a TxO puzzle usually involves a digital
signature using the private key related to the
address the TxO is associated to
22/108
TxIns
Each TxIn must hold:
• the reference to the UTxO being spent:
– hash pointer to the previous Tx (TxPrev) where the
UTxO has been created
– zero-based index identifying the UTxO among those
created in TxPrev
• the unlocking solution of the UTxO mathematical
puzzle (usually including private key signature)
23/108
nLockTime
• Earliest time that a transaction is valid and can be relayed on the
network or added to the blockchain
• A transaction is finalized when its nLockTime has been reached
– nLockTime < 500,000,000 it is interpreted as block number
– nLockTime > 500,000,000 it is interpreted as Unix Epoch timestamp
(number of second since 00:00:00UTC Jan 1, 1970)
• A TxIn include a sequence number used to override a transaction
prior to the expiration of its (nonzero) lock-time (nLockTime is
ignored when the sequence numbers of all TxIns are set to
UINT_MAX)

24/108
Transaction Validity
1. can be finalized (i.e. it is not time locked)
2. TxIns reference UTxOs only
3. Each TxIn provides the unlocking solution for the
mathematical puzzle of its referenced UTxO
4. The amounts of the newly generated TxOs is less
than or equal to the amount of TxIns
5. ...
25/108
TxIns, TxOs, and Fees
• σ 𝑇𝑥𝑂𝑖 ≤ σ 𝑇𝑥𝐼𝑛𝑖 : the amounts of the newly generated
TxOs must be less than or equal to the amount of TxIns
• σ 𝑇𝑥𝑂𝑖 + 𝐹𝑒𝑒 = σ 𝑇𝑥𝐼𝑛𝑖 : the difference between TxIns
and TxOs is collected as additional fee reward in the
coinbase transaction
• If the amount referenced by the used TxIns is greater than
the amount of the intended transaction, a change must be
sent to a change address
• The fee cannot not be a TxO because the winning miner is
not known at transaction time
26/108
Transaction Fees
• A minimum fee of 0.0001 BTC is used as disincentive
against "spam" transactions or system abuse
• Fees are an incentive for miners to prioritize a transaction
for inclusion in the next block, especially if blocks are full
• Fees depend on the size of the transaction in kilobytes, not
the transaction value in BTC
• The way transaction fees are calculated and the effect they
have on transaction prioritization has been evolving
according to market forces

27/108
Transaction Fees
https://blockchain.info/charts/transaction-fees?timespan=all&showDataPoints=false&daysAverageString=1&show_header=true&scale=0&address

28/108
https://bitcoinchain.com/block_explorer/tx/5a42590fbe0a90ee8e8747244d6c84f0db1a3a24e8f1b95b10c9e050990b8b6b

29/108
Table of Contents
1. Addresses and Wallet Import Formats
2. TxIns, TxOs, UTxOs
3. Bitcoin Script Language
4. Transaction Scripts
5. Odds and Sods
6. Blocks
7. Historical Transactions
30/108
Stack Data Structure
• Based on the Last In First Out (LIFO) principle
• Operators push data on the top of the stack or
pop out data from the top of the stack
• Conditional operators evaluate a condition,
pushing a TRUE/FALSE result on the top of the
stack
31/108
Script Language
A very simple Forth-like language that uses reverse-polish notation
1. no loops or complex flow control capabilities
2. ensure termination, i.e. finite time execution (implied by 1)
3. memory access is stack-based: there are no variables, calculations
are performed on the stack

Script is purposefully stateless and not Turing-complete

Limited flexibility is a deliberate security feature, preventing


vulnerability from the transaction validation mechanism

32/108
Verify 2+3=5 Using Script
2 3 OP_ADD 5 OP_EQUAL Stack

• 2
• 3
• OP_ADD
• 5
• OP_EQUAL

33/108
Verify 2+3=5 Using Script
2 3 OP_ADD 5 OP_EQUAL Stack

→2
• 3
• OP_ADD
• 5
• OP_EQUAL
• 2
34/108
Verify 2+3=5 Using Script
2 3 OP_ADD 5 OP_EQUAL Stack

• 2
→3
• OP_ADD
• 5
• OP_EQUAL • 3
• 2
35/108
Verify 2+3=5 Using Script
2 3 OP_ADD 5 OP_EQUAL Stack

• 2
• 3
→ OP_ADD
• 5
• OP_EQUAL
• 5
36/108
Verify 2+3=5 Using Script
2 3 OP_ADD 5 OP_EQUAL Stack

• 2
• 3
• OP_ADD
→5
• OP_EQUAL • 5
• 5
37/108
Verify 2+3=5 Using Script
2 3 OP_ADD 5 OP_EQUAL Stack

• 2
• 3
• OP_ADD
• 5
→ OP_EQUAL
• TRUE
38/108
Interactive Script Playgrounds

• Bitcoin Debug Script Execution


https://webbtc.com/script

• convert Script to JavaScript


http://www.crmarsh.com/script-playground/
39/108
Operators
256 opcodes total (15 disabled, 75 reserved)
• Arithmetic
• If/then
• Logic/data handling
• Crypto
– Hashes
– Signature verification
– Multi-signature verification

40/108
Operators
• OP_DUP duplicates the top stack value
• OP_HASH160 performs double hashing of the top stack value, first using SHA256
and then RIPEMD160
• OP_HASH256 performs double hashing of the top stack value using SHA256
• OP_EQUAL returns TRUE if the two top stack values are exactly equal, FALSE
otherwise
• OP_VERIFY marks transaction as invalid if top stack value is not TRUE. The top
stack value is removed.
• OP_EQUALVERIFY is equivalent to OP_EQUAL followed by OP_VERIFY
• OP_CHECKSIG checks that the input signature is a valid signature using the input
public key for the hash of the current transaction
• OP_RETURN marks transaction as invalid. A standard way of attaching extra data to
transactions is to add a zero-value TxO with a <scriptPubKey> consisting of
OP_RETURN followed by exactly one pushdata operator
https://en.bitcoin.it/wiki/Script
41/108
Table of Contents
1. Addresses and Wallet Import Formats
2. TxIns, TxOs, UTxOs
3. Bitcoin Script Language
4. Transaction Scripts
5. Odds and Sods
6. Blocks
7. Historical Transactions
42/108
Transaction Script
• TxOs include a <scriptPubKey> locking
mathematical puzzle (usually including, in some
way, the bitcoin address or the public key)
• The puzzle must be solved in order to spend the
UTxO
• The spending TxIn provides <scriptSig> unlocking
solution (usually including, in some way, the
private key signature)
43/108
Script Evaluation
• The Unlock+Lock script (<scriptSig>+<scriptPubKey>) is
evaluated
• If the script fails or its result is FALSE then the TxIn is
invalid
• A UTxO is unaffected by failed attempts to spend it
• A TxIn that satisfies the UTxO conditions does spend it:
the TxO remains in the blockchain, but it is removed
from the UTxO pool
44/108
Script Execution
Scripts are not really concatenated anymore: executed separately for security reason,
stack being transferred between the two

45/108
Standard Transactions
Many different scripts are possible, but for security reason a transaction is usually
relayed only if IsStandard(), i.e.
• does not violate good network behavior rules
• its scripts match a small set of believed-to-be-safe templates:
– pay-to-public-key (P2PK, the easiest and oldest)
– pay-to-public-key-hash (P2PKH, the most common)
– null data (OP_RETURN)
– multi-signature (limited to 15 keys)
– pay-to-script-hash (P2SH, the most versatile)
– {SegWit transactions}

Valid non-standard transactions, if included in blocks, are accepted

46/108
Pay-To-Public-Key (P2PK)

The first transaction type was Pay-To-Public-Key


(P2PK)

In the early days of Bitcoin


• coins were assigned to uncompressed Public keys
• spent using DER signatures

47/108
Pay-To-Public-Key (P2PK)
TX_PUBKEY
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
• OP_CHECKSIG

48/108
Pay-To-Public-Key (P2PK)
TX_PUBKEY
<scriptSig> + <scriptPubKey> Stack
→ <sig>
• <pubKey>
• OP_CHECKSIG

• <sig>
49/108
Pay-To-Public-Key (P2PK)
TX_PUBKEY
<scriptSig> + <scriptPubKey> Stack
• <sig>
→ <pubKey>
• OP_CHECKSIG

• <pubKey>
• <sig>
50/108
Pay-To-Public-Key (P2PK)
TX_PUBKEY
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
→ OP_CHECKSIG

• TRUE
51/108
Quantum Resistance

Problem: to publish a public key on the blockchain is not


quantum resistant, as such it is not future proof

Solution: pay to the hash of the public key, publishing


only the public key hash (i.e. the address) on the
blockchain
52/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
• OP_DUP
• OP_HASH160
• <pubKeyHash?>
• OP_EQUALVERIFY
• OP_CHECKSIG

53/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
→ <sig>
• <pubKey>
• OP_DUP
• OP_HASH160
• <pubKeyHash?>
• OP_EQUALVERIFY
• OP_CHECKSIG
• <sig>
54/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
• <sig>
→ <pubKey>
• OP_DUP
• OP_HASH160
• <pubKeyHash?>
• OP_EQUALVERIFY
• <pubKey>
• OP_CHECKSIG
• <sig>
55/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
→ OP_DUP
• OP_HASH160
• <pubKeyHash?> • <pubKey>
• OP_EQUALVERIFY
• <pubKey>
• OP_CHECKSIG
• <sig>
56/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
• OP_DUP
→ OP_HASH160
• <pubKeyHash?> • <pubKeyHash>
• OP_EQUALVERIFY
• <pubKey>
• OP_CHECKSIG
• <sig>
57/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
• OP_DUP
• OP_HASH160 • <pubKeyHash?>
→ <pubKeyHash?> • <pubKeyHash>
• OP_EQUALVERIFY
• <pubKey>
• OP_CHECKSIG
• <sig>
58/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
• OP_DUP
• OP_HASH160
• <pubKeyHash?>
→ OP_EQUALVERIFY
• <pubKey>
• OP_CHECKSIG
• <sig>
59/108
Pay-To-Public-Key-Hash (P2PKH)
TX_PUBKEYHASH
<scriptSig> + <scriptPubKey> Stack
• <sig>
• <pubKey>
• OP_DUP
• OP_HASH160
• <pubKeyHash?>
• OP_EQUALVERIFY
→ OP_CHECKSIG
• TRUE
60/108
Pay-To-Public-Key-Hash (P2PKH)
• Public keys are revealed at redemption time
only
• Problem: multiple UTxOs associated to the
same address would see their common public
key revealed when the first UTxO is spent
• Solution: use a different address (i.e. public
key) for each TxO!
61/108
Blockchain for Data Unrelated to Transactions
• The 20-byte destination address can be used to store any data in
the blockchain, e.g. file hash for proof-of-existence of the file on the
transaction date
• Blockchain as distributed and time-stamped ledger system for
digital notary services, stock certificates, smart contracts, etc.

Blockchain abuse or clever use?


• Waste: if the address does not correspond to a private key the UTxO
can never be spent, associated bitcoins are lost
• Bloat: blockchain disk storage, UTxO cache RAM

62/108
A Better Approach: OP_RETURN
• 80 bytes of nonpayment data are allowed after OP_RETURN
• OP_RETURN forces the failure of any script including it; the
associated TxO cannot be spent
• As such, its TxO is provably unspendable: it is stored in the
blockchain but prunable from the UTxO pool (limited bloat)
• The TxO can have zero bitcoin associated (no waste)

see www.eternitywall.com, www.eternitywall.com/notarize, and


www.opentimestamps.org

63/108
OP_RETURN
TX_NULL_DATA
<scriptSig> + <scriptPubKey> Stack

• <WHATEVER>
• OP_WHATEVER
• OP_RETURN
• <data>

OP_RETURN makes the TxO unspendable

64/108
Multisignature (M-of-N) Transaction
TX_MULTISIG
<scriptSig> + <scriptPubKey> Stack
• OP_0
• <sig1>
• …
• <sigM>
• <M>
• <pubKey1>
• …
• <pubKeyN>
• <N>
• OP_CHECKMULTISIGVERIFY

65/108
Multisignature (M-of-N) Transaction
TX_MULTISIG
<scriptSig> + <scriptPubKey> Stack
• OP_0 • N
• <sig1> • <pubKeyN>
• … • …
• <sigM> • <pubKey1>
• <M> • M
• <pubKey1>
• <sigM>
• …
• …
• <sig1>
• <pubKeyN>
• 0 OP_CHECKMULTISIGVERIF
Y bug: it consumes one
Fast forward here → <N> extra ignored data

• OP_CHECKMULTISIGVERIFY element

66/108
Multisignature (M-of-N) Transaction
TX_MULTISIG
<scriptSig> + <scriptPubKey> Stack
• OP_0
• <sig1>
• …
• <sigM>
• <M>
• <pubKey1>
• …
• <pubKeyN>
• <N>
→ OP_CHECKMULTISIGVERIFY
• TRUE
67/108
From TX_MULTISIG To TX_SCRIPTHASH
TX_MULTISIG: up to 15-of-15 (1650 bytes signature script limit)

Problems:
• Public keys are published on the blockchain
• A multisig <scriptPubKey> is bigger than the P2PKH one
• Expensive for the sender, beneficial for the receiver

Solution: create a new type of UTxO that shifts the burden into the
redemption <scriptSig>

68/108
From TX_MULTISIG To TX_SCRIPTHASH
• This 65*3+3 bytes <redeem script>
<2 pubk1 pubk2 pubk3 3 OP_CHECKMULTISIG>
• Can be represented by its much shorter 20 bytes HASH160:
<redeem script 20-byte Hash160>
• Lock the transaction with:
OP_HASH160 <redeem script 20-byte Hash160> OP_EQUAL
• Unlock with:
<Sig2> <Sig3> <2 pubk1 pubk2 pubk3 3
OP_CHECKMULTISIG>

69/108
BIP16 Pay-To-Script-Hash (P2SH)
• pay to a script matching this hash, a script that will be presented to
spend this output in the future: the sender does not handle
complexity, the recipient will
• Scripts are coded as addresses: complex scripts are replaced by
shorter fingerprints in the TxO
• A future spending TxIn will contain the redeem script whose hash is
contained in the UTxO: the fee cost for a complex script is shifted
from the current sender to the recipient at future redemption time
• Smaller <scriptPubKey> in the (present) UTxO set, larger <scriptSig>
in the (future) blockchain
• Public keys are revealed at redemption time only

70/108
BIP16 Pay-To-Script-Hash (P2SH)
• P2SH transactions can contain any valid script allowing for
experimentation with new and complex types of transactions
• Transactions that redeem P2SH TxO are considered standard if the
redeem script is, itself, one standard transaction type
• A TxO locked with the hash of an invalid script is valid, but cannot
be spent with a valid TxIn
• P2SH specification is not recursive
• Redeem script cannot include OP_RETURN

71/108
P2SH Addresses (BIP16)
• Base58Check encode of a P2SH use version prefix of 5
(instead of 0), resulting in an address starting with a “3”
(instead of “1”)
• P2SH “3” addresses designate the beneficiary of a bitcoin
transaction as the hash of a script
• Bitcoins sent to “3” P2SH addresses require something
more than the presentation of one public key (hash) and
one private key signature to be spent
• Requirements are designated at the time the address is
created, within the script
72/108
P2SH Example: One Signature
Required
<scriptSig> + <scriptPubKey> Stack
• <sig>
• {[pubkey] OP_CHECKSIG}
• OP_HASH160
• [20-byte-hash of {[pubkey] OP_CHECKSIG}]
• OP_EQUAL

73/108
P2SH Example: Hash of P2PK
<scriptSig> + <scriptPubKey> Stack
→ <sig>
• {[pubkey] OP_CHECKSIG}
• OP_HASH160
• [20-byte-hash of {[pubkey] OP_CHECKSIG}]
• OP_EQUAL

<sig>

74/108
P2SH Example: Hash of P2PK
<scriptSig> + <scriptPubKey> Stack
• <sig>
→ {[pubkey] OP_CHECKSIG}
• OP_HASH160
• [20-byte-hash of {[pubkey] OP_CHECKSIG}]
• OP_EQUAL

{[pubkey] OP_CHECKSIG}
<sig>

75/108
P2SH Example: Hash of P2PK
<scriptSig> + <scriptPubKey> Stack
• <sig>
• {[pubkey] OP_CHECKSIG}
→ OP_HASH160
• [20-byte-hash of {[pubkey] OP_CHECKSIG}]
• OP_EQUAL

[20-byte-hash of {[pubkey]
OP_CHECKSIG}]
<sig>

76/108
P2SH Example: Hash of P2PK
<scriptSig> + <scriptPubKey> Stack
• <sig>
• {[pubkey] OP_CHECKSIG}
• OP_HASH160
→ [20-byte-hash of {[pubkey] OP_CHECKSIG}]
• OP_EQUAL

[20-byte-hash of {[pubkey] OP_CHECKSIG}]


[20-byte-hash of {[pubkey] OP_CHECKSIG}]
<sig>

77/108
P2SH Example: Hash of P2PK
<scriptSig> + <scriptPubKey> Stack
• <sig>
• {[pubkey] OP_CHECKSIG}
• OP_HASH160
• [20-byte-hash of {[pubkey] OP_CHECKSIG}]
→ OP_EQUAL

<sig>

78/108
P2SH Example: Hash of P2PK
Now keep validating using the current stack and
the redeem script as <scriptPubKey>
<scriptPubKey> Stack
• [pubkey]
• OP_CHECKSIG

<sig>

79/108
P2SH Example: Hash of P2PK
<scriptPubKey> Stack
→ [pubkey]
• OP_CHECKSIG

[pubkey]
<sig>

80/108
P2SH Example: Hash of P2PK
<scriptPubKey> Stack
• [pubkey]
→ OP_CHECKSIG

TRUE

81/108
Pay-to-script-hash (P2SH)
https://p2sh.info/dashboard/db/home-dashboard?orgId=1&from=now-5y&to=now

82/108
Homework (1/2)
• Create a Hashlock transaction, i.e. an output locking script
<scriptPubKey> including a hash value, spendable with an
input unlocking script <scriptSig> composed only by the
hash pre-image
• Preferably use the hash value with seven leading zero you
obtained in the first lesson homework
(hint: use OP_HASH265 and OP_EQUAL)

• Check the result with online script engines or python code


• Why is such a transaction not secure?
(hint: who see your spending transaction? What attack could be performed?
Why do we usually rely on asymmetric cryptography?)

83/108
Homework (2/2)
• See also:
https://webbtc.com/tx/09f691b2263260e71f363
d1db51ff3100d285956a40cc0e4f8c8c2c4a80559
b1
• Study the script logic at:
https://webbtc.com/script/09f691b2263260e71f
363d1db51ff3100d285956a40cc0e4f8c8c2c4a80
559b1:0

84/108
Table of Contents
1. Addresses and Wallet Import Formats
2. TxIns, TxOs, UTxOs
3. Bitcoin Script Language
4. Transaction Scripts
5. Odds and Sods
6. Blocks
7. Historical Transactions
85/108
TxIn signature
<scriptSig> Hash Type
Which of the newly created TxOs are covered by the TxIns signature
1. SIGHASH_ALL (default): modifying any TxO in a transaction would require
all the TxIns to be signed again
2. SIGHASH_NONE: any TxO in the transaction can be changed
3. SIGHASH_SINGLE: the TxO of the same index as the TxIn cannot be
changed

2-3 does allow other TxIns to update their sequence numbers, 1 does not

SIGHASH_ANYONECANPAY is combined with the previous ones to indicate


which TxIn is covered: the current TxIn if TRUE, all TxIns if FALSE

86/108
Malleability
• Transaction signature does not cover all the data in a
transaction that is hashed to create the transaction hash
• A transaction’s hash can be manipulated without altering
TxIn, TxOut, and spendibility conditions; e.g.
– DER-encoded ASN.1 octet representation
– for every ECDSA signature (r, s), the signature (r, N-s) is a valid
signature of the same message
– the <scriptSig> is not signed and can be manipulated with
additional data then removed with OP_DROP, etc.

87/108
Segregated Witness (SegWit)
"witness" is a solution to a cryptographic puzzle, e.g.:
<scriptSig>
• every TxIn in a transaction is followed by the witness
data that unlocks its corresponging TxO.
• Segregated Witness moves the <scriptSig> outside of
the transaction data structure, into a separate witness
data structure that complements the transaction
• Clients may request transaction data with or without
the accompanying witness data.
88/108
SegWit Benefits
• Transaction malleability fix
• Signature verification optimization (linear scaling of
sighash operations)
• Increased security for multisig via pay-to-script-hash
(P2SH)
• Script versioning
• Network and storage scaling
• Offline signing improvement
https://bitcoincore.org/en/2016/01/26/segwit-benefits/

89/108
Empty <scriptPubKey>

• Anyone can spend an empty <scriptPubKey>


with a <scriptSig> consisting of OP_TRUE only

• <scriptSig>+<scriptPubKey> = OP_TRUE

90/108
Transaction Chaining and Orphan Transactions
• Transaction chaining: child transaction spends the outputs of the parent
transaction
• The child might arrive before the parent: it is put it in the orphan
transaction pool while waiting for the arrival of its parent
• There is a limit MAX_ORPHAN_TRANSACTIONS to the number of orphan
transactions stored in memory, to prevent a denial-of-service attack
• If a transaction is stuck because of a low fee, child-pay-for-parent means
that a child transaction can pay enough fee for prioritizing both parent and
child

91/108
Replace By Fee - BIP 125

• RBF allows replacing a 0-confirmations


transaction by transmitting another
transaction with a higher fee

• RBF is opt-in
92/108
Table of Contents
1. Addresses and Wallet Import Formats
2. TxIns, TxOs, UTxOs
3. Bitcoin Script Language
4. Transaction Scripts
5. Odds and Sods
6. Blocks
7. Historical Transactions
93/108
Transaction Bundling
• Transactions are bundled in blocks for practical reasons
(shorter chain, single unit of work for validators, faster
history validation)
nonce nonce nonce nonce nonce
prev_hash prev_hash prev_hash prev_hash prev_hash
Tx Tx Tx Tx Tx
Tx Tx Tx Tx Tx
Tx Tx Tx Tx Tx

• Transactions in a block are actually packaged in a Merkle


Tree

94/108
Block Structure
Hash chain of blocks

prev: H( ) prev: H( ) prev: H( )


trans: H( ) trans: H( ) trans: H( )

H( ) H( )

Hash tree (Merkle


tree) of transactions in H( ) H( ) H( ) H( )
each block

transaction transaction transaction transaction 95/108


Block structure
Block structure
Block size
4 bytes

Block header
80 bytes

Number of Transactions
1-9 bytes

Transactions
Variable bytes

The average block


contains more than
2000 transactions.
The maximum block
size, as fixed in Bitcoin
Core, is 1MB

96/108
Block header
Field Description Updated when Size

Block version New software is 4


Version
number released bytes
Block structure
Reference to the hash
Block size Previous A new block comes 32
of the previous
4 bytes block hash in bytes
block
Block header
Hash of the root of
80 bytes A transaction is 32
Merkle root the Merkle tree of
accepted bytes
Number of Transactions the block’s transaction
1-9 bytes
Block time creation
4
Transactions Timestamp time (seconds from Every few seconds bytes
Variable bytes Unix Epoch)

Difficulty Every 2160 blocks 4


target bytes

Partial Inversion
Number used for the 4
Nonce Hash Puzzle is
proof-of-work bytes
solved

97/108
Block structure: example

98/108
https://blockexplorer.com/block/0000000000000000016a4f0250796c29542d6821c42b4837f3e41a6cca20cfaf

99/108
https://blockchain.info/block/0000000000000000016a4f0250796c29542d6821c42b4837f3e41a6cca20cfaf

100/108
Homework
• First halving: provide block height and hash pointer
of the first 25BTC coinbase transaction

• Last halving: provide block height and hash pointer


of the last halving coinbase transaction

Hint: use https://blockexplorer.com/, https://blockchain.info/ or any other block explorer

101/108
Table of Contents
1. Addresses and Wallet Import Formats
2. TxIns, TxOs, UTxOs
3. Bitcoin Script Language
4. Transaction Scripts
5. Odds and Sods
6. Blocks
7. Historical Transactions
102/108
Genesis Block

103/108
Genesis Block
https://blockchain.info/tx/4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
Number Of Transactions: 1; Difficulty: 1; Nonce: 2083236893; Block Reward: 50 BTC
Hash: 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
Merkle Root: 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b

• The genesis block reward can't be spent due to a


quirk in the way that the genesis block is
expressed in the code. It is not known if this was
intentional or an accident
https://en.bitcoin.it/wiki/Genesis_block
https://github.com/bitcoin/bitcoin/blob/9546a977d354b2ec6cd8455538e68fe4ba343a44/src/main.cpp#L1668

104/108
First Transaction, From Satoshi to Hal Finney
https://blockchain.info/tx/f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16

105/108
First Purchase: Pizza Transaction
https://bitcointalk.org/index.php?topic=137.msg1195#
msg1

106/108
First Purchase: Pizza Transaction
https://blockchain.info/tx/a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d

107/108
Bibliography
• A. Narayanan, et al., “Bitcoin and Cryptocurrency
Technologies”, chapter 3
• Pedro Franco, “Understanding Bitcoin”, Wiley,
chapter 6
• Andreas Antonopoulos, “Mastering Bitcoin”,
O'Reilly, chapters 2, 4, 6, 7
• https://en.bitcoin.it/wiki/Script
108/108

You might also like