Week 2
Cryptography You Need
- Blockchain from zero, week 2 of 12
- Hashes, keys, signatures and Merkle trees, with live Python
Outcomes
What You Will Be Able To Do
- Compute SHA-256 hashes in Python
- Explain public and private keys
- Sign and verify a message
- Build a Merkle root
- Place each tool inside a block
Map
Three Needs, Four Tools
- Tamper evidence: hash functions
- Proof of ownership: keys and signatures
- Compact commitment: Merkle trees
- Open checking: all of these are public algorithms
| Need | Tool |
|---|
| Detect change | Hash function |
| Prove authorship | Digital signature |
| Summarise many items | Merkle tree |
| Identify an owner | Public key |
Hashing
Hash Function: A Digital Fingerprint
- Any input in, fixed-size output out
- SHA-256 gives 256 bits, 64 hex characters
- Same input always gives same output
- Fast to compute
Security
Properties That Matter
- Avalanche: one changed character changes everything
- Preimage resistant: cannot go backwards
- Collision resistant: no two inputs share a hash
Live code
Demo: Hashing In Python
- Two sentences differ by one digit
- Compare the digests side by side
import hashlib
a = hashlib.sha256(b'Alice pays Bob 5').hexdigest()
b = hashlib.sha256(b'Alice pays Bob 6').hexdigest()
print(a)
print(b)
print(a == b)
Tamper evidence
Hashes Chain Blocks
- Each block stores the previous block's hash
- Editing an old block changes its hash
- The next block's stored link no longer matches
- Every later block shows the mismatch
Block 1: hash A
Block 2: prev A, hash B
Block 3: prev B, hash C
Edit Block 1 -> hash A'
Block 2 says prev A: mismatch
Key pairs
Public And Private Keys
- Private key: secret number, never shared
- Public key: derived from private, safe to share
- Private to public is easy
- Public to private is infeasible
Responsibility
Your Key Is Your Authority
- Whoever holds the private key controls the funds
- No support desk can reverse a loss
- Back up keys offline
- Never type a key into unknown websites
Authorisation
Digital Signatures
- Sign: message plus private key gives a signature
- Verify: message, signature and public key give yes or no
- Proves the sender and proves the message is unchanged
Live code
Demo: Sign And Verify
- Ed25519 with the cryptography package
- Bitcoin and Ethereum use ECDSA, same pattern
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.exceptions import InvalidSignature
key = Ed25519PrivateKey.generate()
sig = key.sign(b'Alice pays Bob 5')
key.public_key().verify(sig, b'Alice pays Bob 5')
try:
key.public_key().verify(sig, b'Alice pays Bob 500')
except InvalidSignature:
print('rejected')Commitment
Why A Merkle Tree
- A block holds thousands of transactions
- We want one short fingerprint for all of them
- We want to prove one item sits inside
Merkle root
Building The Tree
- Hash each transaction to form leaves
- Pair, join, hash to form the next layer
- Repeat until one hash remains
- Odd layer: duplicate the last hash
| Level | Contents |
|---|
| Leaves | Hash of each transaction |
| Middle | Hash of each pair |
| Root | One hash for everything |
tx1 tx2 tx3 tx4
h1 h2 h3 h4
h12 h34
rootLive code
Demo: Merkle Root In Python
- Short function, about ten lines
- Change one leaf and the root changes
import hashlib
def h(b):
return hashlib.sha256(b).digest()
def merkle_root(txs):
level = [h(t) for t in txs]
while len(level) > 1:
if len(level) % 2 == 1:
level.append(level[-1])
level = [h(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
return level[0].hex()Putting it together
All Tools In One Block
- Header: previous hash, Merkle root, timestamp, counter
- Body: transactions, each signed
- Signatures prove authority to spend
- Hashes make history tamper-evident
Header { prev_hash, merkle_root, time, nonce }
Body { tx1+sig, tx2+sig, tx3+sig }Week 2 in five lines
Recap
- Hashes: fixed-size fingerprints
- Key pairs: secret private, shareable public
- Signatures: prove approval and integrity
- Merkle trees: one root commits to many items
- Together they build tamper-evident chains
Week 3
Next Week: Bitcoin
- UTXOs and transactions
- Blocks, mining and proof of work
- 21 million supply and the halving
- A guided tour of the 2008 whitepaper
Hands-on
Questions And Exercise
- Hash two near-identical sentences
- Sign, verify and tamper with a message
- Write merkle_root and break it on purpose