Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Chapter-3 Mechanics of Bitcoin

 Bitcoin consensus mechanism gives us an append-only ledger, a data structure that we can only
write to. Once data is written to it, it’s there forever.
 A decentralized protocol establishes consensus about the value of that ledger, and miners use
the protocol and validate transactions.
 The protocol and miners together make sure that transactions are well formed, that the bitcoins
involved aren’t already spent, and that the ledger and network can function as a currency.
 Currency existed to motived the miners.

3.1 Bitcoin transactions

Bitcoin does not use the account model. The account model works on BALANCE. But bitcoin works on
transactions.

In the account model – if allice receives 25 coins in first transaction and then transfers 17 coins to Bob in
the second transaction, she would have 8 bitcoins left in her account.

The downside to this model – If anyone wants to determine whether a transaction is valid will have to
keep track of these account balances. (For example, if Alice tries to transfer 15 coins to David, To figure
out whether Alice really have the 15 coins she is trying to transfer – we need to track every transaction
affecting Alice.

We can have some data structures that track Alice’s balance after each transaction. But that’s going to
require a lot of extra housekeeping besides the ledger itself.

Bitcoin does not use account-based model. Instead Bitcoin uses a ledger that just keeps track of
transactions.
Transactions specify a number of inputs and a number of outputs.

 Inputs – coins being consumed (created in a previous transaction) – No inputs if the transaction
just creates coin (see transaction 1 in Fig 3.2)
 Outputs – coins being created. Outputs are indexed beginning with 0 – so we refer to first
output as “output 0”
 Each transaction has a unique identifier. (a Hash)

Note: The following screenshots explain Fig 3.2. If you already understand it – skip.

Change Address: In Fig 3.2, in transaction 1, Alice receives 25 coins. Then she wants to pay 17 bitcoins to
Bob, but the output she owns is worth 25 bitcoins. So she creates another output, where 8 bitcoins are
sent back to herself. This could be a different address from the one that owned the 25 bitcoins, but it
would have to be owned by her. This is called Change Address.
Efficient Verification:

 Looking up the transaction output is easy, since, we are using hash pointers.
 To ensure it has not been spent, we need to scan the block chain between the referenced
transaction and the latest block. (We need not go all the way back to the beginning of the block
chain) – Additional data structures can speed this up.

Consolidating Funds:

 Transactions can have many inputs and many outputs, splitting and merging value is easy.
o For example, if Bob received money in two different transactions – 17 bitcoins in one
and 2 in another.
o Bob might want to have a single transaction output available for later, so that he can
spend all 19 bitcoins he controls.
o He creates a transaction using the two inputs and one output, with the output address
being one that he owns. This lets him consolidate those two transactions.

Joint Payments:

 Joint payments are easy to do


o Suppose Carol and Bob both want to pay David.
o They can create a transaction with two inputs and one output, but with the two inputs
owned by two different people
o Since the two outputs from prior transactions that are being claimed here are from
different addresses, the transaction needs two separate signatures – one by Carol and
one by Bob.
Transaction Syntax:

A transaction consists of three parts:

 Some metadata
 A series of inputs
 A series of outputs

META DATA: Some housekeeping information is present

First line – hash of the entire transaction – acts as a unique ID for the transaction. This allows us to use
this hash pointers to reference transactions.

Line 2 – version
Line 3 – Number of inputs – 2 here
Line 4 – Number of outputs – 1 here
Line 5 – Lock_time: 0 here. (Lock time is useful in micro transactions and will be explained later)
Line 6 – Size of the transaction.

INPUTS: Transaction inputs form an array and each input has the same form.

The INPUT stars with “in”: [

Each input specifies a previous transaction, so it contains a hash of that transaction, which acts as a hash
pointer to it. It also contains the index of the previous transaction’s outputs that are being claimed.

“prev-out”:{ - points to the previous output

“hash” : - provides the hash of the previous output

“n”: provides index of the previous output (0 here – first index)

The input has a “Script Sig”: Which is the Script Signature – This contains the Public Key of the person
who claims the previous output and the signature of the same person.

OUTPUTs: This is again an array. Each output has just two fields.

“out”: - points to the start of the output block

“value”: - value field – provides the value of the bitcoins getting created. The value of all the outputs
should be equal or less than the sum of all input values. If the output values are less than the sum of
inputs, the difference gets paid to the minter who writes this transaction in his block.

“ScriptPubkey”: - is the output script – which contains the double hashed value of the Public key of the
person for whom the coins are getting paid to.

It also has a set of commands like OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG – that helps
in verifying the claim – when this output hash and index are referred to in an INPUT of a later
transaction.
3.2 Bitcoin Scripts

Each transaction output does not just specify a public key. It actually specifies a script.

As mentioned before the INPUT of a current transaction refers to “Hash” and “Index” of the OUTPUT of
a previous transaction.

INPUT has a <Pubkey> and a <Sig> of the person who claims the coins created in the OUTPUT (Hash and
Index) of the previous transaction. (The <Pubkey> is the plain text version of the Pubic Key), <Sig> is the
signature)

As mentioned in the previous section, the OUPUT has a <PubkeyHash ?> which is the double hashed
version of the Public Key of the person to whom the coin is getting paid.

It also has a set of OP_ commands, that helps in verifying or matching the <Pubkey> in INPUT to the
<PubkeyHash ?> in the OUTPUT of the previous transactions and also verifying the <Sig> in the INPUT.

Hence, the scripts in the INPUT of the current transaction and the OUPUT(Index) of the previous
transactions are concatenated and executed.
As the script is STACK based – any data encountered (<>) is pushed into the stack. Any OP_ command
performs some operation on the data on the top of the stack.

When the concatenated script is run –

 <sig> is pushed into the stack (<Sig> from the INPUT)


 <Pubkey> is pushed into the stack (<Pubkey> is the plain text public key from the INPUT)
 OP_DUP is executed – This duplicates the stack top (i.e., <Pubkey>) and pushes it to the top of
the stack.
 OP_HASH160 – <Pubkey> is popped from stack top and SHA 256 hash is performed and then
160 bit hash is performed and the result is pushed to the stack as <PubkeyHash>
 <PubkeyHash ?> is pushed to the stack from OUPUT – this is the double hashed public key
present in the OUTPUT.
 OP_EQUALVERIFY: The <PubkeyHash ?> and <PubkeyHash> are popped from the stack and they
are compared. If the result is true proceeds to next step – else the transaction is rejected
 OP_CHECKSIG: The <Pubkey> and <sig> are popped from the stack and the signature is checked.
The <Pubkey> and <sig> are from the INPUT. If the result is TRUE the transaction is accepted and
added to the block, else the transaction is rejected.
Bitcoin Scripting Language

 It is specifically designed for Bitcoin and is just called “script” or “the Bitcoin scripting language”.
 It has many similarities to a language called “Forth”
o Old, Simple
o Stack-based programming language (Every instruction is executed exactly once, in linear
manner. In particular there are no loops)
 The instructions in the script gives us an upper bound on how long it might take
to run and how much memory it could use.
o The language is not Turing complete, i.e., it doesn’t have the ability to compute
arbitrarily powerful functions.
o Loops are not allowed – because by design – miners have to run these scripts, which are
submitted by arbitrary participants in the network. They should not have the power to
submit a script that might have an infinite loop.
o It has native support for cryptographic operations.
 For example, there are special purpose instructions to compute hash functions
and to compute and verify signatures.
o Only two possible outcomes can result when a Bitcoin script is executed:
 It either executes successfully with no errors, in which case the transaction is
valid. Or,
 If there’s any error while the script is executing, the whole transaction will be
invalid and shouldn’t be accepted into the block chain.
o Scripting language is very small
 There are 256 instructions – out of which 15 are currently banned and 75 are
reserved (The reserved instruction codes haven’t been assigned any specific
meaning yet, but might be used for instructions that are added at a later time.)
 It has basic arithmetic
 It has basic logic (“if” and “then” statement)
 Throwing errors
 Not throwing errors
 Returning early
 Crypto instructions, which include hash functions, instructions for signature
verification and CHECKMULTISIG that lets you check multiple signatures with one
instruction.

CHECKMULTISIG: This instruction requires specifying n public keys and a parameter t for a threshold. For
this instruction to execute successfully, at least t signatures from 5 out of n of those public keys must be
present and valid. It’s a powerful primitive. We can use it to express in compact way the concept of t out
of n specified entities must sign for the transaction to be valid.

There is a bug in the multisignature implementation. The CHECKMULTISIG instruction pops an extra
data value off the stack and ignores it. This is a quirk of the Bitcoin language, and one has to deal with it
by putting an extra dummy variable onto the stack. The bug was in original implementation, and the
costs of fixing it are much higher than the damage it causes. At this point, this bug is considered a
feature in Bitcoin, in that it’s not going away.
What is used in Practice

If we look at the scripts that have actually been used in the history of Bitcoin, nearly all are identical to
the script used in our example. This script just specifies one public key and requires a signature for that
public key to spend the coins.

There has not been much diversity in the scripts used. This is because Bitcoin nodes, by default, have a
whitelist of standard scripts, and they refuse to accept scripts that are not on the list. This doesn’t mean
that those scripts can’t be used at all; It just makes them harder to use.

Proof of Burn

 A proof of burn is a script that can never be redeemed.


 Sending coins to a proof-of-burn script establishes that they have been destroyed, since there is
no possible way for them to be spent.
 One use of proof of burn is to bootstrap an alternative to Bitcoin by forcing people to destroy
bitcoins to gain coins in the new system.
 It is quite easy to implement:
o The OP_RETURN opcode throws an error if it’s ever reached.
o No matter what values you put before OP_RETURN, that instruction will eventually be
executed, in which case this script will return false.
 Because the error is thrown, the data in the script that comes after OP_RETURN will not be
processed.
o So this is an opportunity for users to put arbitrary data in a script, and hence into the
block chain. If, for some reason, you want to write your name, or if you want to
timestamp and prove that you knew some data at a specific time, you can create a low-
value Bitcoin transaction.
o You can destroy a very small amount of currency, but you can then write whatever you
want into the block chain, which should be retained for the life of the Bitcoin system.

Pay-to-Script-Hash

 Bitcoin requires that the sender of coins has to specify the script exactly.
 Sometimes this may not be feasible. For example, if you are shopping online, and you’re about
to order something and are ready to pay. The company gives a MULTISIG address.
 Instead of telling “send coins to the hash of this public key”, “send coins to the hash of this
script”
o Impose the condition that to redeem those coins, it is necessary to reveal the script that
has the given hash, and further, provide data that will make the script evaluate to true.
o The sender achieves this by using the Pay-to-Script-Hash (P2SH) transaction type, which
has the above semantics.
 Specifically, the P2SH script simply hashes the top value on the stack, checks whether it
matches the provided hash value, and
o Then executes a special second step of validation: that top data value from the stack is
interpreted as a sequence of instructions and is executed a second time as a script, with
the rest of the stack as input.
 This P2SH support was not there in the Bitcoin’s initial design specification. It was added later.
 It solves couple of important problems:
o It removes the need for a complex response from the sender, because the recipient can
just specify a hash that the sender sends money to.
 Alice need not worry that Bob is using MULTISIG; she just sends to Bob’s P2SH
address and it is Bob’s responsibility to specify the fancy script when he wants
to redeem the coins.
o P2SH also has a nice efficiency gain.
 With P2SH outputs, the output scripts are now much smaller, as they only
specify a hash. All of the complexity is pushed to the input script.
3.3 Application of Bitcoin Scripts

Escrow Transactions

 Having a third party between two people involved in a transaction, who intervenes only when
there’s a dispute.
 Alice is ordering something from Bob. Alice do not want to pay until Bob delivers and Bob does
not want to deliver until Alice pays.
o One solution is to have Judy as a third party and go ahead with the transaction.
o This can be easily implemented with MULTISIG. Alice creates a 2-out-of-3 MULTISIG
transaction that sends some coins she owns and specifies that they can be spent if any
two of Alice, Bob and Judy sign.
o This transaction is included in block chain, and at this point, these coins are held in
escrow among Alice, Bob and Judy – such that any two of them can specify where the
coin should go.
o Case1: Both Alice and Bob are honest. After Bob delivers Alice and Bob sign and send
Bob the money. So, instead of a single transaction – two transactions are required.
o Case 2: Alice is honest and Bob cheats – Judy intervenes and Judy and Alice sign and
send the money to Alice.
o Case 3: Bob is honest and Alice cheats – Alice is not signing after receiving the goods.
Judy intervenes and Judy and Bob sign and send the money to Bob.

Green Addresses

In blockchain each block takes around 10 minutes to get written. Also, if we want to be sure that the
transaction is valid, we need to wait for another 6 blocks to be written after the block with the
transaction is written – this will take on an average one hour.

If someone uses bitcoin to order food – the vendor cannot wait for one hour to deliver the food.

To solve the problem of being able to send money using Bitcoin without the recipient accessing the
block chain, we have to introduce another third party – A bank.

Alice calls the bank and asks the bank to send money to Bob (who delivers food). Bank sends bitcoins
directly to Bob. Bob believes the bank as its history shows that it never double spends. Hence, he
delivers the food immediately.

This is a real-world guarantee and not Bitcoin-enforced guarantee. For this to work, Bob should trust
the Bank.

If the Bank double spends, people will stop trusting the green addresses. In fact, the two most
prominent online services that implemented green addresses were Instawallet and Mt. Gox, and both
ended up collapsing.

Today green addresses aren’t used much.

Efficient Micropayments
 Suppose Alice is a customer who wants to continually pay Bob small amounts of money for some
service that Bob provides.
o For example, Bob may be Alice’s wireless service provider and requires her to pay a
small fee for every minute that she talks on her phone.
 Creating a Bitcoin transaction for every minute that Alice speaks on the phone won’t work. This
will create too many transactions, and the transaction fee add up. We want to combine all these
small payments into one big payment at the end.
 We start with a MULTISIG transaction that pays the maximum amount Alice would ever need
to spend to an output requiring both Alice and Bob to sign to release the coin.
o After each minute of using the service Alice signs one transaction and sends it to Bob,
paying cumulative amount for the service and sending the rest to herself. These
transactions are signed only by Alice and not signed yet by Bob and not being published
to the block chain.
o This process continues until Alice finishes using the service. At the end Alice tells Bob to
cut off the service.
o At this point Alice will stop signing additional transactions. Bob will disconnect her
service, signs the last transaction that Alice sent and publish it to the block chain.
o All other transactions will be discarded. (Technically all the intermediate transactions
are double spends.
 Case1: Bob does not sign the last transaction and he decides “Let the money be in escrow
forever”. Alice will lose the full value that she paid at the beginning. There is a clever way to
avoid this problem.
o Lock Time: To avoid the above problem, before the micropayment protocol can even
start, Alice and Bob will both sign a transaction that refunds all of Alice’s money to her,
but the refund is “locked” until sometime in the future.
o So, after Alice signs, but before she broadcasts, the first MULTISIG transaction that puts
her funds into escrow, she’ll want to get this refund transaction from Bob and hold on to
it. (This guarantees that if she makes it to time t and Bob hasn’t signed any of the small
transactions that Alice has sent, Alice can publish this transaction, which refunds all the
money directly to her).
o The meta data of the Bitcoin transaction contains a field Lock_time. It tells miners not to
publish the transaction until the specified time. The transaction will be invalid before a
specific block number.
o This works quite nicely in the micropayment protocol as a safety value to reassure Alice
that if Bob never signs, eventually she’ll be able to get her money back.
 Multiplayer lottery – a complicated multistep protocol with lots of transactions having different
lock times and escrows in case people cheat.
 Some neat protocols use the Bitcoin scripting language to allow different people to combine
their coins in such a way that it’s hard to trace who owns which coin.

Smart Contracts

 A really cool feature of Bitcoin is that we can use scripts, miners, and transaction validation to
realize the escrow protocol or the micropayment protocol without resorting to a centralized
authority.
 Smart contracts are contracts for which we have some degree of technical enforcement in
Bitcoin.
 There are many types of smart contracts that people want to enforce but that aren’t supported
by the Bitcoin scripting language today.
o At least no one has come up with a creative way to implement them.
o With a bit of creativity, you can do quite a lot with the Bitcoin script as it currently
stands.

You might also like