Thursday, October 16, 2014

Interactive session with Electrum

I recently had the opportunity to teach telecommunication engineering graduates at ICAI the fundamentals of Bitcoin in two sessions (thanks Javier and Rafael for the opportunity). In the first session I talked about the fundamentals of Bitcoin (elliptic curves, transactions and the blockchain), following the material in the book.

I wanted the second session to be practical, so I decided to tinker with the Electrum wallet to drive home some of the Bitcoin transactions concepts introduced in the theoretical session. I decided to go with Electrum over Bitcoin Core because it is lightweight: installation and setup is faster as there is not need to download the blockchain. On the other hand, Bitcoin Core has a lot of functionality readily available to explore the blockchain. A third session on blockchain exploration using Bitcoin Core would be the natural next step.

After loading the wallet with some Bitcoin, we turned to the console view of Electrum. First we checked the addresses available:

>> listaddresses()
[
"18tc1LCXMSAGPziTk3HuUKKUQ286uyiMd7",
"1Jc4645oAT1T4b11aBVFL84ejVsmWkKs1n",
"1FwX6t96ab2KKuMHehRF3CR1K3mtxCVtXo",
"1Chp3HR94Z7ZsjG9nHFhz5BPNrjypoiHw5",
"19DCsPuYcJ69p8Hfk2RsXrfSQTFQkBbL1S"
]

These are the addresses generated by Electrum after the 12 word mnemonic code. This mnemonic code can be visualized using the command getseed:

>> getseed()
{
"mnemonic": "unable beard giant feather nobody special pants also stop decide hallway slide",
"seed": "d95a9af9f0e3241bc778909fd4f7eebb",
"version": 4
}

To retrieve the private key associated with a public key we can use the command dumpprivkey:

>> dumpprivkey("1CaPam1wUfJttt5Gkd71wzifVdjxrE9W7o")
[
"5JxQWPa2sqxBfyyyFhRKdQFKRb47FNVuhBed7YtVg5xFada4UC1"
]


Now, lets see what is the balance of our wallet:

>> getbalance()
{
"confirmed": "0.001"
}

And the unspent transaction outputs where this balance comes from:

>> listunspent()
[
{
"address": "18tc1LCXMSAGPziTk3HuUKKUQ286uyiMd7",
"coinbase": false,
"height": 0,
"is_pubkey": false,
"prevout_hash": "1c27a5ec75e4e4367f0074edded0659d33b86d52dc8683086aa248716f0261da",
"prevout_n": 0,
"scriptPubKey": "76a914568b50da42f77d267a037c5dc9ad90ff863af0d488ac",
"value": "0.001"
}
]

There is a bunch of information here, aside from the address recipient of the funds ("18tc1...") and the amount (0.001).

Notice the scriptPubKey of the transaction: "76a91...". This is the computational puzzle that anyone wishing to spend this transaction output must solve, which in this case means signing with the private key associated with the address "18tc1...".

Also, notice the hash of the transaction, that serves as the transaction id: "1c27a...". A following transaction that spends this transaction would reference this hash.

Let's go ahead and create another transaction spending 0.5 mBTC to address "1Jc46...". To achieve this, we have first to create a transaction (using the createrawtransaction command), then request Electrum to sign it (using the signrawtransaction command), and finally publish it to the blockchain (using the sendrawtransaction command). Of course, these three functions are performed by Electrum when sending bitcoins through the GUI, but it is more instructive (and fun :) ) to perform them by hand:


>> tx = wallet.make_unsigned_transaction([("1Jc4645oAT1T4b11aBVFL84ejVsmWkKs1n", 50000)], None, None, None)

This creates a transaction sending 0.5 mBTC to address "1Jc46...". Electrum chooses the unspent transaction outputs to create the transaction. The decision is straightforward in this case as there is only one unspent transaction output available in the wallet. Lets see the transaction created by Electrum:

