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.

PayToPubKeyPurchase.png

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.

OpenSesamePrivateKey.png

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.

P2pkUnlockScript.png

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)
        {
            stack.Push(command);
            continue;
        }
        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
        }
        else
        {
            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.

P2pkhUnlockScript.png

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 »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s