bitcoin : a fierce decentralized crypto currency - report

18
Bitcoin A decentralized, fierce internet currency & how to earn it Shivek Khurana {[email protected] } Cluster Innovation Centre University of Delhi Report submitted in partial fulfillment of the requirements for the Degree of Bachelor of Technology : Mathematics and IT

Upload: shivek-khurana

Post on 29-Jan-2015

119 views

Category:

Education


2 download

DESCRIPTION

This report outlines the bitcoin protocol and analysis ways to mine it.

TRANSCRIPT

Page 1: Bitcoin : A fierce decentralized crypto currency - Report

Bitcoin

A decentralized, fierce internet currency & how to earn it

Shivek Khurana {[email protected]}

Cluster Innovation CentreUniversity of Delhi

Report submitted in partial fulfillment of the requirements for the Degree ofBachelor of Technology : Mathematics and IT

Page 2: Bitcoin : A fierce decentralized crypto currency - Report

Abstract

Bitcoin is a peer to peer, decentralized crypto-currency. Bitcoin design and prototype was published by Satoshi Nakamoto in 2008 and since then, the protocol has been on a rollercoaster ride. The current 1

value of the bitcoin ecosystem is $ 4,072,936,500 (at $380/BTC) and is rising exponentially. Unlike 2

traditional currencies, there are no banks or other forms of regulators. All transactions are entries into a public ledger called the blockchain. The system is regulated by volunteers called miners (or a voluntary group called mining pool). The money supply is a algorithmically regulated. The maximum numbers of bitcoins that can be generated is 20,999,999.9769. New bitcoins are generated as a reward in the mining process. The difficulty of mining process is exponential to bitcoins generated. In this paper, I have studied the bitcoin protocol and implemented a basic CPU based bitcoin miner that runs on the getwork 3

protocol.

Keywords

bitcoin, litecoin, bitcoin protocol, mining, mining pool, proof of work in bitcoin, getwork

1 Satoshi Nakamoto is the pseudonymous person or group of people who designed and created the original Bitcoin software, https://en.bitcoin.it/wiki/Satoshi_Nakamoto2 As of November 12, 2013, http://bitcoinwatch.com/3 JSON RemoteProcedure Call https://en.bitcoin.it/wiki/Getwork

Page 3: Bitcoin : A fierce decentralized crypto currency - Report

Index

1. Index2. Index of Figures3. Index of Tables4. Intended audience5. Introduction6. Bitcoin Protocol