>> decoderawtransaction(tx.raw)
{
"inputs": [
{
"address": null,
"prevout_hash": "1c27a5ec75e4e4367f0074edded0659d33b86d52dc8683086aa248716f0261da",
"prevout_n": 0,
"sequence": 4294967295,
"signatures": []
}
],
"lockTime": 0,
"outputs": [
{
"address": "1Jc4645oAT1T4b11aBVFL84ejVsmWkKs1n",
"is_pubkey": false,
"prevout_n": 0,
"scriptPubKey": "76a914c11b46240cb97ad18fd08e472c299296324819de88ac",
"value": 50000
},
{
"address": "15AuBAcN96nDH3FXZFtG3m5ySfG85w5qJ9",
"is_pubkey": false,
"prevout_n": 1,
"scriptPubKey": "76a9142dbfccee75eaed84d180d800499ceab579fbd0c288ac",
"value": 30000
}
],
"version": 1
}

The transaction has one input (the only unspent transaction output in the wallet), with transaction id "1c27a...", and two outputs:

"1Jc46...": 0.0005
"15AuB...": 0.0003

Where the values in the transactions are expressed, as is standard, in satoshis (1 satoshi = 10e-8 bitcoins = 0.00000001 bitcoins). Although we only wanted to send bitcoins to the address "1Jc46...", Electrum creates a transaction with two outputs. The reason is that all transaction outputs must be fully spent. Therefore, Electrum sends the requested 0.5 mBTC to addess "1Jc46...", and the rest (0.3 mBTC) to a new address in the wallet. Why send the change to a new address and not the original address "18tc1..."? Electrum by default does not reuse addresses, to increase privacy. Why 0.3 mBTC, where are the other 0.2 mBTC? These are the fees left to the miners.

Also note that the signature to the input is set to null, thus the transaction is not finalized and cannot be send yet. To finalize it, lets create a list with the private keys associated with the addresses with associated unspent funds:

>> public = map(lambda x:x.get('address'), listunspent())
>> public
['18tc1LCXMSAGPziTk3HuUKKUQ286uyiMd7']
>> private = [pr[0] for pr in dumpprivkeys( public )]
>> private
['5JxQWPa2sqxBfyyyFhRKdQFKRb47FNVuhBed7YtVg5xFada4UC1']

The private key "5JxQW..." corresponds to the address "18tc1...". We can now sign the transaction with this private key:

>> txsigned = signrawtransaction(tx.raw, tx.get_input_info(), private)

The variable txsigned contains the signed transaction:

>> txsigned.raw
"0100000001da61026f7148a26a088386dc526db8339d65d0deed74007f36e4e475eca5271c000000008b483045022100a83c4163b62573625e919cf440243365a0a2c4ceb2ca3c51727928786b4e394b02206379678a8e8e76e85dcd8472b86197bc5f28ede3a34ed6bda6c5312736ee005d014104786afa5fa718aa563d51eb305ccf097359145fa99e389484e69c3aa4617786a936da6837e2890448918f4d5b1cbfe132b9e210e0a3b43a2fd766ffe7d7f4c7e7ffffffff0230750000000000001976a9142dbfccee75eaed84d180d800499ceab579fbd0c288ac50c30000000000001976a914c11b46240cb97ad18fd08e472c299296324819de88ac00000000"

The part in bold (76a9142dbfccee75eaed84d180d800499ceab579fbd0c288ac) is the signature to the unspent transaction output. Finally, lets send the signed transaction to the network:

>> sendrawtransaction(txsigned.raw)
"65c2d3d164b36b9926705069043ab8d40df6187b023791d7ee53900aad4486ad"

The response to the sendrawtransaction command is the transaction id: "65c2d...". Finally, lets take a look at the list of unspent transaction outputs again:

