How Much of Bitcoin's Code Did Satoshi Actually Write?
On January 8, 2009, Satoshi announced Bitcoin v0.1 with a line that most people skim past: "Windows only for now. Open source C++ code is included." I went back to that archive, counted every line, and lined the code up against the open source libraries Satoshi had on the shelf in 2008. Here's how much of the first Bitcoin was written by Satoshi, what was borrowed, and whether the whole thing was invented or discovered.
There's a romantic version of the Bitcoin origin story in which a lone genius sits in a dark room and types out a new form of money from scratch, line by line, like a monk copying a manuscript. It's a nice story. It's also not how software gets written, not in 2008 and not today. Nobody serious writes their own elliptic curve math, their own database engine or their own windowing toolkit when battle-tested open source versions exist. Satoshi certainly didn't.
But "Satoshi used libraries" is the kind of half-truth that gets repeated on X by people who want to make Bitcoin sound like a copy-paste job, and also by people who want to make Satoshi sound like a demigod who merely "discovered" something that was always there. Both camps would benefit from looking at the actual code. So that's what I did. I took the bitcoin-0.1.0 archive preserved by the Satoshi Nakamoto Institute (the MD5 and SHA-1 of my download match the hashes the Institute publishes), the four-file preview Satoshi e-mailed to a handful of cryptographers in November 2008, and the exact library versions that were available at the time: Crypto++ 5.5.2, OpenSSL 0.9.8h, Berkeley DB 4.7.25 and Hashcash 1.22. Then I counted, diffed and compared.
If you've read my essay Who is Satoshi? What the code says, you know I like receipts. This one has plenty of them, and every snippet below is copied from the original files, with the file name and line number so you can check me.
What Was Actually in the Box?
The bitcoin-0.1.0 archive is tiny by modern standards: a Windows executable, two DLLs (one of them is OpenSSL's libeay32.dll), a license, a readme and a src folder with the C++ sources, two makefiles and the GUI project file. Fun detail: the readme inside calls the release "BitCoin v0.01 ALPHA", with a capital C that didn't survive the year.
The most honest description of what Satoshi borrowed is in that readme, in Satoshi's own words. It lists four libraries you had to download separately in order to build Bitcoin:
17Dependencies
18------------
19Libraries you need to obtain separately to build:
20
21 default path download
22wxWidgets \wxWidgets http://www.wxwidgets.org/downloads/
23OpenSSL \OpenSSL http://www.openssl.org/source/
24Berkeley DB \DB http://www.oracle.com/technology/software/products/berkeley-db/index.html
25Boost \Boost http://www.boost.org/users/download/
26
27Their licenses:
28wxWidgets LGPL 2.1 with very liberal exceptions
29OpenSSL Old BSD license with the problematic advertising requirement
30Berkeley DB New BSD license with additional requirement that linked software must be free open source
31Boost MIT-like licenseLook at how Satoshi describes those licenses: OpenSSL comes "with the problematic advertising requirement", Berkeley DB demands that linked software be open source. This is somebody who read the license files, which is more than I can say about most developers in 2026. And notice that Bitcoin itself went out under MIT/X11, the most permissive of the bunch. In 2010 Satoshi explained on BitcoinTalk that "The MIT license is compatible with all other licenses and commercial uses", which is a polite way of saying: take it, fork it, build on it. And judging by our list of every Bitcoin fork, people certainly did.
Those four libraries were linked, not copied. They're dependencies, the same way your browser depends on your operating system. The question of what Satoshi copied into the Bitcoin source tree itself has a much shorter answer, and we'll get to it in a minute. First, the numbers.
The Numbers: How Much of Bitcoin v0.1 Is Satoshi's?
I ran cloc 2.02 over the v0.1.0 src folder and sorted every C++ file into one of three buckets, based on its header and on a diff against the upstream source:
- Written by Satoshi: every file whose header says "Copyright (c) 2009 Satoshi Nakamoto" and that wasn't generated by a tool.
- Generated by a tool:
uibase.cppanduibase.h, which open with "C++ code generated with wxFormBuilder (version Apr 16 2008)" and "PLEASE DO "NOT" EDIT THIS FILE!". Satoshi designed the windows in a visual editor; the editor wrote this code. - Copied from Crypto++:
sha.cppandsha.h, whose headers say "SHA routines extracted as a standalone file from: Crypto++: a C++ Class Library of Cryptographic Schemes Version 5.5.2 (9/24/2007)".
- Written by Satoshi: 12,209 lines (83.9%)
- Generated by wxFormBuilder: 1,801 lines (12.4%)
- Copied from Crypto++ 5.5.2: 537 lines (3.7%)
| Origin | Files | Lines of code | Share |
|---|---|---|---|
| Written by Satoshi: core engine | main, net, script, serialize, uint256, bignum, db, util, irc, base58, key, headers | 9,263 | 63.7% |
| Written by Satoshi: Windows GUI logic | ui.cpp, ui.h | 2,691 | 18.5% |
| Written by Satoshi: unused marketplace | market.cpp, market.h | 255 | 1.8% |
| Generated by wxFormBuilder | uibase.cpp, uibase.h | 1,801 | 12.4% |
| Copied from Crypto++ 5.5.2 (Wei Dai) | sha.cpp, sha.h | 537 | 3.7% |
| Total C++ in v0.1.0 | 26 files | 14,547 | 100% |
So the short answer is about 84% of the C++ in Bitcoin v0.1 was written by hand by Satoshi, 12% was generated by the GUI designer, and less than 4% (one SHA-256 implementation) was copied from someone else. If you only count the engine (everything except the user interface and an unused marketplace module), Satoshi's hand-written core is 9,263 lines of code, and it contains zero lines copied from anyone else's project. The SHA-256 files are used by the miner, and I'll explain why in the next section.
For a sense of scale, the libraries Satoshi linked against dwarf that core. OpenSSL 0.9.8h has roughly 206,000 lines of code in its crypto and ssl folders alone, and Berkeley DB 4.7.25 has about 141,000 lines of C and C++. Bitcoin used a small slice of each, but the point stands: Satoshi built a 12,000-line house on top of foundations that other people spent decades pouring. That's not a criticism. That's engineering.
One more caveat before somebody yells at me in the comments. Line counts measure volume, not difficulty. I'd bet the 2,407 lines of ui.cpp took far less thinking than the 868 lines of script.cpp. Keep that in mind; we'll come back to it.
The One File Satoshi Copied: Wei Dai's SHA-256
Here's the irony that I can't get over. The only code in Bitcoin v0.1 that Satoshi lifted from another project came from Crypto++, the C++ library written by Wei Dai. The same Wei Dai who published b-money in 1998. The same Wei Dai who became reference [1] in the Bitcoin whitepaper. Satoshi's first e-mail to Wei Dai, sent on August 22, 2008, opens like this:
"I was very interested to read your b-money page. I'm getting ready to release a paper that expands on your ideas into a complete working system. Adam Back (hashcash.org) noticed the similarities and pointed me to your site."
So Wei Dai's ideas went into the paper and Wei Dai's code went into the miner. Let's look at how much Satoshi changed. On the left is Bitcoin; on the right is Crypto++ 5.5.2, checked out from the official repository at the CRYPTOPP_5_5_2 tag.
1// This file is public domain
2// SHA routines extracted as a standalone file from:
3// Crypto++: a C++ Class Library of Cryptographic Schemes
4// Version 5.5.2 (9/24/2007)
5// http://www.cryptopp.com
6
7// sha.cpp - modified by Wei Dai from Steve Reid's public domain sha1.c
8
9// Steve Reid implemented SHA-1. Wei Dai implemented SHA-2.
10// Both are in the public domain.
11
12#include <assert.h>
13#include <memory.h>
14#include "sha.h"
15
16namespace CryptoPP
17{1// sha.cpp - modified by Wei Dai from Steve Reid's public domain sha1.c
2
3// Steve Reid implemented SHA-1. Wei Dai implemented SHA-2.
4// Both are in the public domain.
5
6#include "pch.h"
7
8#ifndef CRYPTOPP_IMPORTS
9
10#include "sha.h"
11#include "misc.h"
12#include "cpu.h"
13
14NAMESPACE_BEGIN(CryptoPP)141void SHA256::Transform(word32 *state, const word32 *data)
142{
143 word32 W[16];
144 word32 T[8];
145 /* Copy context->state[] to working vars */
146 memcpy(T, state, sizeof(T));
147 /* 64 operations, partially loop unrolled */
148 for (unsigned int j=0; j<64; j+=16)
149 {
150 R( 0); R( 1); R( 2); R( 3);
151 R( 4); R( 5); R( 6); R( 7);
152 R( 8); R( 9); R(10); R(11);
153 R(12); R(13); R(14); R(15);
154 }
155 /* Add the working vars back into context.state[] */
156 state[0] += a(0);
157 state[1] += b(0);
158 state[2] += c(0);
159 state[3] += d(0);
160 state[4] += e(0);
161 state[5] += f(0);
162 state[6] += g(0);
163 state[7] += h(0);138void SHA256::Transform(word32 *state, const word32 *data)
139{
140 word32 W[16];
141 word32 T[8];
142 /* Copy context->state[] to working vars */
143 memcpy(T, state, sizeof(T));
144 /* 64 operations, partially loop unrolled */
145 for (unsigned int j=0; j<64; j+=16)
146 {
147 R( 0); R( 1); R( 2); R( 3);
148 R( 4); R( 5); R( 6); R( 7);
149 R( 8); R( 9); R(10); R(11);
150 R(12); R(13); R(14); R(15);
151 }
152 /* Add the working vars back into context.state[] */
153 state[0] += a(0);
154 state[1] += b(0);
155 state[2] += c(0);
156 state[3] += d(0);
157 state[4] += e(0);
158 state[5] += f(0);
159 state[6] += g(0);
160 state[7] += h(0);When I diffed the two sha.cpp files with whitespace ignored, the only differences were Satoshi's five-line header comment, the include lines, the namespace macros, the closing #endif and one preprocessor block that picks an SSE2-aligned table on x86. Every line of actual hashing logic is identical. The header file is a different story: Crypto++ builds its hash classes out of templates spread across sha.h, iterhash.h and misc.h, and Satoshi flattened all of that into one self-contained header with plain classes.
131// implements the SHA-256 standard
132class SHA256
133{
134public:
135 typedef word32 HashWordType;
136 static void InitState(word32 *state);
137 static void Transform(word32 *digest, const word32 *data);
138 static const char * StaticAlgorithmName() {return "SHA-256";}
139};19//! implements the SHA-256 standard
20class CRYPTOPP_DLL SHA256 : public IteratedHashWithStaticTransform<word32, BigEndian, 64, 32, SHA256>
21{
22public:
23 static void CRYPTOPP_API InitState(HashWordType *state);
24 static void CRYPTOPP_API Transform(word32 *digest, const word32 *data);
25 static const char * CRYPTOPP_API StaticAlgorithmName() {return "SHA-256";}
26};Why bother? Because in v0.1 this code is only used in one place: BlockSHA256() in main.cpp, the function the miner calls millions of times. Everything else in Bitcoin (block hashes, transaction IDs, addresses) goes through OpenSSL's SHA256() via the Hash() and Hash160() helpers in util.h. Satoshi wanted a stripped-down transform the miner could call on raw 64-byte blocks, without OpenSSL's context bookkeeping. It's a performance hack, and it stayed one: in July 2010 Satoshi upgraded it and described the process like this.
"I added a subset of the Crypto++ 5.6.0 library to the SVN. I stripped it down to just SHA and 11 general dependency files."
And yes, this is legal and polite. Crypto++'s license places the individual files in the public domain, and Satoshi kept "This file is public domain" at the top along with the credit to Steve Reid (SHA-1) and Wei Dai (SHA-2). Credit where credit is due, literally.
A small aside for the Satoshi hunters: in my stylometry essay, Wei Dai's Crypto++ came out as the closest suspect codebase to Satoshi's, and still more than six times farther from Satoshi than Satoshi ever got from himself. Reading these two files side by side, you can see why it's close and why it isn't a match: the copied file looks like Wei Dai, and everything around it looks like somebody else.
OpenSSL Did the Cryptography, Satoshi Did the Wrapping
If Crypto++ provided one hash function, OpenSSL provided the rest of the cryptographic muscle: SHA-256 for everything except the miner, RIPEMD-160 for addresses, ECDSA on the secp256k1 curve for signatures, and arbitrary-precision integers for the difficulty math. Satoshi didn't copy OpenSSL's code into Bitcoin. Instead, Satoshi wrote thin C++ classes around OpenSSL's C functions, which is exactly what a sane developer should do with cryptography.
The key class is a good example. On the right are the prototypes in OpenSSL 0.9.8h's ec.h and the curve ID in obj_mac.h; on the left is the wrapper Satoshi wrote around them.
43class CKey
44{
45protected:
46 EC_KEY* pkey;
47
48public:
49 CKey()
50 {
51 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
52 if (pkey == NULL)
53 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
54 }
⋮
75 void MakeNewKey()
76 {
77 if (!EC_KEY_generate_key(pkey))
78 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
79 }crypto/objects/obj_mac.h:360
360#define SN_secp256k1 "secp256k1"
361#define NID_secp256k1 714
crypto/ec/ec.h:303
303EC_KEY *EC_KEY_new(void);
304EC_KEY *EC_KEY_new_by_curve_name(int nid);
305void EC_KEY_free(EC_KEY *);
306EC_KEY *EC_KEY_copy(EC_KEY *, const EC_KEY *);
307EC_KEY *EC_KEY_dup(const EC_KEY *);
⋮
330/* EC_KEY_generate_key() creates a ec private (public) key */
331int EC_KEY_generate_key(EC_KEY *);That NID_secp256k1 constant on line 51 is one of the most consequential choices in Bitcoin's history, and it's a single argument to someone else's function. OpenSSL already shipped the curve, the signing code and the key encoding. Satoshi's contribution was the choice, plus the error handling, plus the decision that a private key would live in a secure_allocator vector, which overwrites the memory with zeros when it's freed. When a user hit an error in this exact constructor in May 2010, Satoshi pasted these lines on BitcoinTalk and said "It's a call to OpenSSL that I assumed would never fail".
Addresses work the same way. The famous "hash the public key with SHA-256, then with RIPEMD-160" recipe is eight lines of Satoshi glue around two OpenSSL one-shot functions:
392inline uint160 Hash160(const vector<unsigned char>& vch)
393{
394 uint256 hash1;
395 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
396 uint160 hash2;
397 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
398 return hash2;
399}crypto/sha/sha.h:145
145unsigned char *SHA256(const unsigned char *d, size_t n,unsigned char *md);
crypto/ripemd/ripemd.h:97
97unsigned char *RIPEMD160(const unsigned char *d, size_t n,
98 unsigned char *md);The difficulty encoding is my favorite example, because it shows how a library can shape a protocol. Every Bitcoin block header carries a 32-bit field called nBits, the compact form of the mining target. Ever wondered why it's such an odd format, one byte of size followed by three bytes of number? Look at what SetCompact() does: it builds a byte array in OpenSSL's MPI format (four bytes of length, then big-endian digits) and hands it to BN_mpi2bn().
257 CBigNum& SetCompact(unsigned int nCompact)
258 {
259 unsigned int nSize = nCompact >> 24;
260 std::vector<unsigned char> vch(4 + nSize);
261 vch[3] = nSize;
262 if (nSize >= 1) vch[4] = (nCompact >> 16) & 0xff;
263 if (nSize >= 2) vch[5] = (nCompact >> 8) & 0xff;
264 if (nSize >= 3) vch[6] = (nCompact >> 0) & 0xff;
265 BN_mpi2bn(&vch[0], vch.size(), this);
266 return *this;
267 }91BIGNUM *BN_mpi2bn(const unsigned char *d, int n, BIGNUM *a)
92 {
93 long len;
94 int neg=0;
95
96 if (n < 4)
97 {
98 BNerr(BN_F_BN_MPI2BN,BN_R_INVALID_LENGTH);
99 return(NULL);
100 }
101 len=((long)d[0]<<24)|((long)d[1]<<16)|((int)d[2]<<8)|(int)d[3];
102 if ((len+4) != n)
103 {
104 BNerr(BN_F_BN_MPI2BN,BN_R_ENCODING_ERROR);
105 return(NULL);
106 }
⋮
117 d+=4;
118 if ((*d) & 0x80)
119 neg=1;In other words, the compact target format that every miner on Earth still produces today is a squeezed-down version of how OpenSSL 0.9.8 serialized big numbers. OpenSSL even uses the top bit of the first digit as a sign bit (bn_mpi.c line 118), which is why the compact format inherited a sign bit that a mining target never needs. That's not discovery or invention. That's a fossil.
Satoshi didn't love OpenSSL, by the way. In an August 2009 e-mail to Martti Malmi, Satoshi wrote that "it's a pain that the dependencies are so big and hard to build" and added: "OpenSSL is the harder one to build." Anyone who's tried to compile OpenSSL on Windows with MinGW will nod here. The v0.1 readme even includes step-by-step patches to build a stripped-down OpenSSL with RSA, AES, DES and friends removed, because, in Satoshi's words, "Bitcoin does not use any encryption."
Berkeley DB, Boost and the Boring Parts
The wallet and the block index lived in Berkeley DB, Oracle's embedded transactional database. When a curious user asked about data safety in December 2009, Satoshi answered plainly: "It uses a transactional database called Berkeley DB."
How did Satoshi learn to use it? I can't prove anything about anybody's learning process, but I can show you what the official example looked like. Berkeley DB 4.7.25 shipped with examples_cxx/EnvExample.cpp, and Satoshi's environment setup in db.cpp follows the same shape, with the same five flags in the same order, plus a few production extras:
64 dbenv.set_lg_dir(strLogDir.c_str());
65 dbenv.set_lg_max(10000000);
66 dbenv.set_lk_max_locks(10000);
67 dbenv.set_lk_max_objects(10000);
68 dbenv.set_errfile(fopen("db.log", "a")); /// debug
69 ///dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1); /// causes corruption
70 ret = dbenv.open(strAppDir.c_str(),
71 DB_CREATE |
72 DB_INIT_LOCK |
73 DB_INIT_LOG |
74 DB_INIT_MPOOL |
75 DB_INIT_TXN |
76 DB_THREAD |
77 DB_PRIVATE |
78 DB_RECOVER,
79 0);85 DbEnv *dbenv = new DbEnv(0);
86 dbenv->set_error_stream(&err_stream);
87 dbenv->set_errpfx(progname);
88
89 //
90 // We want to specify the shared memory buffer pool cachesize,
91 // but everything else is the default.
92 //
93 dbenv->set_cachesize(0, 64 * 1024, 0);
94
95 // Databases are in a subdirectory.
96 (void)dbenv->set_data_dir(data_dir);
97
98 // Open the environment with full transactional support.
99 dbenv->open(home,
100 DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN, 0);This is normal. You start from the vendor's example, then you add what your application needs: DB_THREAD because Bitcoin ran several threads, DB_RECOVER so the database could repair itself after a crash, DB_PRIVATE so no other process could touch the environment, and bigger lock tables. Satoshi also left a revealing comment on line 69, next to a disabled log setting: "causes corruption". You only write that after it bit you.
Boost was even more mundane. The v0.1 headers.h pulls in boost/foreach.hpp, lexical_cast, tuple and array, and the code is sprinkled with foreach loops. The one place where Boost could have done something important, the network serialization, is the place Satoshi deliberately didn't use it. In April 2009, Satoshi told Mike Hearn:
"I looked at Google protocol buffers when they were released last year, but I had already written everything by then. What I did was something similar to Boost Serialisation. For this application, where I was parsing messages from strangers who might have extreme incentive to hack the protocol, it was necessary to make it as basic as possible so I could crawl over every line of code to convince myself it was airtight."
That's the 840-line serialize.h, written by hand, on purpose. Remember that quote, because it's the best one-sentence explanation of why the core of Bitcoin v0.1 contains no borrowed code at all.
The Face of Bitcoin v0.1 Was Drawn in wxFormBuilder
The first Bitcoin client had a proper Windows GUI with a toolbar, an address book and a "Generate Coins" menu option. It was built with wxWidgets, and Satoshi liked the choice: "wxWidgets really pays off for cross platform." The window layouts were designed visually in wxFormBuilder, which saved them in uiproject.fbp (11,825 lines of XML that I excluded from the counts) and generated the C++ in uibase.cpp. Satoshi then wrote the behavior by hand in ui.cpp. Here's the same menu item on both sides of that line:
32 wxMenuItem* m_menuOptionsGenerateBitcoins;
33 m_menuOptionsGenerateBitcoins = new wxMenuItem(m_menuOptions, wxID_OPTIONSGENERATEBITCOINS, wxString(wxT("&Generate Coins")) , wxEmptyString, wxITEM_CHECK);
34 m_menuOptions->Append(m_menuOptionsGenerateBitcoins);821void CMainFrame::OnMenuOptionsGenerate(wxCommandEvent& event)
822{
823 fGenerateBitcoins = event.IsChecked();
824 nTransactionsUpdated++;
825 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
826
827 if (fGenerateBitcoins)
828 if (_beginthread(ThreadBitcoinMiner, 0, NULL) == -1)
829 printf("Error: _beginthread(ThreadBitcoinMiner) failed\n");The generated side is the bigger chunk of non-Satoshi code in v0.1: 1,801 lines, more than three times the Crypto++ files. Nobody would call that copying, though. It's the 2008 equivalent of designing a form in a visual editor, and it's the reason "Satoshi wrote 84%" is a fairer statement than "Satoshi wrote 96%".
The Parts Nobody Handed to Satoshi
Now for the fun part. Some of the most recognizable things in Bitcoin have no upstream at all. I looked for them in every library above and found nothing to compare against, because they're Satoshi's.
Base58. The address alphabet without 0, O, I and l comes with its own justification, right at the top of base58.h, and I don't know of any earlier library that used this exact alphabet for this purpose:
6//
7// Why base-58 instead of standard base-64 encoding?
8// - Don't want 0OIl characters that look the same in some fonts and
9// could be used to create visually identical looking account numbers.
10// - A string with non-alphanumeric characters is not as easily accepted as an account number.
11// - E-mail usually won't line-break if there's no punctuation to break at.
12// - Doubleclicking selects the whole number as one word if it's all alphanumeric.
13//
14
15
16static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";"E-mail usually won't line-break if there's no punctuation to break at." That is a person who has pasted long strings into e-mails and been annoyed. The actual encoding math, of course, runs on OpenSSL bignums.
The IRC bootstrap. How does a brand new node find other nodes when there's no server? In v0.1, it logs into chat.freenode.net, joins #bitcoin and uses its own IP address and port, encoded in base58, as its nickname. Everybody else in the channel does the same, so the user list doubles as a peer list. It's a hack, and a clever one. It's also the reason Alex Waltz could reconstruct who was online in the first days of the network from Hal Finney's debug log, as he explained to me in S17 E31.
144void ThreadIRCSeed(void* parg)
145{
146 loop
147 {
148 struct hostent* phostent = gethostbyname("chat.freenode.net");
149 CAddress addrConnect(*(u_long*)phostent->h_addr_list[0], htons(6667));
⋮
164 string strMyName = EncodeAddress(addrLocalHost);
165
166 if (!addrLocalHost.IsRoutable())
167 strMyName = strprintf("x%u", GetRand(1000000000));
168
169 Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
170 Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
171
172 if (!RecvUntil(hSocket, " 004 "))
173 {
174 closesocket(hSocket);
175 return;
176 }
177 Sleep(500);
178
179 Send(hSocket, "JOIN #bitcoin\r");
180 Send(hSocket, "WHO #bitcoin\r");Script. Bitcoin's transaction language is a small stack machine, and if you've ever touched Forth, the stack operations will feel familiar: DUP, DROP, SWAP, OVER, ROT, NIP, TUCK, PICK, ROLL, 2DUP, 2SWAP, ?DUP and the return stack words >R and R> all exist in standard Forth, and Satoshi's list maps onto them almost one to one (with OP_IFDUP for ?DUP and an "alt stack" for the return stack):
57 // stack ops
58 OP_TOALTSTACK,
59 OP_FROMALTSTACK,
60 OP_2DROP,
61 OP_2DUP,
62 OP_3DUP,
63 OP_2OVER,
64 OP_2ROT,
65 OP_2SWAP,
66 OP_IFDUP,
67 OP_DEPTH,
68 OP_DROP,
69 OP_DUP,
70 OP_NIP,
71 OP_OVER,
72 OP_PICK,
73 OP_ROLL,
74 OP_ROT,
75 OP_SWAP,
76 OP_TUCK,I'd love to tell you Satoshi was a Forth programmer, but there's no evidence for it: I searched all 773 writings in our Satoshi archive and the word "Forth" never appears. The resemblance is real; the lineage is unproven. What Satoshi did explain is why Script exists in the first place:
"The nature of Bitcoin is such that once version 0.1 was released, the core design was set in stone for the rest of its lifetime." [...] "The script is actually a predicate. It's just an equation that evaluates to true or false. Predicate is a long and unfamiliar word so I called it script."
Add to these the things that make Bitcoin Bitcoin: the UTXO model in main.h, the longest-chain logic and reorganizations in main.cpp, the inventory-based gossip protocol in net.cpp, the difficulty retargeting, the coinbase, the halving. None of it came from a library. It all fits in about 9,000 lines.
Hashcash, Then Something Better
When Satoshi announced the whitepaper on Perry Metzger's cryptography mailing list, one of the bullet points read: "New coins are made from Hashcash style proof-of-work." Hashcash is Adam Back's 1997 anti-spam system, and it's reference [6] in the whitepaper. (No, that doesn't make Adam Satoshi. I've written about that already.)
Here's where the November 2008 preview becomes priceless. Satoshi sent a handful of cryptographers, including Hal Finney and Ray Dillinger, an archive with four files: main.cpp, main.h, node.cpp and node.h. In a public reply to James A. Donald on November 17, 2008, Satoshi wrote: "I believe I've worked through all those little details over the last year and a half while coding it, and there were a lot of them. The functional details are not covered in the paper, but the sourcecode is coming soon. I sent you the main files." Ray Dillinger posted those files on BitcoinTalk in December 2013. Even then, main.cpp already included sha.h, so the Crypto++ hash was there before the first block was mined.
In that preview, the proof-of-work check counts leading zero bits, exactly like Hashcash does. Put Adam Back's Hashcash 1.22 next to it:
1172 if (nBits < MINPROOFOFWORK)
1173 return error("CheckBlock() : nBits below minimum");
1174 if (GetHash() > (~uint256(0) >> nBits))
1175 return error("CheckBlock() : hash doesn't match nBits");
main.h:37
37///static const unsigned int MINPROOFOFWORK = 40; /// need to decide the right difficulty to start with
38static const unsigned int MINPROOFOFWORK = 20; /// ridiculously easy for testing384 memset( target_digest, 0, SHA1_DIGEST_BYTES );
385
386 SHA1_Init( &ctx );
387 SHA1_Update( &ctx, token, strlen( token ) );
388 SHA1_Final( &ctx, token_digest );
389
390 for ( i = 0;
391 i < SHA1_DIGEST_BYTES && token_digest[ i ] == target_digest[ i ];
392 i++ ) {
393 }
394
395 last = i;
396 preimage_bits = 8 * i;
397
398#define bit( n, c ) (((c) >> (7 - (n))) & 1)
399
400 for ( i = 0; i < 8; i++ )
401 {
402 if ( bit( i, token_digest[ last ] ) ==
403 bit( i, target_digest[ last ] ) ) {
404 preimage_bits++;
405 } else {
406 break;
407 }
408 }
409 return preimage_bits;Same idea, very different code: Hashcash 1.22 (2006) hashes a text stamp with SHA-1 and counts its leading zero bits, byte by byte and then bit by bit, while Satoshi shifts a 256-bit number of all ones right by nBits and compares. In November 2008, Bitcoin's difficulty was a whole number of zero bits, and the retargeting code could only move it up or down by one bit, which doubles or halves the work in one step. A comment in the preview's main.h says the minimum of 20 bits is "ridiculously easy for testing".
By January 2009, all of that had changed. Look at the same functions two months apart:
main.cpp:652
652int64 GetBlockValue(int64 nFees)
653{
654 int64 nSubsidy = 10000 * CENT;
655 for (int i = 100000; i <= nBestHeight; i += 100000)
656 nSubsidy /= 2;
657 return nSubsidy + nFees;
658}
⋮
660unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
661{
662 const unsigned int nTargetTimespan = 30 * 24 * 60 * 60;
663 const unsigned int nTargetSpacing = 15 * 60;
664 const unsigned int nIntervals = nTargetTimespan / nTargetSpacing;
main.cpp:1172
1172 if (nBits < MINPROOFOFWORK)
1173 return error("CheckBlock() : nBits below minimum");
1174 if (GetHash() > (~uint256(0) >> nBits))
1175 return error("CheckBlock() : hash doesn't match nBits");main.cpp:675
675int64 CBlock::GetBlockValue(int64 nFees) const
676{
677 int64 nSubsidy = 50 * COIN;
678
679 // Subsidy is cut in half every 4 years
680 nSubsidy >>= (nBestHeight / 210000);
681
682 return nSubsidy + nFees;
683}
⋮
685unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
686{
687 const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
688 const unsigned int nTargetSpacing = 10 * 60;
689 const unsigned int nInterval = nTargetTimespan / nTargetSpacing;
main.cpp:1179
1179 // Check proof of work matches claimed amount
1180 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
1181 return error("CheckBlock() : nBits below minimum work");
1182 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
1183 return error("CheckBlock() : hash doesn't match nBits");In the preview, a block paid 100 coins, the reward halved every 100,000 blocks, blocks were targeted at 15 minutes and difficulty was reviewed over 30 days. If you do the math, that schedule would have topped out just under 20 million coins. In v0.1 it's 50 coins, a halving every 210,000 blocks, 10-minute blocks and a two-week window, and the target became a full 256-bit number in the compact nBits format we saw earlier, so difficulty could move smoothly instead of in jumps of 2x. Even the size of a coin changed: the preview defines COIN as 1,000,000 base units, v0.1 as 100,000,000. That's the eight decimal places you use today.
I'll be honest, this comparison changed my answer to the title question more than any line count did.
Was Bitcoin Invented or Discovered?
The "discovered" camp has a good argument. SHA-256 and ECDSA are mathematics, and mathematics doesn't care who writes it down. Satoshi's whitepaper cites eight references, and most of them are the building blocks: Wei Dai's b-money; Massias, Avila and Quisquater on timestamping with minimal trust; three papers by Stuart Haber and W. Scott Stornetta (one of them with Dave Bayer) on hash-linked timestamping; Adam Back's Hashcash; Ralph Merkle's 1980 paper behind Merkle trees; and William Feller's probability textbook. In 2010 Satoshi was even more direct about the lineage: "Bitcoin is an implementation of Wei Dai's b-money proposal [...] on Cypherpunks [...] in 1998 and Nick Szabo's Bitgold proposal". Interestingly, Nick Szabo's bit gold isn't cited in the paper, and neither is Hal Finney's RPOW, even though both are obvious ancestors. If you want the full family tree, Aaron van Wirdum walked me through it in S15 E15.
So the pieces were there. The cryptography came from OpenSSL, the fastest hash from Wei Dai, the database from Oracle, the windows from wxWidgets, the proof-of-work from Adam Back, the timestamping chain from Haber and Stornetta. If Bitcoin were only the sum of its parts, "discovered" would be a fair word.
But here's what the code tells me, and why I land on the other side. Discovered things don't change their constants in two months. Gravity didn't go from 100 coins to 50. The speed of light didn't get a new halving interval between November 2008 and January 2009. The block reward, the 10-minute target, the two-week window, the eight decimal places, the decision to fold Hashcash's leading zeros into a 256-bit target: those are choices, made by a person, revised by a person, and then frozen on purpose. Satoshi said as much:
"I actually did this kind of backwards. I had to write all the code before I could convince myself that I could solve every problem, then I wrote the paper."
Satoshi on the cryptography mailing list, November 9, 2008 (original)
"Since 2007. At some point I became convinced there was a way to do this without any trust required at all and couldn't resist to keep thinking about it. Much more of the work was designing than coding."
Put those two quotes next to the numbers and the picture is consistent. The design work is in the 9,000 hand-written lines, not in the 537 borrowed ones. Satoshi wrote the code first because the hard part wasn't the cryptography (OpenSSL had that covered) but the incentives, the edge cases and the network behavior, the things you can't hand-wave in a nine-page PDF. In a November 14, 2008 reply to Hal Finney, Satoshi put it this way: "It's very attractive to the libertarian viewpoint if we can explain it properly. I'm better with code than with words though." The code agrees.
My favorite way to think about it is music. The Beatles didn't invent the guitar, the chord progression, the recording studio or the twelve-bar blues. Nobody would say they "discovered" A Day in the Life, though. Bitcoin is the same kind of thing: an arrangement of existing instruments into something that hadn't existed before, and that nobody else had managed to play in the decade of attempts that came before it.
The Verdict
Here's my scorecard, with the receipts above:
- Copied: one SHA-256 implementation from Wei Dai's Crypto++ 5.5.2, credited and public domain, 537 lines or 3.7% of the C++, used only by the miner.
- Generated: 1,801 lines (12.4%) of GUI code written by wxFormBuilder from Satoshi's visual designs.
- Written by Satoshi: 12,209 lines (83.9%), including the entire 9,263-line core: consensus, Script, the P2P network, serialization, the wallet database layer, base58, the IRC bootstrap.
- Linked, not copied: OpenSSL (ECDSA on secp256k1, SHA-256, RIPEMD-160, bignums), Berkeley DB, Boost and wxWidgets, as listed in Satoshi's own readme.
- Borrowed ideas, cited: b-money, Hashcash, Haber and Stornetta's timestamping, Merkle trees. Borrowed ideas, not cited in the paper: bit gold and RPOW.
Was Bitcoin invented or discovered? The ingredients were discovered, many of them by people Satoshi e-mailed personally. The recipe was invented, and you can watch it being invented in the two months between the November 2008 preview and the January 2009 release. Then it was locked, which is the one decision that made all the others matter.
Next time somebody tells you Satoshi "just glued libraries together", ask them which library had the halving in it. And if you have Bitcoin code from before 2009 that I haven't compared yet, send it my way. I'll diff it.
Part 2: the ideas behind the code, source by source, with the primary texts side by side: Was Satoshi a Cypherpunk? Every Idea Bitcoin Borrowed.
Methodology and sources
- Bitcoin v0.1.0: bitcoin-0.1.0.tgz from the Satoshi Nakamoto Institute, MD5 dca1095f053a0c2dc90b19c92bd1ec00, SHA-1 35f83eaa334e0e447ceea77a7cc955a4ccdd1a1d, both matching the published values.
- November 2008 preview: bitcoin-nov08 from the same page (four files, 2,879 lines of code), first posted by Ray Dillinger on BitcoinTalk. The .rar original matches the Institute's MD5 (1de1b45c425c1cebb2b3280baffe7f25).
- Upstream code: Crypto++ 5.5.2 (tag CRYPTOPP_5_5_2), OpenSSL 0.9.8h (the version named in Satoshi's readme), Oracle's Berkeley DB 4.7.25 tarball (May 2008) and Hashcash 1.22 via the Internet Archive. Boost and wxWidgets were not measured.
- Counting: cloc 2.02, code lines only, for the 26 .cpp and .h files. Excluded: uiproject.fbp (11,825 lines of XML), makefiles, readme, license and resource files. Library sizes for scale: OpenSSL 0.9.8h crypto/ and ssl/ 205,652 lines, Berkeley DB 4.7.25 C and C++ sources 141,502 lines (docs, tests, examples and other language bindings excluded).
- Snippets: copied programmatically from the files above, with original line numbers; tabs shown as four spaces (eight for OpenSSL, Berkeley DB and Hashcash, which assume eight-column tabs), trailing spaces trimmed. A vertical ellipsis marks skipped lines.
- Quotes: every Satoshi quote links to our Satoshi archive and was checked word for word against the original mailing list, forum or e-mail source. The whitepaper references are from bitcoin.pdf.
Related
S1 E3 Remastered: Zack Voell on Bitcoin & Politics
Zack Voell: the host of The Coin Pod back in 2019, who later worked at Messari, CoinDesk, Compass Mining and Blockstream, and…
Remembering Donald McIntyre: S1 E1 Remaster, on Bitcoin, Tim May, Nick Szabo and the History of Money
Donald McIntyre: Ethereum Classic advocate, author of the [Etherplan](https://etherplan.com/) blog, collaborator of [Nick…
S15 E15: Where Did Bitcoin Come From? Aaron van Wirdum on The Genesis Book
Where did Bitcoin come from? In S15 E15, Aaron van Wirdum walks through The Genesis Book: e-gold, Hayek, cypherpunks, Bit Gold…


Comments
Questions or corrections? Email me, or say it on Nostr or X. I read all three.
Email meNostrX