a. Cryptographic Hashesb. Properties of a good cryptographic hash function :c. Digital Signaturesd. Pseudonymous Transactionse. Transactionsf. Blocks and Block Chaing. Proof Of Workh. Mining Networki. Money Supplyj. Double Spendingk. Mining Pooll. Json RPC Getworkm. Real World Example (from slush pool knowledge base#)

i. Miner connects the serverii. Authorize workers

iii. Description of every field of the notification in the particular order:iv. How to build coinbase transaction ?v. How to build block header?

vi. How to submit share?7. Jinter : A web based bitcoin miner8. Future Work9. Conclusion

1

Page 4: Bitcoin : A fierce decentralized crypto currency - Report

Index of Figures

Fig 1 : Schematic Representation of Digital Signature SchemeFig 2 : Real Life vs Pseudo Identity of a transacting partyFig 3 : Structure of a Transaction BlockFig 4 : Making a transaction using a bitcoin wallet clientFig 5a : Unmined transactionsFig 5b : Each miner has her own copy of unmined transactionsFig 6 : Miner’s block and attaching it to the block chainFig 7 : Cumulative network hashrate from Jan 2013 to Jan 2014

Index of Tables

Table 1 : No. of bitcoins in circulation (estimated)Table 2 : Blocks mined by various pools. Data for last 2016 block as on January 9 2014,

Intended audience

This paper was written as a result of a project “Mining Bitcoins”. It includes the functional aspects of bitcoins and how the community goes about mining it. I briefly touch the difference between solo mining and pooled mining. The vision here is to give a technical overview of the Bitcoin protocol and empower the reader to get involved into it. For the economic effects of bitcoins and how it can possibly disrupt existing bank systems, see “Economic Effects of Bitcoins [4]”

Introduction

Bitcoin is an anonymous crypto-currency, regulated by a group of volunteers called miners. Bitcoin transactions are not like physical transactions where value is directly transferred from one party to another as a currency note. A bitcoin transaction is a ledger item. A party (say Alice) can transfer bitcoins to another party (say Bob) by creating a ledger item that credits ‘A’ bitcoins to Bob. For this, the presence of one or more ledger items that credited ‘A’ or more bitcoins to Alice is mandatory. In simple words, Alice cannot spend the bitcoins she doesn’t have. This transaction is broadcasted to the network of bitcoin miners where the above mentioned validation takes place. There are other validations , about which I’ll talk in subsequent sections. The miner collects all transactions and forms a block. If a single transaction was a ledger entry, then the block is a ledger page. Each miner has different blocks that include same transactions. The miner’s task now is to get his block accepted to the block chain (i.e the ledger itself). For this, he needs to come up with a proof of work acceptable by the entire network. The protocol estimates that the entire ecosystem should come up with a valid proof every 10 minutes. To ensure this, the difficulty is calibrated every 14 days. Once a miner has a valid proof, the block gets attached to the block chain and all miners then start validating the next set of transactions. As a reward for coming up with a proof, the miner is awarded with 50 bitcoins. This reward is halved every 210,000

2

Page 5: Bitcoin : A fierce decentralized crypto currency - Report

blocks and currently is 25 bitcoins. Along with this reward, the miner also gets to collect the transaction fee. All transactions are alphanumeric hashes. Bitcoins can be exchanged for real currencies on exchanges like Mt. Gox .1

The mining process is hardware intensive. Mining software have evolved extensively, starting from 2

simple CPU based miners, to GPU based miners and special ASIC chips now. After studying all available technologies, I concluded that hosted mining solution are best to keep up with continuously increasing 3

difficulty. Another approach could be desktop clusters, where the miner runs in the background. This might not be as good as an ASIC chip or a hosted solution, the volume of bitcoins generated can be increased by simply adding more desktops. This approach is suitable only for casual miners with abundant desktop availability (like a university student who has access to all labs or an office person). The web browser can also be used as a miner. This approach, although unethical, is interesting because it converts a websites entire traffic into an army of bitcoin miners.

I have worked on an existing get work based solution written as a webapp and modified and updated it to fit the getwork standard. An average rate of 50 khash is obtained per computer in contrast with upto 5 ghash on dedicated ASICs.

Bitcoin Protocol

The protocol specified by Nakamoto is a mechanical replica of existing banking systems. The sharp contrast is : providing the validation power to users rather than the banks. In fiat banking system, the issuing authority mints currency(as per the statistically measured economic status of that country) and circulates it in the territory. For example, The Reserve Bank of India issues � notes and is then circulated across entire continent. Now when a purchase is made against this note, it’s RBI’s responsibility to authorize it. It does the same by promising to pay the bearer a sum of one thousand rupees. This promise ensures that whoever exchanged a good or service against that note can further exchange a good or service against the note he has.

In bitcoin, the RBI does not exist, and the currency is minted by miners. Just like RBI, a government institution earns seigniorage, the miner earns bitcoins for each transaction block she validates, i.e. mathematically guarantee to be legit. This reward for mining is called coinbase. The coinbase keeps the miner indulged into mining. The authenticity of a bitcoin transaction depends on :

1. Does the person owns bitcoins he is spending ?2. Has he spend the same bitcoins before (double spending) ?

Such validations are not required in fiat systems because the physical nature of the currency. You can

1 https://www.mtgox.com/2 Alec Liu, “A Guide to Bitcoin Mining: Why Someone Bought a $1,500 Bitcoin Miner on eBay for $20,600”, http://motherboard.vice.com/blog/a-guide-to-bitcoin-mining-why-someone-bought-a-1500-bitcoin-miner-on-ebay-for-206003 http://www.butterflylabs.com/landing/slanding.php

3

Page 6: Bitcoin : A fierce decentralized crypto currency - Report

never spend a rupee that you don’t have, but because bitcoins are basically electrical voltages in a distributed computer network, validations are necessary.

Cryptographic Hashes

A cryptographic hash is a mathematical function which converts a given input (and optional operation parameters) into an encoded output, hiding almost all features of the input. For example, consider a linear mathematical function :

Equation 1

Suppose I pass an input argument x = 4 to the function, the output(also referred to as digest or hash) willbe 11. 11 has no properties of 4, is mathematically different and cannot be related to 4 in anyway (exceptthat both are integers). The same principle is applied to hide important information and messages usingcryptographic hash functions which make it almost impossible to relate the output back to input.

As evident from Equation 1, if function f(x) is known, the input argument can easily be concluded if outputis known, i.e. we can get back to 4 if 11 and f(x) is known, but this defies the purpose of securinginformation, hence Equation 1 is not a good cryptographic hash function.

Properties of a good cryptographic hash function :

1. Computationally efficient : Should have a low time/ memory complexity4

2. Collision resistance : It should be hard to find two inputs which have same digest or no twoinputs should have the same digest. The first definition is more apt because we know that set ofinputs is infinite and this infinite set is mapped to a finite set (all literals of length 256 in case ofSHA 256) so we cannot guarantee that the hashes will always be different.

3. Hide input characteristics : The hash should be such that no property of the original input can beinferred

4. Well distributed : The hash should appear random

The Bitcoin protocol can work with any hash function which satisfies the above requirements. Currently,two major hash functions are being used. (The mechanism of usage is explained in later sections)

1. SHA256 (used by bitcoin)5

2. Scrypt (used by litecoin)6

Digital Signatures

A digital signature is an electronic equivalent of a physical signature. Consider two parties Alice and

4 Complexity of Algorithms, IISc Banglore, http://lcm.csa.iisc.ernet.in/dsa/node4.html5 http://www-ma2.upc.es/~cripto/Q2-06-07/SHA256english.pdf6 Colin Percival, STRONGER KEY DERIVATION VIA SEQUENTIALMEMORY-HARD FUNCTIONS, http://www.tarsnap.com/scrypt/scrypt.pdf

4

Page 7: Bitcoin : A fierce decentralized crypto currency - Report

Bob. If Alice wants to transfer some important information (a transaction initiation in bitcoin’s case) to Bob, and Bob on the other hand wants to ensure that the information he received was sent by Alice, a digital signature scheme can be used.

Fig 1 : Schematic Representation of Digital Signature Scheme

A digital signature scheme is applied between two parties , each of which have a private and a public key (fundamentally these keys are long random alphanumeric text). When Alice wants to transfer Message M to Bob, Alice will encrypt M with her private key SKA using a (generally oneway ) cryptographic hash 7

function to obtain output M*. The receiving party Bob will have a copy of Alice’s public key VKA. This public key will be used to verify the authenticity of M* by using an inverse hash functions which yields a boolean true or false value. The bitcoin protocol uses ECDSA for processing signatures.8

Pseudonymous Transactions

Physical world transactions have the identities of involved parties attached. For example, if I write acheque to pay my university fee, the government can always trace the transaction parties simply byverifying against the cheque number of the issuing bank. But bitcoin has no issuing authority, so the partiescannot be traced back(theoretically), given a particular transaction. In the bitcoin ecosystem, each memberis defined by a public private key pair. Suppose Alice and Bob are the real world identities of twoparties, then in the bitcoin ecosystem, Alice will be identified as her public key and her real worldidentity will be hidden. Same will be true for Bob. This helps in digital signature verification as thesenders name is the public key and the hashed message can be validated against the sender itself.

In fact, the verification key is the address of a party’s bitcoin wallet. The number 32… in Fig 2 is a real lifeexample of a bitcoin address. One party may have one or more bitcoin wallets. Transactions occur

7 http://en.wikipedia.org/wiki/One-way_function8 http://en.wikipedia.org/wiki/Elliptic_Curve_DSA

5

Page 8: Bitcoin : A fierce decentralized crypto currency - Report

between two wallets. A bitcoin wallet is an online or offline software that stores a party’s transactions.9

Fig 2 : Real Life vs Pseudo Identity of a transacting party

Transactions

Bitcoin transactions are not like physical transactions. These transactions involve a fair amount of processing and validation. Bitcoin system can be visualized as a global and open ledger, where money can be credited to any member of the network, provided her pseudonymous identity(i.e. wallet address) is known. The best way to learn how a transaction work is by taking an example. Suppose Alice wants to transfer 0.05 BTC to Bob. Alice and Bob, both must have a bitcoin wallet and Alice should know the address of Bob’s wallet (it’s like sending an email with bitcoins attached). Furthermore it is mandatory for Alice to have 0.05 or more BTC at that instant of time. Because each transaction is a ledger entry, the former condition can also be interpreted as, the global ledger (blockchain) should have one or more entries crediting Alice with 0.05 BTC or more and Alice must have at least 0.05 BTC still available to her as credits if she spent the remaining.

Each ledger entry to the global ledger is called a transaction. Just like physical transactions in the ledger entry have a tabular structure, a bitcoin transaction also has a structure and unlike physical world ledgers, where the structure varies from one individual to another, the bitcoin transaction structure is programmatically generated and uniform throughout the system.

A transaction consists of two parts : input and output. Input part is a reference to all the transactions which credited bitcoins to Alice’s(sender’s) address. The output part consist of an amount being credited to Bob, the remaining amount that needs to be returned back to Alice and a small fee(optional). The number of bitcoins referenced by input and output should be equal. For the sake of our example, let us assume the Caroll and Dave credited 3 and 0.02 BTC to Alice at some point of time before she wanted to send 0.05 BTC to Bob. Figure 3 shows the structure of the transaction.

The hash of transactions between Carroll and Alice and Dave and Alice are hashed. The left part of Figure 3 represents receipt of bitcoins from Carroll's and Dave’s wallet address. These two transaction ids are passed in as the inputs to the new transaction block and then the output of transaction block is defined. The packing is done by the wallet software.The hence packed information is signed using Alice’s private key and then broadcasted to the network of miners for validation. Real example of a transactions 10

9 https://en.bitcoin.it/wiki/Wallet10 http://blockchain.info/tx/49a7a8e93efeeea1584fbe9fc16957cd05bbb315340a02ff28ec49cffdb14768?show_adv=true

6

Page 9: Bitcoin : A fierce decentralized crypto currency - Report

can be found on blockchain.

Fig 3 : Structure of a Transaction Block

Figure 4 depicts how the end user will make a transaction using a wallet. Only the receiver's address andthe amount to be transferred needs to be entered. An optional message can also be added. The visualdesign of the wallet may vary from client to client but fundamentally all wallets are same.

A transaction is complete only after a miner mines it. It should take about 10 minutes for the transaction tobe completed, but time may vary if a large percentage of the network faces a technical issue i.e. thecomputation power of the network is less.

Fig 4 : Making a transaction using a bitcoin wallet client. Source : Coinbase11

11 http://coinbase.com

7

Page 10: Bitcoin : A fierce decentralized crypto currency - Report

Blocks and Block Chain

Once a transaction is broadcasted to the network, all miners start hashing the unmined transactions and form a block. A block is a set of all transactions that are not validated yet. In the ledger analogy, if a transaction is a ledger entry, a block is a ledger page. A block is formed by pairwise hashing of unmined transactions, i.e. if there are 4 unmined transactions in the network, the miner will hash the first 2 and then the next two and finally the two digests obtained from former hashing to finally obtain a 256 bit alphanumeric string, which uniformly incorporates the information of all transactions. Every miner on the network has slightly different copies of the current block, except for miners who mine in pools, where all members of the pool work on the same copy of the block. Theoretically a new block should be attached to the blockchain every ten minutes.

Fig 5a : Unmined transactionsFig 5b : Each miner has her own copy of unmined transactions

The blockchain is the global bitcoin ledger. It is an open record of all transactions in the bitcoin network and freely available on the internet at blockchain.info. All transactions in the blockchain are final and validated. A miner’s job is to attach his copy of the latest block on the blockchain. By doing this, he is rewarded with a coinbase transaction. The attachment process is a hardware intensive mathematical puzzle, i.e needs a certain number of CPU clock cycles to be solved.

Each miner spends her hardware capability on mining in hope that she might solve the puzzle and be rewarded with a coinbase. This puzzle is called the proof of work. Once a miner on the network is able to solve the puzzle, it is broadcasted on the network to accept. After the solution is accepted and attached to the blockchain, all miners drop the current versions of their blocks, and start mining new transactions.

Proof Of Work

A proof of work is a piece of data which is costly(in terms of computation cycles) and takes time to produce so as to satisfy a certain requirement. Producing a proof of work is a brute force process with 12

uniform probability distribution, so that a lot of trial and error is required (on average) before a valid

12 Similar to brute force attach but with legit intentions http://en.wikipedia.org/wiki/Brute-force_attack

8

Page 11: Bitcoin : A fierce decentralized crypto currency - Report

proof is generated. Bitcoin uses the hashcash proof of work.13

Proof of work is based on the principle that given a good hash function, y = H(x), it is easy to calculate y given and x, but difficult to calculate x if y is given.For Example (quoted from bitcoin wiki )14

Let's say the base string that we are going to do work on is "Hello, world!". Our target is to find a variation of it that SHA-256 hashes to a value beginning with '000'. We vary the string by adding an integer value to the end called a nonce and incrementing it each time. Finding a match for "Hello, world!" takes us 4251 tries (but happens to have zeroes in the first four digits):

"Hello, world!0" => 1312af178c253f84028d480a6adc1e25e81caa44c749ec81976192e2ec934c64"Hello, world!1" => e9afc424b79e4f6ab42d99c81156d3a17228d6e1eef4139be78e948a9332a7d8"Hello, world!2" => ae37343a357a8297591625e7134cbea22f5928be8ca2a32aa475cf05fd4266b7..."Hello, world!4248" => 6e110d98b388e77e9c6f042ac6b497cec46660deef75a55ebc7cfdf65cc0b965"Hello, world!4249" => c004190b822f1669cac8dc37e761cb73652e7832fb814565702245cf26ebb9e6"Hello, world!4250" => 0000c3af42fc31103f1fdc0151fa747ff87349a4714df7cc52ea464e12dcd4e9

Fig 6 : Miner’s block and attaching it to the block chain

In the bitcoin system , the proof is to come up with a string such that SHA256 hash of the given challenge string and proof concatenated should have certain number of leading elements equal to zero. All miners are encouraged to start with a random nonce, so that different nodes generate different hashes and

13 https://en.bitcoin.it/wiki/Hashcash14 https://en.bitcoin.it/wiki/Proof_of_work

9

Page 12: Bitcoin : A fierce decentralized crypto currency - Report

repetitive hashes are avoided(to a certain extent). The protocol aims on having 1 proof every ten minutes, so that it takes only ten minutes for a transaction to be validated. If the network is taking less than ten minutes to come up with a block, the difficulty is calibrated i.e. the number of preceding zeros required will be reduced and conversely, the number of preceding zeros required will be increased. A miner is awarded with a coinbase only if she could present a proof of work and bitcoin transactions are validated in the process. The difficulty is calibrated every 2 weeks. Ideally 2016 blocks should be generated every 2 weeks (10 minutes per block - 6 blocks per hour - 144 blocks per day - 2016 blocks every two weeks)

Once a proof is obtained, it is broadcasted to be verified by the network, and is then attached to the block chain. See dotted line in Fig 6. After this, the entire network drop their copies of block and start working on the new transaction block. The first block of the block chain is called the genesis block .15

Mining Network

Mining network is the network of computers connected over the internet and collectively indulged in the process of mining. The strength of the network is calculated in Ghash/ sec i.e. no. of hashes, all the nodes of the network can collectively generate per second. The current hash rate of the network is 12,903,895.95 GH/s .16

With continuous acceptance of bitcoin, the hash rate has increased exponentially. Fig 7 shows the burst in computation strength of the bitcoin network from January 2013 to January 2014.

Fig 7 : Cumulative network hashrate from Jan 2013 to Jan 2014. Source blockchain.info

15 Details of transactions in the genesis block : http://blockchain.info/address/1ArFAXhvMbwJuub4ujnVbLFszqX3McuzsX16 source : http://blockchain.info/stats as of January 7 2014

10

Page 13: Bitcoin : A fierce decentralized crypto currency - Report

Money Supply

Notes minted by an institution is the liquid equivalent of all goods and services produced by that territory. In fiat banking systems, the government can manipulate the minting. This causes the economy drop globally, but preserves local economic structure i.e. West Indies as a country will be poor, but the rich of West Indies will continue to be rich. These manipulations are almost impossible in the case of bitcoins.

New coins are generated when a miner successfully comes up with a proof of work against which he is allowed to perform a coinbase transaction, where a predefined reward is transferred to miner’s wallet. This reward is halved every 210,000 blocks. For bitcoin, it was initially 50 BTC, as of now it is 25 BTC.

Block RewardEra

BTC/block Year Start BTC BTC Added End BTC BTCIncrease

End BTC% of Limit

0 1 50.00 2009 0 2625000 2625000 infinite 12.500%

52500 1 50.00 2010 2625000 2625000 5250000 100.00% 25.000%

105000 1 50.00 2011 5250000 2625000 7875000 50.00% 37.500%

157500 1 50.00 2012 7875000 2625000 10500000 33.33% 50.000%

210000 2 25.00 2013 10500000 1312500 11812500 12.50% 56.250%

262500 2 25.00 2014 11812500 1312500 13125000 11.11% 62.500%

315000 2 25.00 2015 13125000 1312500 14437500 10.00% 68.750%

367500 2 25.00 2016 14437500 1312500 15750000 9.09% 75.000%

420000 3 12.50 2017 15750000 656250 16406250 4.17% 78.125%

472500 3 12.50 2018 16406250 656250 17062500 4.00% 81.250%

525000 3 12.50 2019 17062500 656250 17718750 3.85% 84.375%

577500 3 12.50 2020 17718750 656250 18375000 3.70% 87.500%

630000 4 6.25 2021 18375000 328125 18703125 1.79% 89.063%

682500 4 6.25 2022 18703125 328125 19031250 1.75% 90.625%

735000 4 6.25 2023 19031250 328125 19359375 1.72% 92.188%

787500 4 6.25 2024 19359375 328125 19687500 1.69% 93.750%

Table 1 : No. of bitcoins in circulation (estimated). Source : Bitcoin Wiki 17

The estimates make it clear that the number of bitcoins in circulation will saturate around 2030. After that period, the miner will have smaller revenues, in the form of transactions fee. The bitcoin community believes that by 2030, bitcoin will be a mainstream currency, so the transaction fee generated will be enough to keep miners indulged in mining.

17 https://en.bitcoin.it/wiki/Controlled_Currency_Supply

11

Page 14: Bitcoin : A fierce decentralized crypto currency - Report

Double Spending

Suppose Alice tries to double spend her money. She transfers the 5 BTC to Bob and after the transaction block including the former transaction with Bob has been validated and appended to longest chain, i.e the chain whose combined difficulty level is maximum, she sends the same 5 BTC to Ethan.

To trick the system, she needs to append it on a fork of the main chain. Now the main chain has to openings. Aice can trick the system if she can prove that the forked chain is the longest chain, which can happen only if Alice has the computational power greater than that of the entire ecosystem(because the honest chain, by now, have added more blocks). Even if she does have that power, it will be more apt if she actually starts legit mining rather than tricking the system. Hence bitcoin protocol morally secures itself to a great extent.

Mining Pool

As bitcoin gained popularity, miners realized that their probability of earning more coinbase transactions will increase if they mine in pools, and split the reward in ratio of computation power one supplies to the pool. This idea was an instant hit. As of January 9, 2014, it is almost impossible for a solo miner to mine bitcoins. The bitcoin based pools use the getwork JSON RPC to distribute work to members while the litecoin use the stratum protocol.

Pool Found blocks

BTC Guild 513 (25.45%)

GHash.IO 346 (17.16%)

Eligius 240 (11.90%)

slush - mining.bitcoin.cz 123 (6.10%)

Discus Fish 108 (5.36%)

Bitminer 69 (3.42%)

Eclipse Mining pool 42 (2.08%)

p2pool 32 (1.59%)

Polmine 11 (0.55%)

ASICMiner 5 (0.25%)

Bitparking Merged Mining Pool 3 (0.15%)

ozcoin 2 (0.10%)

Horrible Horrendous Terrible TremendousMining Pool

1 (0.05%)

12

Page 15: Bitcoin : A fierce decentralized crypto currency - Report

Triplemining 1 (0.05%)

Table 2 : Blocks mined by various pools. Data for last 2016 block as on January 9 2014, source :blockorigin18

Json RPC Getwork

Json RPC (Javascript Object Notation : Remote Procedure Call) is a protocol to manage distributed computing networks. In the case of bitcoins, the pool server is the manager and all members of the pool are a node in the distributed computing network. The job is to hash the challenge string iterating over random nonce as supplied by the pool server and send back the result if a proof of work is obtained. The protocol specification is simple and the implementation is fairly easy.19

Real World Example (from slush pool knowledge base )20

This example contains real log of miner-pool communication which solved testnet3 block 000000002076870fe65a2b6eeed84fa892c0db924f1482243a6247d931dcab32

Miner connects the server

On the beginning of the session, client subscribes current connection for receiving mining jobs:

{"id": 1, "method": "mining.subscribe", "params": []}\n{"id": 1, "result": [[["mining.set_difficulty", "b4b6693b72a50c7116db18d6497cac52"], ["mining.notify","ae6812eb4cd7735a302a8a9dd95cf71f"]], "08000002", 4], "error": null}\n

The newline character \n is a part of the message and must be added to the end of every JSON message. Server may wait to this magic character to start processing the message. This is the most common mistake which people implementing line-based clients do!

The result contains three items:○ Subscriptions details - 2-tuple with name of subscribed notification and subscription ID.

Theoretically it may be used for unsubscribing, but obviously miners won't use it.○ Extranonce1 - Hex-encoded, per-connection unique string which will be used for coinbase

serialization later.○ Extranonce2_size - Represents expected length of extranonce2 which will be generated by the

miner.

Authorize workers

18 http://blockorigin.pfoe.be/top.php19 http://json-rpc.org/wiki/specification20 http://mining.bitcoin.cz/stratum-mining

13

Page 16: Bitcoin : A fierce decentralized crypto currency - Report

You can authorize as many workers as you wish and at any time during the session. In this way, you can handle big basement of independent mining rigs just by one Stratum connection.

{"params": ["slush.miner1", "password"], "id": 2, "method": "mining.authorize"}\n{"error": null, "id": 2, "result": true}\n

Server start sending notifications with mining jobs. Server sends one job almost instantly after the subscription.

{"params": ["bf", "4d16b6f85af6e2198f44ae2a6de67f78487ae5611b77c6c0440b921e00000000","01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff20020862062f503253482f04b8864e5008","072f736c7573682f000000000100f2052a010000001976a914d23fcdf86f7e756a64a7a9688ef9903327048ed988ac00000000", [],"00000002", "1c2ac4af", "504e86b9", false], "id": null, "method": "mining.notify"}

Description of every field of the notification in the particular order:

○ job_id - ID of the job. Use this ID while submitting share generated from this job.○ prevhash - Hash of previous block.○ coinb1 - Initial part of coinbase transaction.○ coinb2 - Final part of coinbase transaction.○ merkle_branch - List of hashes, will be used for calculation of merkle root. This is not a list of all

transactions, it only contains prepared hashes of steps of merkle tree algorithm.○ version - Bitcoin block version.○ nbits - Encoded current network difficulty○ ntime - Current ntime/○ clean_jobs - When true, server indicates that submitting shares from previous jobs don't have a

sense and such shares will be rejected. When this flag is set, miner should also drop all previous jobs, so job_ids can be eventually rotated.

How to build coinbase transaction ?

Now miner received all data required to serialize coinbase transaction: Coinb1, Extranonce1, Extranonce2_size and Coinb2. Firstly we need to generate Extranonce2 (must be unique for given job_id!). Extranonce2_size tell us expected length of binary structure. Just be absolutely sure that your extranonce2 generator always produces extranonce2 with correct length! For example my pool implementation sets extranonce2_size=4, which mean this is valid Extranonce2 (in hex): 00000000. To produce coinbase, we just concatenate Coinb1 + Extranonce1 + Extranonce2 + Coinb2 together.

How to build block header?

Now we're almost done! We have to put all together to produce block header for hashing:

version + prevhash + merkle_root + ntime + nbits + '00000000' +'00000080000000000000000000000000000000000000000000000000000000000000000000000

14

Page 17: Bitcoin : A fierce decentralized crypto currency - Report

0000000000080020000'

First zeroes are blank nonce, the rest is padding to uint512 and it is always the same. Note that merkle_root must be in reversed byte order. If you're a miner developer, you already have util methods there for doing it. For some example in Python see Stratum mining proxy source codes. Server can occasionally ask miner to change share difficulty. Default share difficulty is 1 (big-endian target for difficulty 1 is 0x00000000ffff0000000000000000000000000000000000000000000000000000), but server can ask you anytime during the session to change it:{ "id": null, "method": "mining.set_difficulty", "params": [2]}This means that difficulty 2 will be applied to every next job received from the server.

How to submit share?

When miner find the job which meets requested difficulty, it can submit share to the server:{"params": ["slush.miner1", "bf", "00000001", "504e86ed", "b2957c02"], "id": 4, "method": "mining.submit"}{"error": null, "id": 4, "result": true}

Values in particular order: worker_name (previously authorized!), job_id, extranonce2, ntime, nonce.

Jinter : A web based bitcoin miner

Jinter is a javascript miner that runs on the above defined protocol. It is a pooled mining software and is designed for pools that mine using getwork over SHA256 algorithm (bitcoin and alikes). This miner connects to the pool api and mines using the capacity of the browser. The code is open sourced . Jinter 21

uses the jquery library for sending HTTP request. All other algorithms are implemented without 22

libraries. A video demonstration of jinter is available on youtube at .

Future Work

The javascript miner achieves 50 khash/second. This is negligible compared to ASIC chips that mine at 5 ghash/second. A better implementation of the SHA256 hash and usage of webgl can improve the performance of the system. I also wish to extend this system to allow Scrypt based mining as well. Another step can be removing server dependence and creating a full featured frontend mining solution.

Conclusion

In this paper, we studied the bitcoin protocol specification, it’s vulnerabilities and measures adopted by the system to control them. We also studied and implemented the JSON remote procedure call and actually mined bitcoins. Bitcoin has potential to become a mainstream currency.

21 http://github.com/shivekkhurana/jinter22 http://jquery.com/

15