This semester, I’ve bot taking a course on Bitcoin and Cryptocurrencies, suggested by Princeton’s Center for Information Technology Policy, and co-taught by Arvind Narayanan and Joseph Bonneau (with help from Ed Felten and Andrew Miller).
The ES6 source is available on GitHub, you can also download the interpreter spil the bitcoin-script package on npm.
Ter this postbode, I’ll explain some of the core principles and functionality behind Script before introducing the Script Playground and a few examples.
What is Script?
(If you have a good treat on Script, feel free to skip ahead.)
Script is a elementary stack-based programming language used by Bitcoin to validate transactions.
Script programs are processed left-to-right, with each operation modifying a global stack. On termination, the script is either considered valid (indicated by the presence of a 1 on top of the stack) or invalid (anything else).
Spil an example, this script shoves a 0 onto the stack, increments it, and terminates. Spil 0 + 1 = 1 is on top of the stack, this script will run successfully:
Ter the Setting of Bitcoin
Script is used to verify that the spender of some Bitcoins actually wields them. Ter other words, scripts validate transactions.
Each Bitcoin transaction requires two scripts: ScriptPubKey and ScriptSig. The former is included spil part of the transaction when it is broadcast to the network and typically encodes the destination address D of the Bitcoins involved. The latter is provided when those Bitcoins are spent te the future by the possessor of address D and typically provides some evidence that the holder actually wields that address (i.e., by signing a message with its private key).
To validate the spending of Bitcoins, miners concatenate the ScriptSig and ScriptPubKey. If the concatenated program is valid, the transaction is valid, and vice-versa. For this reason, thesis scripts are sometimes referred to spil the ",unlocking", and ",locking", scripts, respectively, spil the ScriptPubKey is provided to lock some Bitcoins to an address, and the ScriptSig, to unlock them te the future.
Elementary By Vormgeving
Script is purposefully not Turing-complete. It contains no loops (it’s only form of control flow is through if-else statements) and the instruction set is limited to the nude necessities: stack manipulation, arithmetic, cryptography, and little else.
This plainness is a feature, not a flaw.
Spil scripts are used to validate transactions, miners across the network have to execute them ter bulk to compose and validate blocks. If the Script language permitted for intense computation, miners would be disincentivized from validating transactions because of the costs of computing.
At the very least, thesis miners would be incurring an unnecessary cost, spil Script’s plainness is sufficient for covering most of what wij want to do ter transaction validation. This cost would make mining less attractive, and spil the attractivity of mining is crucial to maintaining a high hash rate across the network (and thus securing the network), this simpleness is a good thing.
Te practice, Bitcoin scripts typically take one of a handful of forms, e.g.:
- P2PKH: the ScriptSig requires a signature and the public key from which it wasgoed generated, while the ScriptPubKey verifies that the public key matches the desired address and the signature is valid.
- Multisig: similar to the above, but requires M-of-N signatures to be valid.
Ter fact, miners will reject transactions that veer from the list of standard Script formats. Ter Bitcoin vaktaal, thesis are referred to spil ",non-standard transactions",.
Why Build a Playground?
Script is an interesting opzicht of Bitcoin.
Very first, the language is intentionally elementary, which makes you wonder just how far you can thrust it.
2nd, Script is a good mechanism for reinforcing the principles behind Bitcoin. For example, Script’s limited instruction set reinforces an understanding of miner incentives, while its multi-signature support demonstrates interesting use-cases for Bitcoin.
For thesis reasons, I desired to make it possible to play with Script te the most accessible of settings: the browser. The finished product is available here, with the source free to view on GitHub. You can also download it spil the bitcoin-script package from npm.
My implementation of Script covers all of the enabled opcodes listed on the Bitcoin Wiki, exclusief from the reserved words, altstack directives, pseudo-words, and OP_CODESEPARATOR . Te particular, it’s worth noting that my implementation permits for the use of disabled directives, like OP_MUL , by passing te true spil the 2nd argument to any of the exported functions. (The Script Playground has this behavior enabled by default.)
However, it differs from Bitcoin’s implementation ter a few ways:
- It shoves any hex gegevens to the stack. So, it disregards the OP_PUSHDATA instructions and instead shoves any hex-formatted gegevens to the stack (e.g., 0x05 or fde5a ). Further, this hex gegevens can be of arbitrary length.
- Unlike te the official implementation, OP_CHECKMULTISIG does not speelgoedpop an reserve, arbitrary value off the stack (spil this is considered a bug and would only serve to confuse fresh users).
- It generates and validates signatures using a nonce, rather than hashing transaction inputs and outputs.
Each of thesis switches wasgoed made so spil to make this implementation lighter to use and understand.
Ter addition to the Script implementation itself, the Playground also includes:
- A utility for generating (signature, public key) pairs, which you can druppel into your scripts to test out the signature verification directives.
- A permalink button for generating shareable URLs with your scripts embedded, creating a GitHub gist-like practice.
The live editor itself is based on my friend Joel Burget’s react-live-editor, which is in-turn based on CodeMirror for real-time updates and editing.
An Example: Testing for Primality
Spil Script’s division and remainder operators are disabled ter Bitcoin, the best wij can do (whilst remaining ter the field of enabled operators) is generate all the set of prime numbers ter [100, 999] and evaluate whether the ScriptSig is ter that set. Since the ScriptPubKey is public, wij won’t want to include the actual primes, instead, wij’ll include the hash of each prime and evaluate the hash of the ScriptSig for equality.
The final evaluation function looks like this:
It’s joy to test the thresholds of Script’s expressiveness.
Unluckily, this example isn’t very useful. Ter the real world, the purpose of such a script would be to incentivize individuals to find large primes: ter terugwedstrijd for their effort, they could unlock the script and voorkoop some Bitcoin (this is ter the area of a useful proof-of-work system).
But by computing all the primes te advance, wij defeat the purpose, spil all the work is being done twice: once by the individual that issues the challenge, and once by the individual that solves it.
What guidelines would it take, then, to write a ScriptPubKey that doesn’t need to precompute primes?
A test for divisability would be sufficient and, indeed, this is possible with the OP_MOD directive. OP_MOD is disabled ter the Bitcoin Script spec, but can be enabled ter my implementation by switching a flag.
Here’s the revised code which is much more useful, spil the cargo of producing a prime number is placed on the unlocker:
I’d encourage you to play around with your own scripts te the playground and see what you can come up with. Alternatively, you can download the bitcoin-script package from npm.
Thanks to Shubhro Saha for his terugkoppeling on a draft of this postbode.
If you clicked the button above, then you are presently mining bitcoin, the math-based digital currency that recently topped $1,000 on exchanges. Congratulations. (It won&rsquo,t do anything bad to your pc, wij promise.)
Fresh bitcoins are created toughly every Ten minutes te batches of 25 coins, with each coin worth around $730 at current rates. Your pc&mdash,ter collaboration with those of everyone else reading this postbode who clicked the button above&mdash,is racing thousands of others to unlock and voorwaarde the next batch.
For spil long spil that toonbank above keeps climbing, your rekentuig will keep running a bitcoin mining script and attempting to get a chunk of the act. (But don&rsquo,t worry: It&rsquo,s designed to shut off after Ten minutes if you are on a phone or a tablet, so your battery doesn&rsquo,t drain).
So what is that script doing, exactly?
Let&rsquo,s embark with what it&rsquo,s not doing. Your rekentuig is not blasting through the cavernous insides of the internet ter search of digital ore that can be fashioned into bitcoin bullion. There is no ore, and bitcoin mining doesn&rsquo,t involve extracting or smelting anything. It&rsquo,s called mining only because the people who do it are the ones who get fresh bitcoins, and because bitcoin is a finite resource liberated te puny amounts overheen time, like gold, or anything else that is mined. (The size of each batch of coins drops by half harshly every four years, and around 2140, it will be cut to zero, capping the total number of bitcoins ter circulation at 21 million.) But the analogy finishes there.
What bitcoin miners actually do could be better described spil competitive bookkeeping. Miners build and maintain a gigantic public ledger containing a record of every bitcoin transaction ter history. Every time somebody wants to send bitcoins to somebody else, the transfer has to be validated by miners: They check the ledger to make sure the sender isn&rsquo,t transferring money she doesn&rsquo,t have. If the transfer checks out, miners add it to the ledger. Eventually, to protect that ledger from getting hacked, miners seal it behind layers and layers of computational work&mdash,too much for a would-be fraudster to possibly accomplish.
And for this service, they are rewarded te bitcoins.
Or rather, some miners are rewarded. Miners are all challenging with each other to be very first to approve a fresh batch of transactions and finish the computational work required to seal those transactions ter the ledger. With each fresh batch, winner takes all.
It&rsquo,s the computational work that indeed takes time, and that&rsquo,s mostly what your rekentuig is doing right now. It&rsquo,s attempting to solve a zuigeling of cryptographic problem that involves guessing and checking billions of times until it finds an response.
If this all seems pretty heady, that&rsquo,s because mining is an elaborate solution to a rough problem that plagues every currency&mdash,dual spending.
Dual spending and a public ledger
Spil the name implies, dual spending is when somebody spends money more than once. It&rsquo,s a risk with any currency. Traditional currencies avoid it through a combination of hard-to-mimic physical metselspecie and trusted third parties&mdash,banks, credit-card providers, and services like PayPal&mdash,that process transactions and update account balances accordingly.
But bitcoin is entirely digital, and it has no third parties. The idea of an overseeing figure runs downright toonbank to its ethos. So if you tell mij you have 25 bitcoins, how do I know you&rsquo,re telling the truth? The solution is that public ledger with records of all transactions, known spil the block chain. (Wij&rsquo,ll get to why it&rsquo,s called that shortly.) If all of your bitcoins can be traced back to when they were created, you can&rsquo,t get away with lounging about how many you have.
So every time somebody transfers bitcoins to somebody else, miners raadpleging the ledger to make sure the sender isn&rsquo,t double-spending. If she indeed has the right to send that money, the transfer gets approved and entered into the ledger. Elementary, right?
Well, not truly. Using a public ledger comes with some problems. The very first is privacy. How can you make every bitcoin exchange entirely see-through while keeping all bitcoin users fully anonymous? The 2nd is security. If the ledger is totally public, how do you prevent people from fudging it for their own build up?
There is no such thing spil a bitcoin account
Bitcoin&rsquo,s ledger deals with the privacy punt through a bit of accounting trickery. The ledger only keeps track of bitcoin transfers, not account balances. Ter a very real sense, there is no such thing spil a bitcoin account. And that keeps users anonymous.
Here&rsquo,s how it works: Say Alice wants to transfer one bitcoin to Bob. Very first Bob sets up a digital address for Alice to send the money to, along with a key permitting him to access the money once it&rsquo,s there. It works sort-of like an email account and password, except that Bob sets up a fresh address and key for every incoming transaction (he doesn&rsquo,t have to do this, but it&rsquo,s very recommended).
When Alice clicks a button to send the money to Bob, the transfer is encoded te a chunk of text that includes the amount and Bob&rsquo,s address. Here&rsquo,s what that text actually look like:
And here&rsquo,s a more digestible diagram of it:
That transaction record is sent to every bitcoin miner&mdash,i.e., every rekentuig on the internet that is running mining software&mdash,and if it&rsquo,s legit, it gets added to the ledger. Let&rsquo,s assume it goes through.
Now, say Bob wants to pay Carol one bitcoin. Carol of course sets up an address and a key. And then Bob essentially takes the bitcoin Alice talent him and uses his address and key from that transfer to sign the bitcoin overheen to Carol:
This transaction gets sent out to all of the miners, and they will check (using the reference number from Alice&rsquo,s transfer to Bob) to make sure that Bob hasn&rsquo,t already transferred that bitcoin to somebody else. No dual spending. After validating the transfer, each miner will then send a message to all of the other miners, providing hier bliss.
If Bob&rsquo,s transfer to Carol passes muster, then it, too, will be added to the ledger.
That&rsquo,s all transactions are&mdash,people signing bitcoins (or fractions of bitcoins) overheen to each other. The ledger tracks the coins, but it does not track people, at least not explicitly. Assuming Bob creates a fresh address and key for each transaction, the ledger won&rsquo,t be able to expose who he is, or which addresses are his, or how many bitcoins he has ter all. It&rsquo,s just a record of money moving inbetween anonymous arms.
There is no master document
Now for the trickier problem: keeping the ledger secure.
The very first thing that bitcoin does to secure the ledger is decentralize it. There is no thick spreadsheet being stored on a server somewhere. There is no master document at all.
Instead, the ledger is cracked up into blocks: discrete transaction logs that contain Ten minutes worth of bitcoin activity apiece. Every block includes a reference to the block that came before it, and you can go after the linksaf backward from the most latest block to the very very first block, when bitcoin creator Satoshi Nakamoto conjured the very first bitcoins into existence.
This lineage of blocks is the block chain, and it constitutes bitcoin&rsquo,s public ledger. Every Ten minutes miners add a fresh block, growing the chain like an expanding pearl necklace.
Generally speaking, every bitcoin miner has a copy of the entire block chain on hier rekentuig. If she shuts hier rekentuig down and stops mining for a while, when she starts back up, hier machine will send a message to other miners requesting the blocks that were created te hier absence. No one person or pc has responsibility for thesis block chain updates, no miner has special status. The updates, like the authentication of fresh blocks, are provided by the network of bitcoin miners at large.
Proof of work
Dividing the ledger up into distributed blocks isn&rsquo,t enough on its own to protect the ledger from fraud. Bitcoin also relies on cryptography.
To add a fresh block to the chain, a miner has to finish what&rsquo,s called a cryptographic proof-of-work problem. Such problems are unlikely to solve without applying a ton of brute computing force, so if you have a solution ter arm, it&rsquo,s proof that you&rsquo,ve done a certain quantity of computational work. The computational problem is different for every block ter the chain, and it involves a particular zuigeling of algorithm called a hash function.
Like any function, a cryptographic hash function takes an input&mdash,a string of numbers and letters&mdash,and produces an output. But there are three things that set cryptographic hash functions exclusief:
1. The output is a predetermined length, regardless of the input.
The hash function that bitcoin relies on&mdash,called SHA-256, and developed by the US National Security Agency&mdash,always produces a string that is 64 characters long. For example:
You could run your name through that hash function, or the entire King James Bible. Ter either case, you&rsquo,ll get 64 characters out the other end. And, for a given input, you&rsquo,ll always get the same output.
Two. It&rsquo,s unlikely to make a cryptographic hash function work te switch roles.
If you have the output of a cryptographic hash function (called a hash for brief), there&rsquo,s no way of knowing what the input wasgoed. It&rsquo,s a one-way street. And that&rsquo,s what makes it cryptographic&mdash,you can use a hash function to scramble text te a way that&rsquo,s unlikely to unscramble.
Think of it like mixing paint. It&rsquo,s effortless to mix pink paint , blue paint , and grey paint . But it&rsquo,s hard to take the resulting purple and unmix it.
Three. Switching the input even a little bit switches the output dramatically
Paint mixing is a good way to think about the one-way nature of hash functions, but it doesn&rsquo,t capture their unpredictability. If you substitute light pink paint for regular pink paint te the example above, the result is still going to be pretty much the same purple , just a little lighter. But with hashes, a slight variation ter the input results ter a totally different output:
The proof-of-work problem that miners have to solve involves taking a hash of the contents of the block that they are working on&mdash,all of the transactions, some meta-data (like a timestamp), and the reference to the previous block&mdash,plus a random number called a nonce.
Their objective is to find a hash that has at least a certain number of leading zeroes. Something like this:
That constraint is what makes the problem more or less difficult. More leading zeroes means fewer possible solutions, and more time required to solve the problem. Every Two,016 blocks (toughly two weeks), that difficulty is reset. If it took miners less than Ten minutes on average to solve those Two,016 blocks, then the difficulty is automatically enhanced. If it took longer, then the difficulty is decreased.
Miners search for an acceptable hash by choosing a nonce, running the hash function, and checking. If the hash doesn&rsquo,t have the right number of leading zeroes, they switch the nonce, run the hash function, and check again.
Because of the one-way nature of hash functions, you can&rsquo,t work your way rearwards to find a nonce that fits. And because of a hash function&rsquo,s unpredictability, attempting different nonces never indeed gets you closer to the right one. It&rsquo,s all a process of elimination.
When a miner is ultimately fortunate enough to find a nonce that works, and wins the block, that nonce gets appended to the end of the block, along with the resulting hash.
The entire block then gets sent out to every other miner ter the network, each of whom can then run the hash function with the winner&rsquo,s nonce, and verify that it works. If the solution is accepted by a majority of miners, the winner gets the prize, and a fresh block is began, using the previous block&rsquo,s hash spil a reference.
So how does this protect bitcoin from fraud?
Let&rsquo,s say a hacker desired to switch a transaction that happened 60 minutes, or six blocks, ago&mdash,maybe to liquidate evidence that she had spent some bitcoins, so she could spend them again. Hier very first step would be to go ter and switch the record for that transaction. Then, because she had modified the block, she would have to solve a fresh proof-of-work problem&mdash,find a fresh nonce&mdash,and do all of that computational work, all overheen again. (Again, due to the unpredictable nature of hash functions, making the slightest switch to the original block means beginning the proof of work from scrape.) From there, she&rsquo,d have to commence building an alternative chain going forward, solving a fresh proof-of-work problem for each block until she caught up with the present.
But unless the hacker has more computing power at hier disposition than all other bitcoin miners combined, she could never catch up. She would always be at least six blocks behind, and hier alternative chain would obviously be a counterfeit.
The key is that if somebody modifies an accepted block&mdash,one that already has a proof-of-work solution pinned to the end of it&mdash,she can&rsquo,t reuse that same solution. She has to find a fresh one. And that&rsquo,s why proof of work is needed&mdash,to ensure that she can&rsquo,t just surreptitiously modify a block and thus omkoopbaar the ledger.
Mining is competitive, not cooperative
The code that makes bitcoin mining possible is totally open-source, and developed by volunteers. But the force that indeed makes the entire machine go is zuivere capitalistic competition. Every miner right now is racing to solve the same block at the same time, but only the winner will get the prize. Te a sense, everybody else wasgoed just searing electro-therapy. Yet their presence te the network is critical.
Mining&rsquo,s ultimate purpose is to prevent people from double-spending bitcoins. But it also solves another problem. It distributes fresh bitcoins te a relatively fair way&mdash,only those people who dedicate some effort to making bitcoin work get to love the coins spil they are created.
But because mining is a competitive enterprise, miners have come up with ways to build up an edge. One visible way is by pooling resources.
Your machine, right now, is actually working spil part of a bitcoin mining collective that shares out the computational fountain. Your laptop is not attempting to solve the block, at least not instantly. It is chipping away at a cryptographic problem, using the input at the top of the screen and combining it with a nonce, then taking the hash to attempt to find a solution. Solving that problem is a lotsbestemming lighter than solving the block itself, but doing so gets the pool closer to finding a winning nonce for the block. And the pool pays its members te bitcoins for every one of thesis lighter problems they solve.
What are the chances you&rsquo,ll actually win?
You&rsquo,ve no doubt bot waiting very patiently to find out one thing: is there a chance you&rsquo,ll actually win some bitcoins?
Nope. Not at all. If you did find a solution, then your bounty would go to Quartz, not you. This entire time you have bot mining for us!
But the chances that you find a solution and wij profit from the computing power you&rsquo,ve contributed are essentially zero. The Quartz bitcoin mining collective just isn&rsquo,t big enough. Wij&rsquo,re not attempting to take advantage of you. Wij just wished to make the strange and complicated world of bitcoin a little lighter to understand.
Correction (Dec. Legitimate, 2013): An earlier version of this article incorrectly stated that the long pink string of numbers and letters te the interactive at the top is the target output hash your rekentuig is attempting to find by running the mining script. Ter fact, it is one of the inputs that your laptop feeds into the hash function, not the output it is looking for.