The Medieval Hiroshima

The Castello di Monte San Giovanni Campano, just outside Naples, is the medieval Hiroshima. It was destroyed in February 1495 by a powerful new weapon. The world was changed forever.


A dispute over the succession to the throne of Naples, stoked by Pope Innocent VIII, led to the invasion of Italy by King Charles VIII of France. His army, at 25,000 men, was large but not unlike many other medieval armies – except for one thing. His siege train included forty heavy bronze cannon, powered by gunpowder.


Continue reading “The Medieval Hiroshima”

Happy Cosmonautics Day

On April 12, 1961, Yuri Gagarin became the first human to fly in space. At 06:07 UTC a Vostok rocket lifted off from the Baikonur Cosmodrome in what’s now Kazakhstan and lifted the 27-year-old Soviet air force pilot into orbit and into history.


The launch fixed the Soviet Union’s place at the head of the Space Race, when spaceflight marked the leading edge of superpower technology.

Spaceflight is no longer a superpower monopoly. Today, 58 years later, the Space Race is led by SpaceX, one of many private companies opening up spaceflight.

This morning (NZ time), an Israeli non-profit organisation came painfully close to landing the first privately-funded spacecraft on the moon. The probe was launched in February this year on a SpaceX Falcon 9 rocket. It got within a few hundred metres of the moon’s surface before its main engine failed and it was unable to slow its descent enough to land softly.

Three hours later, SpaceX launched the world’s most powerful rocket, the Falcon Heavy, carrying a Saudi Communications satellite. The satellite was nothing out of the ordinary, but the Falcon Heavy’s centre core and both side boosters, made near simultaneous landings and will be used again. Not only is this an extraordinary technical feat that puts traditional launch providers to shame but it will transform the economics of spaceflight.


After decades of stagnation, spaceflight is exciting again!

Is Poland a Real Country?

Poland has the things you’d expect of a real country: a flag, a currency, and its own phone number. But it lacks others, like borders that stay in the same place. The national anthem, entitled Poland Is Not Yet Lost, suggests something’s not quite right.

The national anthem was written in 1797, when Poland was no longer a real country, having just been divvied up by Catherine the Great of Russia and Frederick William II of Prussia, an arrangement that would be echoed in 1939 with the Nazi-Soviet Pact.

Continue reading “Is Poland a Real Country?”

Nobbling the Nobility

Democracy is not a natural state of affairs. Ever since the first Mesopotamian states formed, ten thousand years ago, kings and warlords have wielded power over the rest of the population. These rulers have maintained their positions with violent enthusiasm. Any who didn’t were quickly replaced.


Democracies have been rare and fleeting, popping up briefly in Ancient Greece and Rome and more recently in Europe and America.

There’s a sense today that democracy is failing. Tweets, news reports, and books point to well-funded lobbyists, foreign meddling, the corrosive effects of social media, and the inability of legislatures to decide on anything. There’s palpable worry about what’s being lost.

From our vantage point, it’s easy to think that democracy is the natural way of things. Lapses into dictatorship, as happened in Spain, Italy, and Germany in the 1930s, are the aberration. The truth is that our viewpoint, from a place of prosperity and safety, is unusual.

Instead of asking how democracy might be failing, let’s first ask: how did it ever succeed?

Continue reading “Nobbling the Nobility”

BTC#: Verifying Transactions

Series: BTC# – Learning to Program Bitcoin in C#

« Previous: Spending with Combined Scripts

There are several things that a node does to verify a transaction. Programming Bitcoin covers two of them in detail: making sure that coins aren’t being created out of nothing and checking that signature scripts correctly unlock the value they’re spending.


Fee Calculation

To ensure that coins aren’t being created out of nothing we check the value of the inputs compared to the value of the outputs on a transaction. The value of the inputs must be equal to or greater than the value of the outputs. Where they’re not equal, the difference is a fee collected by the miners as an incentive for their work.