>> listunspent()
[
{
"address": "15AuBAcN96nDH3FXZFtG3m5ySfG85w5qJ9",
"coinbase": false,
"height": 0,
"is_pubkey": false,
"prevout_hash": "65c2d3d164b36b9926705069043ab8d40df6187b023791d7ee53900aad4486ad",
"prevout_n": 0,
"scriptPubKey": "76a9142dbfccee75eaed84d180d800499ceab579fbd0c288ac",
"value": "0.0003"
},
{
"address": "1Jc4645oAT1T4b11aBVFL84ejVsmWkKs1n",
"coinbase": false,
"height": 0,
"is_pubkey": false,
"prevout_hash": "65c2d3d164b36b9926705069043ab8d40df6187b023791d7ee53900aad4486ad",
"prevout_n": 1,
"scriptPubKey": "76a914c11b46240cb97ad18fd08e472c299296324819de88ac",
"value": "0.0005"
}
]

As expected there are now two addresses with associated unspent funds: "1Jc46..." with 0.5 mBTC and the change address "15AuB..." with 0.3 mBTC.

Of course, all this could have been easily accomplished through the GUI:




Disclaimer: products and services mentioned in this post are for illustrative purposes only, and their inclusion does not constitute and endorsement by the author. This material is intended for general information purposes only and does not constitute investment, legal or tax advice.

Tuesday, September 16, 2014

Registering a document in the blockchain... and verifying it

The book has been registered in the blockchain. This post will explain the process followed to register a document in the blockchain and to verify it.

Note that in the case of legal notaries a copy of the full document is kept in archival. In principle this could also be done in the blockchain: a whole document could be split into small chunks (40 bytes size each) and stored in the blockchain. This, however poses two problems.

First, the amount of data to store in the blockchain would be quite big. Storing all this data would inconvenience nodes participating in the Bitcoin network as they would have to store a full copy of our document (plus auxiliary information in the transactions that register this information). This inconvenience has a cost, and the user causing it has to pay for it in the form of transaction fees. Consequently, storing a large document in the blockchain would cost a lot of money.

Second, sometimes we do not want the full document to become public. This is the case here, where we just want to register the existence of such document at a specific point in time.

We can solve these two problems at the same time by first computing a hash (digest) of the document, and then only storing this hash in the blockchain. Several cryptographic hash functions can be used to compute it. One of the most popular is SHA256, the same hash function used in Bitcoin's proof-of-work.

Registering the book in the blockchain


To register the book on the blockchain, the hash of the pdf of an early version of the manuscript is computed:

$ sha256sum understandingbitcoin.pdf

1324585ce12bdf2c16995835e1ba1a04246592e7755c6c1933419fe80f97f10e

The result is the hash of the pdf. This hash is a 256-bit  (32 bytes) number. Encoded in hexadecimal, it results in a 64-character string of numbers and the letters a-e (shown above). This 32-byte number was included in an OP_RETURN transaction that was published in the blockchain. The hash for this transaction (kind of the id of the transaction) is:

e144275426185d0a0b85e7bdcfdfbbaa6f7f750a522007aeaae6f0f8708838bb

Building the OP_RETURN transaction and sending it to the blockchain can be done with one of several Bitcoin wallet clients. This, however, is usually a manual process. However, there are already services that, for a fee, perform these tasks for their users. To register the book I have used  the excellent www.proofofexistence.com. Using it is as easy as dragging and dropping the file to register (the pdf with the manuscript) on the browser and then paying the small bitcoin fee.

Verifying that the book is registered

Once the book is registered, the party interested to demonstrate that the registration took place should provide the verifier a copy of the pdf and a link to the transaction in the blockchain. The verifier would first hash the pdf and check that the result matches the provided hash. In the case of the book, you would have to trust me here that the hash of the pdf is the one above.

Then the verifier would check that this hash is indeed included in the blockchain in the transaction indicated. To do this the verifier would need to have a copy of the blockchain that she trusts. She can then query the blockchain, for instance using the Bitcoin Core Server (bitcoind). The result is:

