A cryptocurrency is a distributed system in which agents who do not trust each other keep a shared ledger of payments. Before we can study how they agree on the ledger, we need three tools from cryptography: hash functions, hash pointers and digital signatures. The next lecture, Bitcoin, puts them together into cryptocurrencies.
This lecture follows chapter 1 of Narayanan, Bonneau, Felten, Miller and Goldfeder, Bitcoin and Cryptocurrency Technologies (Princeton University Press, 2016). A free draft of the book, video lectures and programming assignments are at bitcoinbook.cs.princeton.edu.
Every hash on this page is real The figures compute SHA-256, the hash function Bitcoin uses, in your browser. Type into them, change them, and try to break them.
A hash function H maps an input string of
any size to an output of fixed size, and it is fast to
compute. SHA-256 maps any input to 256 bits, written as 64 hexadecimal
digits. The output is often called a digest: a short summary of
a long message.
Three properties we will assume A cryptographic hash function is collision resistant, hiding and puzzle friendly. The rest of this section explains each one and shows how they are used in cryptocurrency.
Inputs x ≠ y collide if
H(x) = H(y). Collisions must exist: there are infinitely
many inputs and only finitely many outputs (2256 for
SHA-256), so some outputs are shared
by many inputs (the pigeonhole principle). A hash function is
collision resistant if a collision — x ≠ y
where H(x) = H(y) — cannot be found in a reasonable
number of computational steps.
No hash function has been proved collision resistant. We use functions such as SHA-256 that experts have attacked for years without finding a collision. Some hash functions are clearly not collision resistant: one that returns the last 8 bits of its input collides on any two inputs that end in the same byte.
Question for you. Suppose H returns a 4-bit number,
so there are 16 possible outputs. Keep an array D of 16
entries, all empty. Repeatedly pick a random input x,
compute y = H(x); if D[y] is empty, store
x there, and otherwise D[y] and
x collide. How many times will you have to pick an input before
you find the first collision? In the worst case you need 17 inputs: the first
16 could all land in different entries. How many do you need on
average?
Let the hash have N possible outputs. The first collision
happens at input number k if the first k−1
inputs land in different entries and input k lands in one
of the k−1 occupied entries:
This is the birthday paradox: in a room of only 23 people, the
probability that two share a birthday is about 1/2, although there are
365 birthdays. A collision is expected after about
√N inputs. For an n-bit hash,
N = 2n, so a collision is expected after about
2n/2 inputs — for SHA-256,
2128 ≈ 3×1038, a very large number.
N = 256 possible outputs,
one per cell. Each step hashes a new random input and fills its cell.
The hunt ends when an input lands in a cell that is already full. You
might expect to need over a hundred inputs; you usually need about
20, close to √(πN/2) ≈ 20. Press
Run 1,000 hunts to see the spread.
How collision resistance helps: message digests. If
H(x) = H(y), we assume x = y, since
H is collision resistant. To check that a file you downloaded is the file
that was published, compare its hash with the published hash.
Su makes a bet with Al that she can predict whether Al will wear shorts or trousers the next day. She puts her prediction in a sealed envelope and gives it to Tim for safekeeping. After Al appears the next day, they get the envelope from Tim and check whether Su was right.
Next, they want to use digital technology instead of depending on Tim.
Su publishes y = H(x) where H is
a collision-resistant hash, but Su keeps x secret.
After Al appears the next day, Su reveals x; Al checks
if H(x) = y; and they settle the bet.
If Al can find x from y and H
then Al can choose what to wear to falsify Su's prediction.
Question for you. Can x be discovered?
Yes. There are only two possibilities. Al computes H for each
possibility and finds the one that matches y.
Though H is collision resistant, H
does not hide information that comes from a small set.
The fix is to add a secret random value r, chosen
from a spread-out distribution, for example 256 random bits. Su
computes y = H(r ‖ x), where ‖ means
concatenation. Su publishes y and H but not
r or x. Now Al must guess both r and
x: 2 × 2256 possibilities. There are only
two predictions, but r alone makes guessing hopeless.
The next day Su reveals both r and x, and Al
checks that H(r ‖ x) = y. The value y
that Su publishes is called her commitment; from now on we
write it c.
Hiding
H is hiding if, when r is chosen from a
very spread-out distribution, there is no feasible way to find
x from H(r ‖ x).
r of
the length you choose. Al sees only y and tries every pair
(r, prediction) until one matches. With no r
he needs at most 2 tries. Every extra bit of r doubles the
work: at 20 bits he needs up to two million tries, and with a 256-bit
r he would need up to 2 × 2256, about
2×1077.
Hiding protects Su from Al. Now look at it from Al’s side. Suppose
Su predicted shorts, and the next morning Al appears in trousers. Su
would like to claim that she predicted trousers. To do that, she must
reveal some r′ with
H(r′ ‖ trousers) = c = H(r ‖ shorts):
a collision, which she cannot find.
So the same scheme stops both of them. It lets Su commit to a prediction now and reveal it later, so that Al cannot learn it early and Su cannot change it. It is called a commitment scheme:
# commit: Su picks a fresh random nonce r and publishes c r = random_256_bits() c = H(r ‖ prediction) # reveal: Su publishes r and prediction; anyone can check def verify(c, r, prediction): return H(r ‖ prediction) == c
A commitment is not encrypted, and it is never decrypted. Su
opens it by revealing r and her prediction, and anyone can
check them against c. And Tim is no longer needed:
Su can publish c anywhere, because nobody has to be
trusted to hold it.
A secret value used once is called a nonce. Choose a
new r for every commitment: if Su bets with Al
every day and reuses r, equal predictions produce equal
commitments, and Al learns when she predicts the same thing again.
r, predicts shorts, and
publishes c = H(r ‖ shorts). 2. The next
morning Al appears in trousers. 3. Su reveals honestly; Al
recomputes the hash and it matches c: Su loses the bet.
4. Su tries instead to claim she predicted trousers, with the
same r. The hash does not match. To succeed she would
have to find a collision.
A search puzzle is given by a hash function H, a
puzzle id id, and a set Y of target outputs.
A solution is any x with
H(id ‖ x) in Y.
Puzzle friendly
Let H have N possible outputs.
H is puzzle friendly if there is no way to solve a
search puzzle much faster than trying random values of
x. Each try then succeeds with probability about
|Y| / N, so the expected number of tries is about
N / |Y|.
These numbers are approximate because no real hash function is
perfect: its outputs are spread almost, but not exactly, evenly over
the N possibilities.
Example. SHA-256 returns 256 bits, so it has
N = 2256 possible outputs. Each try succeeds
with probability about |Y| / 2256, and the
expected number of tries is about 2256 / |Y|.
So the size of Y sets the difficulty of the puzzle.
If Y is the set of all possible outputs, the first try succeeds.
If Y is half the set of outputs, the expected number of tries
to get a value in Y is about 2.
If Y is the set of outputs in which the first
d bits are zero, then increasing d by 1
reduces the size of Y by half, and the expected number of tries to
get a value in Y doubles. This is Bitcoin’s
mining puzzle, and it is the subject of a later lecture.
x such that
H(id ‖ x) begins with d zero bits
(shown in teal). Each press of Solve numbers the id #1, #2,
…, so each press is a new puzzle. The only method is to try x = 0, 1, 2,
… Press Solve several times: the number of tries varies
a lot from puzzle to puzzle, but averages about 2d. Raise
d by one and the average doubles.
Question for you. Suppose you have a function f that
maps inputs of exactly m + n bits to outputs of
m bits. How would you build a hash function for inputs of
any length?
The Merkle–Damgård transform does it, and SHA-256 is
built this way. Its compression function f takes
768 bits — a 256-bit chaining value and a 512-bit block of
the message — and returns 256 bits.
B1,
…, Bk.IV, given in the SHA-256 standard.C0 = IV, and for i > 0,
Ci = f(Ci−1, Bi).
The hash is Ck.
Why it is secure
If the compression function f is collision resistant, then
so is the hash built from it. A collision in the whole hash would give
a collision in f at some step of the chain.
f. These are SHA-256’s real chaining values (the
first 10 of 64 hex digits are shown), and the last one is the
SHA-256 hash of the message. Edit the message: every chaining value
after the block you changed is different.
A hash pointer to data D is a pair
(ptr, H(D)): ptr says where
D is, and H(D) lets you check that
D has not changed. If the
data to which ptr points is modified from D
to D′, while the hash pointer
(ptr, H(D)) remains unchanged, then an agent can detect
the modification because H(D′) ≠ H(D): since
H is collision resistant, nobody can find a
D′ ≠ D with H(D′) = H(D).
So the data pointed to by a hash pointer is tamper-evident,
provided the hash pointer itself is kept somewhere safe.
Question for you. Design a tamper-evident ledger: a sequence of transactions that nobody can modify without others being able to tell.
A block chain is a linked list that uses hash pointers rather
than regular pointers. The list starts
with a standard genesis block — the zeroth block,
B0, in the list.
The k-th block, Bk, for k > 0, contains (1) a hash pointer
(pk−1, H(Bk−1)) and
(2) data Dk, where pk−1 is a
pointer to Bk−1.
An agent gets access to the list from the hash pointer to the head of
the list.
Tamper evidence
Lemma: If the hash pointer
(pk, H(Bk)) to the k-th block
remains unchanged, then a change to any block Bi, for
i ≤ k, is detectable.
If block Bk is changed to Bk′, the change is detected because H(Bk′) ≠ H(Bk): since H is collision resistant, nobody can find a different block with the same hash. In particular, this proves the case k = 0: a change to the genesis block is detected.
If k > 0 and Bk is unchanged, then the hash pointer that Bk contains, (pk−1, H(Bk−1)), is unchanged too. So, by induction, a change to any of Bk−1, …, B0 is detectable.
A Merkle tree is a binary tree that uses hash pointers in place of regular pointers. The tree is used as a tamper-evident data structure for storing data. The data is stored in the leaves of the tree. The verifier already holds the hash of the root, from a source it trusts. To show that data D is in the tree and has not changed, the prover supplies D and the hashes along D’s path to the root: one sibling hash per level. The verifier rehashes up the path and compares the result with the root it holds.
Using the same reasoning as for block chains, any change to D is detectable. The root must come from the verifier, not from the prover: a prover who could supply its own root could build any tree it liked.
With n items, the proof requires about
log2 n hashes: 20 hashes for a million
transactions. Checking one item in a block chain of n
blocks can mean rehashing all n blocks; a Merkle tree
needs only log2 n. Bitcoin puts each
block’s transactions in a Merkle tree.
If the leaves are kept sorted, a Merkle tree can also prove non-membership: show the two adjacent leaves between which the missing item would be, with their paths to the root.
Digital signatures with secret and public keys are implemented in three parts.
1. Create the keys. The owner generates a pair of keys. The
owner keeps the secret key sk to itself, and
publishes the public key pk for everyone.
(sk, pk) = generateKeys(keysize)
2. Sign a message. The owner signs a message with its secret
key, and sends the message together with the signature. In the
code below, the function sign is the signing algorithm.
sig = sign(sk, message)
send (message, sig)
3. Verify the message. A receiver checks the signature with the
owner’s public key. verify returns True or False.
ok = verify(pk, message, sig)
Bitcoin uses ECDSA, which has no encryption step for signing messages. Encryption is a different tool for keeping a message secret.
Unforgeability is defined by a game
between a challenger, who holds the secret key sk, and an
attacker, who knows only the challenger’s public key
pk. The attacker may ask the challenger to sign any
messages it chooses, a reasonable number of times — for example
230, but not 2128.
Then the attacker must produce a signature that verifies on a
new message (which is different from the messages that the attacker
asked the challenger to sign). The scheme is
unforgeable if every attacker that runs for a reasonable time,
and asks for a reasonable number of signatures, wins with negligible
probability.
pk.
The attacker picks messages and the challenger signs them. Then the
attacker submits a new message with a signature it has made up.
The signatures it has seen are no help: each belongs to its own
message. verify fails, and the attacker loses. (The
σ values here stand in for real signatures; the page does not
implement a signature scheme.)
Sign the hash. A signature scheme signs short messages. To sign
a long message M, sign H(M); because
H is collision resistant, this is as good as signing
M. In particular, to sign a whole ledger kept as a block
chain, sign the hash pointer to its head: that one signature covers
every block in the chain.
Ana wants to send Ben a
message M that only Ben can read, and Ben wants to be sure
it came from Ana and was not changed.
sig = sign(skAna, M).(M, sig) with Ben’s
public encryption key, msg = encrypt(pkBen, (M, sig)),
and sends msg to Ben.msg with his secret key and gets
(M, sig) = decrypt(skBen, msg).verify(pkAna, M, sig) = True, then Ana sent
M and it was not changed.
Decentralized identity
An agent can make a new public key, secret key pair by calling
generateKeys. There is no registry and no central
authority required to generate the keys.
An agent can use different public keys that it generates as separate identities.
An agent X who uses public key, secret key pairs
(pkX0, skX0)
and (pkX1, skX1) can send some
messages using (pkX0, skX0) and others using
(pkX1, skX1).
A receiver who gets a message signed with skX0
checks it with pkX0; the secret key never
leaves X. The receiver knows only that the message is from the agent
that holds that key pair, but cannot learn the agent’s name from
the key.
The anonymity offered by public keys is limited: every message sent with one key is linked to that key, and patterns in those messages can reveal who is behind it. In Bitcoin these identities are called addresses; an address is the hash of a public key.
Next Bitcoin uses these tools. It starts with two simple cryptocurrencies, Goofycoin and Scroogecoin, and the double-spending problem, and ends with Bitcoin itself.
| Tool | Property | What it gives us |
|---|---|---|
| Hash function | Collision resistant | A short digest that identifies a document |
| Hiding, with collision resistance | Commitments: commit now, reveal later, no change possible | |
| Puzzle friendly | Search puzzles whose difficulty we can set | |
| Hash pointer | Detects any change to the data | Block chains and Merkle trees |
| Digital signature | Unforgeable | Authorised payments; public keys as identities |
r for every
commitment? Give an example in which reusing r leaks
information.d = 20?
Bitcoin sets the difficulty so that the whole network solves one
puzzle about every 10 minutes. If the network computes
1020 hashes per second, about how many leading zero bits
does that correspond to?H(M) is as good as signing
M, if H is collision resistant.