Continue reading “BTC#: Verifying Transactions”

BTC#: Spending with Combined Scripts

Series: BTC# – Learning to Program Bitcoin in C#

« Previous: Stack Machine Operations

Next: Verifying Transactions »

The simplest Bitcoin transactions have outputs that pay to a public key. That is, they have a locking script (or “pubkey script”) on the output that consists of a public key supplied by the recipient of the funds and the OP_CHECKSIG command.


Let’s say that Alice pays funds to Bob’s public key. To spend the resulting output, or UTXO, Bob needs to provide the magic number that will unlock his funds.


For a payment to a public key, that magic number is his digital signature, derived from the same private key that he used to generate the public key he gave to Alice.

The OP_CHECKSIG command pops two elements off the stack. It assumes the first to be a public key and it assumes the next is the signature.

public static bool OP_CHECKSIG(Stack<byte[]> stack, BigInteger z) {
    var pkBytes = stack.Pop();
    var pk = PublicKey.Parse(pkBytes);
    var sigBytes = stack.Pop();
    var sig = Signature.Parse(sigBytes);
    stack.Push(EncodeNumber(pk.Verify(sig, z) ? 1 : 0));
    return true;

This operation also takes an argument z for the document hash, which needs to match the document hash that was used to generate the signature.

To validate a transaction, the signature script on the input is concatenated with the pubkey script on the output and then the combined script is executed. The unlocking script on the input contains the signature that the locking script from the previous output needs to validate.


The two scripts are combined by adding an addition operator to the script class. This takes the two sets of commands and concatenates them into a new script.

public static Script operator +(Script a, Script b)
    return new Script(a.Commands.Concat(b.Commands).ToList());

You may have noticed the EncodeNumber() call  in the OP_CHECKSIG method. This deals with some of details of how numbers are serialised onto the stack. The details are in the book and the code is in the repo.

To execute scripts rather than individual commands we need to add an Execute() method to the StackMachine and supply it with the script.

The StackMachine has a dictionary of functions keyed by op-code, so we can pull an op-code off the stack, pull its function reference from the dictionary, and execute it.

private static readonly Dictionary<byte, Func<Stack<byte[]>, bool>> Operations = new Dictionary<byte, Func<Stack<byte[]>, bool>>
    { 0, OP_0 },
    { 118, OP_DUP },
    { 169, OP_HASH160 },
    { 172, OP_CHECKSIG }

The Execute method takes each command of the stack in turn, determines whether it’s an element or an operation and then either pushes the element to the stack or executes the operation. (This is a simplified version to illustrate the basics. It doesn’t yet handle complexities like conditionals.)

public bool Execute(Script script, BigInteger docHash)
    var stack = new Stack<byte[]>();

    foreach (var command in script.Commands)
        if (command.Length > 1 || Operations[command[0]] == null)
        var operation = Operations[command[0]];
        if (operation == OP_IF || operation == OP_NOTIF)
            // handle command list for conditionals
        else if (operation == OP_TOALTSTACK || operation == OP_FROMALTSTACK)
            // handle alternate stack
        else if (operation == OP_CHECKSIG || operation == OP_CHECKSIGVERIFY ||
            operation == OP_CHECKMULTISIG || operation == OP_CHECKMULTISIGVERIFY)
            // handle document hash
            var result = operation(stack);
    return (stack.Count > 0 && DecodeNumber(stack.Peek()) > 0);

The result of the execution is a Boolean value indicating whether the script was successful. In the case of OP_CHECKSIG, if the signature was valid the method returns true and transaction validation is successful. Bob can spend his money.

Programming Bitcoin goes on to describe locking and unlocking Pay to Pubkey Hash (p2pkh) scripts, which are more secure than Pay to Public Key scripts and have a shorter locking script. Their workings are similar.


The book also touches on Pay to Script Hash scripts variations introduced with Segwit, which we’ll cover later.

« Previous: Stack Machine Operations

Next: Verifying Transactions »