Algorithms · Working together

Merkle trees and content addressing

Git’s secret: every file is named by its fingerprint. Change one letter and you can tell exactly which folders changed, by comparing a few hashes.

The problem

Git (Linus Torvalds, 2005) has to track whole projects: thousands of files in nested folders, snapshotted again and again. Every time you commit, Git must answer: what changed since last time?

It also must not waste space. If a thousand snapshots contain the same unchanged file, Git shouldn't keep a thousand copies.

The obvious way

Compare the two snapshots file by file, byte by byte. It works, but the cost grows with the size of the whole project, even if you edited a single comma. A project with 120 files means 120 comparisons to find one edit. A huge project means a huge wait for a tiny change.

The clever idea

Imagine every file wears a name tag that is a fingerprint of its contents. Change one letter and the tag changes completely. Now a folder gets a tag too, made from the tags of everything inside it. Two folders with the same tag must hold identical stuff, so you can skip them without opening anything.

That's Git. Each file (a blob) is stored under the SHA-1 hash of its contents. Each folder (a tree) lists its children's hashes, so its own hash depends on everything inside. A commit points to the top tree. Identical files get the same name, so they're stored only once.

How the code does it

build works bottom-up. A file's hash comes straight from its text (this line). A folder first hashes its children, then hashes their names and fingerprints glued together. That's why editing one file changes its folder's hash and the root's hash, and nothing else.

walk compares two snapshots top-down. At every node it asks one question: do the hashes match? If yes, the whole subtree is skipped. Here that means the root, then dir3, then only its 20 files: 27 comparisons, against 120 for the brute-force loop. Both ways report the same changed file, but one never looked at five of the six folders.

Trade-offs

Hashing isn't free: you must read every byte once to compute a fingerprint, and any change forces re-hashing the path from that file up to the root. It also assumes two different contents never share a hash, which is why Git is moving to SHA-256 as an option. If you compare just once and never again, or the data is tiny, simply comparing directly is simpler and just as fast.

Where else you'll see it

Merkle trees also appear in file-sync tools, databases that compare replicas, and blockchains. To see the real thing, browse the source at github.com/git/git.

You edit one file inside dir3. Which hashes change?

  • Only that file's hash
  • That file, dir3, and the root
  • Every file in the project
Show the answer

That file, dir3, and the root. A folder's hash is built from its children's hashes, so the change ripples up the path to the root. Siblings and other folders keep their hashes.

Change it and see
  • Change range(6) to range(30)
  • Edit two files in different folders
  • Remove [:7] to see full hashes

The code

Python, with what each line means beside it. It compares the clever way with comparing every file byte by byte.

import copy, hashlibBring in tools for copying and hashing
def sha(text):Define a fingerprint maker for text
return hashlib.sha1(text.encode()).hexdigest()[:7]Hash the text, keep first seven characters
def build(node):Define a function that fingerprints a whole tree
if isinstance(node, str):If this is a file's text...
return {"hash": sha(node), "kids": {}}Fingerprint its contents, no children
kids = {n: build(c) for n, c in sorted(node.items())}Otherwise fingerprint each child first, in sorted order
joined = "".join(n + k["hash"] for n, k in kids.items())Glue child names and fingerprints together
return {"hash": sha(joined), "kids": kids}Fingerprint that glue; this is the folder's hash
def walk(a, b, path, count):Define a function comparing two snapshots
count[0] += 1Count this visit
if a["hash"] == b["hash"]:If fingerprints match...
return []Nothing changed here; skip everything below
if not a["kids"]:If this is a file...
return [path]Report this path as changed
found = []Start an empty list of changes
for name in a["kids"]:For each child in this folder
found += walk(a["kids"][name], b["kids"][name], path + "/" + name, count)Compare old and new child, collect changes
return foundHand back all changes found
def flat(node, path=""):Define the obvious way: list every file
if isinstance(node, str):If this is file text...
return {path: node}Return its path paired with contents
return {k: v for n, c in node.items() for k, v in flat(c, path + "/" + n).items()}Otherwise merge the lists from every child
project = {f"dir{d}": {f"f{i}.txt": f"data {d}-{i}" for i in range(20)} for d in range(6)}Make a project: six folders, twenty files each
edited = copy.deepcopy(project)Copy the whole project
edited["dir3"]["f7.txt"] = "data 3-7 EDITED"Edit exactly one file in the copy
old, new = build(project), build(edited)Fingerprint both versions
show({n: k["hash"] for n, k in old["kids"].items()}, "before: folder fingerprints")Show folder fingerprints before the edit
show({n: k["hash"] for n, k in new["kids"].items()}, "after: dir3 changed")Show them after; one folder differs
a, b = flat(project), flat(edited)Flatten both versions into path-to-text tables
slow = [p for p in a if a[p] != b[p]]Obvious way: compare all 120 files
count = [0]Start a comparison counter
fast = walk(old, new, "", count)Clever way: walk down only where hashes differ
show({"obvious way": len(a), "clever way": count[0]}, "comparisons")Show how many comparisons each way needed
print(slow == fast, fast)Confirm both found the same file

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on working together