$ bitcoind getrawtransaction e144275426185d0a0b85e7bdcfdfbbaa6f7f750a522007aeaae6f0f8708838bb


0100000001abf2ec413b4a8b8f38476350ac0246f93fe355976efaa2cfe2014cad297e9e3a8c0000008b4830450221008bb8d36cba5b2b9c54cb8adaf799df6f336d7a93aaf6f6bda261512b45415d1a022075a8a700a9ebeb863ce10bd62ffe28da986fe608df9b963572e5fb3e11fd247a014104bd184b34e4e20698a7670854e16f68c4ca2f9326572342998bdf1b1c4685644c2374e40c19ca20eeb3439e3255d468d3e92aa32f577df99bdb409c8f064462f7ffffffff0100000000000000002a6a28444f4350524f4f461324585ce12bdf2c16995835e1ba1a04246592e7755c6c1933419fe80f97f10e00000000

This is the hex encoding of the transaction, and it contains all the information that Bitcoin nodes need to accept the transaction as valid (including a valid signature from the address sending it). It has a fair amount of information, but the relevant part is highlighted in bold: this is exactly the hash of the pdf. Thus, the hash of the pdf is secured in the blockchain.

If the verifier does not have access to a copy of the blockchain, the transaction could be viewed using one of the blockchain explorer services available. However, in this case the verifier could be potentially subject to a Man-in-the-Middle attack on her browser, whereby the transaction provided by the online blockchain explorer website is swapped before being presented to the user in her browser. This could allow an attacker to trick the verifier into believing that a particular hash is stored in a certain block in the blockchain, when in reality it is not.

How secure is this proof?

Very. The security of this proof rests on two pillars. First, the pre-image resistance of the SHA256 hash function. This property states that given a hash value it is computationally very difficult to find a pdf such that it hashes to it. This assures us that the pdf is indeed linked to the hash value, as no other pdf can be generated such that its hash is the same.

Second, the security of the blockchain itself. The transaction containing the hash is included in block 310,910. As of the time of writing, this block has 10,074 confirmations, meaning there have been a total of 10,074 blocks mined on top of this block. Imagine a cheater wants to include the hash of a pdf that has been recently generated. That is, the cheater wants to include the hash of the pdf in the blockchain a posteriori. She would have to mine 8,505 blocks and catch up with the blocks mined by the rest of the network. The amount of hashing power required to pull off this feat is in the order of tens or hundred of millions USD (depending on the time-frame under which the cheater operates). Too much hassle to break the proof-of-registry of a humble book.




Disclaimer: products and services mentioned in this post are for illustrative purposes only, and their inclusion does not constitute and endorsement by the author. This material is intended for general information purposes only and does not constitute investment, legal or tax advice.

Wednesday, September 10, 2014

Bitcoin Money Supply

I sometimes get the question of what is the money supply of Bitcoin. The answer is, of course, that the total monetary supply is fixed at something over 21 million bitcoins, and also that the path of monetary supply is predetermined. But, wait a second, if miners are mining new bitcoins into existence how can the path of monetary supply be fixed?

The path of monetary supply

I like this kind of question, because it has a simple, closed answer: it is written in the source code. To understand the path of monetary supply we have to look at several parts of the Bitcoin source code.

But first, lets clear out a common misconception. Bitcoin mining differs from, say, gold mining in an important aspect: in gold mining if all miners in the world decide to mine harder (i.e. invest more in mining equipment, hire more workers, start new exploration, and so on) then gold will be mined faster. Not so in Bitcoin: if all Bitcoin miners decide to mine harder (i.e. invest more in ASICs), the number of bitcoins awarded to the miners stays the same. In other words, the difficulty of the mining problem increases, so that each individual miner is rewarded less bitcoins for solving the same mining (partial hash inversion) problem. This decrease in the reward exactly offsets the increase in total network hash rate (mining power), so that the total reward to miners stays the same.

Let's see where all this is written in the code. First, lets look at the function GetBlockValue in main.cpp:

int64_t GetBlockValue(int nHeight, int64_t nFees)
{
    int64_t nSubsidy = 50 * COIN;
    int halvings = nHeight / Params().SubsidyHalvingInterval();

    // Force block reward to zero when right shift is undefined.
    if (halvings >= 64)
        return nFees;

    // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
    nSubsidy >>= halvings;

    return nSubsidy + nFees;
}

The first bold line fixes the reward to miners (called nSubsidy) to 50 bitcoins. This is the initial reward to miners, during the first 4 years of existence of Bitcoin. The second line defines the variable halvings which will have the reward to miners. As the comment indicates, this halving occurs every 210,000 blocks or roughly every 4 years. But where in the code is it indicated that the halving occurs every 210,000 blocks? In  chainparams.cpp:

class CMainParams : public CChainParams {
public:
    CMainParams() {
        ...
        bnProofOfWorkLimit = ~uint256(0) >> 32;
        nSubsidyHalvingInterval = 210000;
        nEnforceBlockUpgradeMajority = 750;
        ...

The variable nSubsidyHalvingInterval controls the number of blocks that have to lapse before the reward to miners is halved. Thus, every 4 years the reward awarded to miners for each mined block is halved. This allows us to compute the number of bitcoins created:

Year 1: 50*52,560 = 2,628,000
Year 2: 50*52,560 = 2,628,000
Year 3: 50*52,560 = 2,628,000
Year 4: 50*52,560 = 2,628,000
Year 5: 25*52,560 = 1,314,000
Year 6: 25*52,560 = 1,314,000
Year 7: 25*52,560 = 1,314,000
Year 8: 25*52,560 = 1,314,000
Year 9: 12.5*52,560 = 657,000
Year 10: 12.5*52,560 = 657,000
...

Where 52,560 = 6 * 24 * 365 is the number of 10 minute periods in a year (let's pretend that there are no leap years). This series sums to 21,052,464, which is the total money supply of bitcoins.

But surely it is not that simple...

It turns out it is not. The path of monetary creation, and thus the total monetary supply is written in the code. So it could potentially be changed. This is where it gets complicated... and interesting.

According to the Bitcoin wiki the total monetary supply and its path of creation cannot be subject to change, or the end result should not be called Bitcoin. But changed it can be. So what would happen if it was changed?

As with all changes there would be winners and losers. For instance, if the money supply of Bitcoin where increased, the current holders of bitcoins would likely be losers, as their bitcoins would be worth less. On the other hand, miners benefiting from an increased block reward would be winners.

The losers would oppose the change and the winners would favor it. Would they vote on the outcome? Perhaps. But a likely outcome is that both groups would part ways: there would be a fork in the code, creating two different versions of Bitcoin.

Chaos would ensue, and this will likely harm both groups. This is the reason why many argue that such a change would in the end harm everyone, even the supposedly "winners."

In a sense forking Bitcoin in such a way is not that different from creating an alt-coin with the new money supply rules: the difference mostly lies in semantics and what project keeps the Bitcoin name and "brand value."

Future proponents of a change to the monetary supply rules know that the outcome of a direct fork would be harmful, and thus would likely try to gather enough support from all parties involved before executing the change.

And this is the key: whether changes in Bitcoin are accepted or not ultimately depends on the mind-share of the proposed changes among all parties involved: developers, businesses, miners, users, ...

Friday, September 5, 2014

"Understanding Bitcoin: Cryptography, Engineering and Economics" is available for pre-order

The book "Understanding Bitcoin: Cryptography, Engineering and Economics" is available for pre-order: wiley, amazon.co.uk, amazon.com, amazon.es.

In this companion blog for the book, extensions to some ideas explored in the book as well as new ideas and technologies occurring in the world of cryptocurrencies will be explored.