Bitcoins and the Digital Economy


3 Δεκ 2013 (πριν από 3 χρόνια και 4 μήνες)

272 εμφανίσεις

Bitcoins and the Digital Economy

Matt Blackman

Department of Computer Science

University of Wisconsin



Bitcoins have been circulated throughout the
internet since 2008 as a globally, peer owned, open
monetary network with no central authority or localization. The topic of this report will cover the
generation, transf
, and security involved with Bitcoins. Peer involvement is key to the success

survival of Bitcoins as users are able to generate Bitcoins; Validate transactions by hosting network

use the currency to give Bitcoins a real world value. The model for how incentive is
produced to keep community interest in Bitcoins and h
ow control is kept out of a small groups hands
will be the focus of this topic as the security and economic strength of Bitcoins cannot be enforced by
any one person. On top of the principles which allow the Bitcoin market exist, a deeper look into the
urity systems in place that allow Bitcoins to remain open
source and peer controlled.


Certain terms associated with Bitcoins are used across this paper and below are the definitions to some
of the language used.


A decentralized
digital currency created in 2009.


A mathematical proof
work solution that tracks the transaction history of the bitcoins
contained within it.

Block Chain

The complete record of all blocks containing the transaction history of all Bitcoins si
the first block.


How easy finding a new block will be.


When a user tries
spending a Bitcoin multiple times.


The process of finding new usable blocks to add on to the Bitcoin block chain.

Pooled Mining

ple users working together to find a block and sharing the reward for each find.


Data that validates a block and allows the kept history of transactions while preventing

illicit data alteration.

What a Bitcoin is

A Bitcoin

abbreviated BTC

is a form of currency existing solely on the internet designed to provide
anonymous, global exchanges. Bitcoins are open source, and no one

person is in charge of all of
itcoins, therefore putting the owners of Bitcoins in charge of the
market. All transactions are publicly
shared, but do not contain information on the Bitcoins' previous owners. Bitcoins are stored in what is
referred to as a “Digital Wallet”, which links your computer to the Bitcoins you own online. A user

digital wall
et is private and therefore cannot be seen by the public. A person intending to apprehend
Bitcoins is only required to have an internet connection, a working computer or internet enabled device,
and a Bitcoin client. Bitcoins are free to transfer in small
sums, but can incur small transaction fees for
ge amounts of Bitcoins or to
speed up the transfer process. Transfers are validated by user hosted
nodes that do not interfere with legitimate transfers removing the need of a middle man. The maximum

of Bitcoins allowed in the market is 21 million, which allows for a true market economy
causing the value of Bitcoins to be determined by the value addressed by Bitcoin users.


The idea of Bitcoins was first introduced to the public in 2008 by S
atoshi Nakamoto in a 9
page PDF[1]
sent out on the Cryptology Mailing list at
. Cyber currency is not a new
concept as it was first brought up by David Chaum in 1982 as a way to apply cryptography

to system
that would allow anonymous payments. David Chaum implemented the first form of cyber currency
1990 with “ecash”, a cryptology protocol using RSA blind signatures developed by David Chaum in
1982[2], which helped design future systems used with B
itcoins. The ecash system inspired the work of
other cryptographers and in 2004 Hal Finney designed the “Reusable Proof of Work” or “RPOW”
system[3], which verifies legitimate digital transactions across a large network over user and not
centralized hosted

servers without sacrificing security. RPOW is addressed in Nakamoto's original
paper to be implemented in the Bitcoin verification and security system[4].

On January 3, 2009, the Bitcoin network first went live with the first block of Bitcoins referred b
y the
“Genesis Block”[5] awarding 50BTC for the finder. Due to a design within the system, the Bitcoins
ging to the Genesis Block are not
spendable, which is viewed as an intentional quirk in the code.
Since the first block was found, over 200,000 blo
cks have been added to the block chain

The first
purchase using Bitcoins would not happen until January 12, 2009, with this transaction taking place
between Satoshi Nakamoto and Hal Finney. Finally after a ten month period the exchange rate for
Bitcoins w
as set at $1 = 1,3909.03 BTC[10].

Bitcoin Market[
6] was established and went live February 6, 2010, which remains as one of the most
popular online outlets to purchase Bitcoins. To date, the largest Bitcoin transaction happened back on
May 22, 2010 in which a user Laszlo paid 10,000 BTC for a pizza, whic
h comes out to the USD value
of around $25. MtGox[7] then was established on July 17, 2010, a market for exchanging Bitcoins to
USD, MtGox truly was the greatest hand at bring the convenience of bank trans
fers of USD to Bitcoins
and vice
versa. The growing

markets and slow appearance on the internet with sites like Slashdot[8]
publishing articles talking up this upcoming online currency had slowly brought the value of 1 BTC =

$0.50 USD and valued the entire Bitcoin market at $1,000,000 USD by November 6, 20

July 18, 2012, ArtForz generated a block using his personally designed mining farm that was built
upon the usage of OpenCL GPU processing strength. Puddinpop[9] would release his version of a
mining program that would run on the Windows CUDA graphics
. ArtForz's OpenCL mining program
would finally reach stable release and get introduced to the public for thousands of Linux miners to get
involved with on October 1, 2010. Bitcoin pooled mining first started by the user Slush had found their
first block o
n December 16, 2012. Pooled mining operations had achieved 10,000 megahashes per
second by January 8, 2010.

The largest trade for Bitcoins was made January 27, 2011 for the three Zimdollars a currency of
Zimbabwe. Each of these Zimdollars were valued at o
hundred trillion dollars Zimbabwe notes and
that total transaction earned the user 12 BTC, which was just enough at the time for a soda for you and
a friend. February 9, 2011 was a big day for Bitcoins because for the first time the Bitcoin was valued
t the same worth as the USD meaning that 1 BTC = $1.

Bitcoins are once again featured on Slashdot, Hacker News and Twitter over 2011 causing
to suffer issues on February 10, 2010 due to the new media attention. Bitcoin mining operations
d 900 Gigahashes per second for a short while on March 6, 2012 before falling back down to 500
Gigahases per second as it is believed botnet mining operations and super computers were adding large
amounts of activity.

In March of 2011, Bitcoins began to g
ain popularity outside the internet and media with the British
Pound sterling given official exchange on March 27, then the Brazilian Real March 31, and finally the
Polish Zloty April 5. With the growing international popularity, Time magazine published an

on April 16, 2011 about the possibility for Bitcoins to challenge Governments and Banks as an
exchangeable currency. Just a week after the Time article, the value of Bitcoins had passed parity with
both the USD and Euro putting the total marke
t value of Bitcoins over $10 Million USD. Then by June
2, 2011, the exchange rate on MtGox for 1 BTC was $10 USD and on June 8, 2011 the exchange rate
peaked at 1 BTC equaling $31.91 USD. Unfortunately this large peak in Bitcoin value dropped back
down, af
ter 4 days to the $10 USD exchange.

With the growing media coverage of Bitcoins brought unwanted attention of many malicious users
causing June of 2011 to contain some of the biggest exploits of the system. June 19, MtGox the current
largest distributor o
f Bitcoins had its database compromised, causing the leak of 60,000 users private
data that were associated with their Bitcoin investme
nts. Data from that leak was

found to contain some
of the same user names and passwords of users on MyBitcoin, which resu
lted in the theft of 2000 BTC
from about 600 users. MtGox had experience another venerability June 19 as an admin account was
logged in to and

of fake Bitcoins were issued over the site to deflate the value of Bitcoins
from $17.15 to $0.01.


19, 2011 was a monumental time as Bitcoins were first successful transferred over NFC (Near
Field Communication). Then July 22, 2011, Bitcoins hit the iPad app store[12] turning thousands of
users digital wallets into a real wallet with “BitCoins Mobile”.

Further Bitcoins began to impact the
physical world on August 20, 2011 with the first Bitcoin Conference and World Expo in New York,
New York[13]. Later on November 25, 2011 the first European Bitcoin Expo was held in Prague,
Czech Republic[15].

4] a decentralized mining pool

mines its first block on August 23, 2011. Peer mining such as

this allowed for many users to work together without the need for private pooling organization and the
risk of reward theft.

On the Linode Bitcoin exchange site
March 1, 2012, the largest theft of Bitcoins occurred after a
security breach resulting in the loss of nearly fifty
thousand Bitcoins[16].

September 15
16, 2012 held host to the Bitcoin conference in London[17], containing speakers and
panels held by figu
res like Richard Stallman the founder of the GNU foundry and technological activist,
and Birgitta Jonsdottir a member of the Icelandic parliament and social activist. Bitcoins working to
create a more trustable and legitimate currency created the Bitcoin F
oundation[18] on September 27,
2012. The Bi
coin Foundation as stated on their site “
Bitcoin Foundation standardizes, protects and
promotes the use of Bitcoin cryptographic money for the benefit of users worldwide.”[

Bitcoin Mining

The Bitcoin wiki
describes mining as:

, or generating, is the process of adding transaction records to Bitcoin's public ledger of
past transactions. This ledger of past transactions is called the block chain as it is a chain of
. The block chain serves to confirm transactions to the rest of the network as having taken
place. Bitcoin nodes use the block chain to distinguish legitimate Bitcoin transactions from
attempts to respend coins that have already been spent

Mining is intentionally designed to be resource
intensive and difficult so that the number of
blocks found each day by miners remains steady. Individual blocks must contain a proof of
work to be considered valid. This proof of work is verified b
y other Bitcoin nodes each time
they receive a block.[19]

As stated in the history section, the “Genesis Block” or first block mined returned a Bitcoin reward of
50 BTC. This reward for mining blocks is what motivates users to get involved in this processor heavy
group work and allows for the decentralization of
Bitcoin distribution. As more people get involved in
mining and more blocks are found the computation difficulty of new blocks is raised and reward value
for new blocks goes down. This idea of difficulty will be explain in the next subsection, but the valu
return of block finding is halved every 210,000 blocks, which means the reward will be halved around
every 4 years. The difficulty is set in a way that sets the discovery rate of Bitcoins to a new block
discovered every 10 minutes. Bitcoins generation is

capped at twenty
one million and the rate of
Bitcoin addition decreasing over time creates a Controlled Currency Supply[20] much like the US
federal reserve or gold supply in Africa does.

Blocks are chronologically added to the block chain and in some ca
ses 2 blocks might be generated
within seconds and are both put on the block chain, which in that event the block that was added first
will be chosen to continue the block chain, and the other block will remain on a fork in the chain and
have its Bitcoin r
eward removed. Blocks that are put on
a fork in the chain, orphan blocks, will remain
in the block chain and can trace back to the genesis block, but orphan blocks will not keep track of

Computational Difficulty


The process of mining invol
ves finding a SHA
256 hash that is less than or equal to a set target before
a block is accepted as valid. An example of a valid block can be found in Appendix A Figure 1. The
target is what is referred to as a “nonce” or a 32
bit field at the beginning of

the block hash with a set
run of zeros at the start. A new target for the size of nonce is set every 2016 blocks, which is calculated
off the time taken to find the last block. We can calculate difficulty as thus:

Target = 0xffff * Log

For Current
Difficulty D

Target = 0xffff * Log
208 / D

Target = D * Log
256 / (0xffff * Log

Target = D * Log
48 / 0xffff

We can then find out network Hash Rate by dividing the target by number of
hashes for 600 seconds

Hash Rate = D * Log
48 / 0xffff / 600

Rate = D * Log
32 / 600

The time it takes to find a new block then can be calculated by

time = D * Log
32 / Hash Rate

This new difficulty is the amount of hashes performed over the network per second, which is used to
determine the target. The target is

set in a way such that 2016 blocks are discovered every 2 weeks. A C
implementation to calculate this difficulty can be found in Appendix A Figure 2.

The Mining Process

For users to mine all that is required is a connection to the internet, any processing they can do, and a
mining program. Mining programs can be made by anyone and designed for any type of hardware.
Some popular mining programs are 50Miner[21], BFGMiner[22
], Cpu Miner[23], and a list of many
more can be found on the Bitcoin Wiki[24]. An example implementation of a mining program is
Python can be found in Appendix A Figure 3.

For those interested in starting Bitcoin mining should understand the difficulty o
f finding a new valid
block by mining by themselves or solo mining. The current probability of finding a valid block with
each has

is 0.0000000000000000704606474755857872804831742996611865237%[26]. So for a user
using the entire processing power of a Tera
sic DE2
115[27] with a MegaHash rate of 80 Mhashs/s
would be able to find a block for themselves every 5.63 years at the current difficulty. If it is that user

hope to profit off their mining operation

they will likely have a total loss due to the power

consumption of their mining rig. This is the reason that most mining is done through pooled mining and

Pooled Mining

As the name suggests, pooled mining is the process of many users grouping up their processing power
in hopes to uncover blocks
together and split the rewards by hashes contributed. So in a fairly
distributed mining operation upon finding a block would split the reward as such:


Personal Reward = Total Reward * ( Personal Hash Rate / Pool Hash Rate )

Although this does remove much

of the reward for finding blocks it will greatly increase the probability
that y
ou shall receive any reward
. Resources online can help you determine the profitable of mining in
a pool with such sites like the Bitcoin Mining Calculator[28].

A concern with

pooled mining is that large enough pools under the control of a few could threaten the
ideal of decentralized distribution. Although this would be a very difficult operation to pull of

due to
the size of network combined processes, which currently is ove
r two
hundred seventy
five PetaFlops
per second. As low as the threat of centralization is, systems have been implemented that helps
anonymously distribute and evenly payout miners called P2Pool mining.

P2Pool Mining

To overcome the threats of large

mining pool operation taking over a majority of generation, or users
stealing blocks they discover in their mining pool, P2Pool distributes new block discovery in fair shares
to miners such that more miners receive rewards without the threat of theft or c
mining is one community’s effort many people are working together on, rather than how mining pools
are working independently for payoff.
Unlike how mining works off the Bitcoin block chain, P2Pool
breaks off the last 8640 blocks, a da
y’s worth of blocks, into P2Pool’s custom block chain, which is
called the “share chain”.

Blocks inside the share chain are called shares, because unlike a regular block,
a share contains the Bitcoin block hash, and P2Pool data such as the total subsidy, a

nonce, payout
script of this share, the previous share’s hash, and the current target for shares.
The difficultly to find a
valid share is lower than that of a valid block as the difficulty for shares is set so a valid share in
P2Pool is found every 10 se

Operations with large processing resources still run the risk of
discovering more valid shares than operations who cannot afford such equipment, so P2Pool allows
users to raise their difficulty to discover shares,
lowering their chance to find valid


Once a

peer locates a

valid share, that peer announces
the find to all other peers who then verify the
share’s transaction history matches that of the share chain. Since the difficulty of a share does not
match the difficulty of a block, all val
id shares are not valid blocks. After a share is discovered that
matches the difficulty of a valid block, the node that discovered the share can get a payout from P2Pool

and the share chain is then added to the block chain
The payout for P2Pool evenly dis
tributes Bitcoin
rewards in a matter described as such from the Bitcoin Wiki:


share contains a generation transaction that pays to the previous n shares, where n is the
number of shares whose total work is equal to 3 times the average work required to

solve a
block, or 8640 (= 24 hours of shares), whichever is smaller. Payouts are weighted based on the
amount of work each share took to solve, which is proportional to the p2pool difficulty at that

The block reward (currently 50BTC) and the
transaction fees are combined and apportioned
according to these rules:

A subsidy of 0.5% is sent to the node that solved the block in order to discourage not sharing
solutions that qualify as a block. (A miner with the aim to harm others could withhold t
he block,
thereby preventing anybody from getting paid. He can NOT redirect the payout to himself.) The
remaining 99.5% is distributed evenly to miners based on work done recently.


In the event that a share qualifies as a block, this generation
transaction is exposed to the
Bitcoin network and takes effect, transferring each node its payout.

Stales, shares that cannot be added to the share chain, happen frequently in P2Pool mining for 2 main
One reason for a stale comes from “Dead On Ar
rival”, in which a share found to be valid on
your local P2Pool network is no longer in the share chain. This usually is the result of a user’s local
P2Pool client is not properly configured. The other reason is from orphan shares, when a valid share is
t extended to the full network before another miner’s share is accepted into the pool. This happens
when a network connectivity problem effects either the pool or the local miner that found the orphan
share. Stales are not bad for the pool or users, and st
ales are expected when users join P2Pool because
it takes time to set up their node properly.

Bitcoin Security

Being that Bitcoins deal with money, the security of users

investments is
principally the largest
concern, which is where all the crypto
logy that goes into blocks and publ
ic key cryptology used in

verify transactions made to the block chain using an honest node chain network in
the proof of work problem is solved and passed along a network.

Block Usages for Transac
tion History and Security

The purpose of the block chain is to keep a public ledger of all Bitcoin transaction history containing
information on how many Bitcoins have been allocated to each address, and validate new blocks being
added to the chain.
block is constructed out of a hash of the bloc
ks address, the transaction history of
Bitcoins monitored by the block
, the location of the last block, and the nonce of the block (
refer to
Appendix B Figure 1 for graphic representation of a block)
, however,
as much data this holds,
a block
is on average 12
, which means the current block chain is around
block chain not requiring large storage space is important because any user with a Bitcoin wallet must
have a

up to date

version of the block chain in order to commit transactions.
A block does not track
the transactions of a Bitcoins generated by it indefinitely, and blocks added on top will track future
Bitcoin transactions (refer to Appendix B Figure 2 for a representati
on of the block chain)

a Bitcoin

s history
is tracked across many blocks, it becomes more difficult over time for a user to
spend a Bitcoin because they would have to rewrite all blocks in the chain and validate that
change, which can c
urrently only be accomplished by a quantum computer. This transaction history is
the major achievement that Bitcoins has made

and is why Bitcoins remain the most popular form of
electronic currency


Bitcoins are transferred by signing tran
saction data (refer to Appendix A Figure

4 for example
transaction data), which is broadcast over the network and validated by honest nodes, and attaching that
transaction to the block chain.
The transaction data includes the address of the previous transa
ction, so
you can trace a Bitcoins transaction history, and the new owner’s public key.

All of this data is not
encrypted, therefore all transaction data is public information, and because the public key information
is exclusive to the Bitcoin client, user
s do not have to worry about their identity being attached to the

Referring back to the transfer example data in Appendix A Figure 4, the transaction is
broken down into two parts, the input and the output. Both of these data sections are gene
rated by the
user that is sending the Bitcoins and are required to verify the exchange.

The input of the transaction is a reference to the output of a previous transaction, and multiple inputs
are included in a transaction, which are added together
to com
bine all the previous outputs and create
part of this transactions output. Previous tx is the hash from the previous transaction on a Bitcoin.
Index is used to associate an input to its proper output since so many inputs are used. ScriptSig, half the
t used to validate a transfer, contains two sets of data used to verify the owner of the Bitcoins is
conducting this transaction, which are a signature and the public key of

the sender
The signature is an
ECDSA signature[32]

a simple hash cr
eated fro
m the transaction data. The sender’s private
signature is not publicly known, making it imposs
ible for someone to generate a s
criptSig without
access to that signature.
A s
is all the data necessary to prove the source of a transaction to the
Bitcoin owner.

The output of the transaction data is all the information required to send the Bitcoins. Value is the
Bitcoin amount being sent, and value is measured in Satoshi, where 1 BTC = 1,000,000 Satoshi. This
means Bitcoins are measurable up to the

millionth decimal so when the Bitcoin market is heavily
saturated, Bitcoins will still be viable for small transactions. The scriptPubKey
is the other half of the
script used to verify a transaction. The scriptPubKey is addressed to whoever is on the
iving end of
the transaction
. Multiple outputs can come from a single transaction, and those outputs will divide up
the inputs that point to Bitcoin values. If someone were to transfer 20 Bitcoins from their stash of 50
Bitcoins to a single user, the trans
action would create 2 outputs, one output
with a 20 Bitcoin output for
the receiver and 30 Bitcoin output for the sender to ensure no Bitcoins are lost.

Verifying the transaction involves a script which validates the data given by a sender from the scrip
and the scriptPubKey. The script used by Bitcoin is much like the forth language, and the script is used
as an instruction set about how the transaction should be conducted. First the script will look at the
scriptSig to reference the scriptPubKey it
is associated with
. After the script validates that the scriptSig
and the scriptPubKey match, the scriptPubKey will verify that whoever is attempting to claim this
transaction, and if no errors are thrown by the script, the transfer will be validated and c
hanges will be
committed to the block chain.

A graphic of this process can be found in Appendix B Figure 3.

This approach to verification allows users to send
Bitcoins in a variety of ways, such methods include 2
party transfers much like cash exchanges,
password redeemable lots, Bitcoins that don’t need
authorization to receive, which could be given at a first
serve basis, and many others.
Currently there are 3 common ways to conduct transactions, and a few more complex methods, which
are “cryp
tographically enforced agreements”[31] known as contracts. Below are the 3 types of transfer

Transfer to Bitcoin Address

A Bitcoin address is a hash

and therefore does not contain a unique public key for the sender to attach
to the scriptPubKey. Therefore when receiving coins sent to the Bitcoin address, the signature and
public key must be provided by the receiver. The script will then check that the

public key hashes into

hash, and that the signature is valid with the provided public key.


Transfer to IP Address

A public key is taken from the receiving party when the two parties communicate over IP
, and the
signature is validated

with the public key the sender assigns in the scriptPubKey.


This transaction is the result of a new block of Bitcoins being rewarded to an IP address. Because there
are no inputs on newly generated Bitcoins, a “coinbase”

takes the positio
n of the scriptSig. The
data inside a


is arbitrary because the transaction history up to this point is moot. The output
given to these transactions are generated like transfer to IP with the IP of the generator being signed to
the scriptPubKey.

Bitcoins Future

With Bitcoins maximum saturation set at 21 million Bitcoins
, which is to be reached in 2140, and their
value growing substantially larger each year, Bitcoins could go any direction as a global economy.
Bitcoins changed from concepts and ideas into a real market valued in the millions in such a short
amount of time. This is the first experiment with an electronic currency that doesn’t fit under the rule of
any governance, and could outlive many existing c
urrencies that have begun to fall with a globally
crashing economy. We are
all worried about the financial situation and are applying our tools and
knowledge to remedy this crisis, but little has the mainstream considered that much like our move off
the go
ld standard that it is time again to shift the basis of our economy. More electronic currencies will
build off the path that Bitcoins has begun, and with time and experience we might see the end of
isolated currencies much like Europe is experiencing with
the Euro. Much as we cannot predict the
path our economy takes, we cannot assume what Bitcoins could hold in store, but once more
understanding is public maybe we will see an economic shift to a digital market.


Nakamoto, S. N. (2008, Nove
Bitcoin: A peer
peer electronic cash system
. Retrieved from

[2] Chaum, D. (1982).
Blind signatures for untraceable payments
. Retrieved from

nney, H. (2004, August 15).

reusable proofs of work
. Retrieved from

Ladd, W. (2012, March 04).
Blind signatures for bitcoins transaction anonymity
. Retrieved from

Block. (n.d.). In
Bitcoin Wiki
. Retrieved November 11, 2012, from




[8] Dawson, K. (2012, July 11).
Bitcoin releases version 0.3
. Retrieved from

Pop, P. (2010, September 18).
Generating bitcoins with your video card
. Retrieved from


Brito, J. (16).
Online cash bitcoin could challenge governments, banks
. Time Tech. Retrieved from





Goodin, D. (2012, March 02).

Bitcoins worth $228,000 stolen from customers of hacked webhost
Retrieved from




Mining. (n.d.). In
Bitcoin Wiki
. Retrieved November 11, 2012, from






Mining A
pps. (n.d.). In
Bitcoin Wiki
. Retrieved November 11, 2012, from




Mining Hardware Comparison. (n.d.). In
Bitcoin Wiki
. Retr
ieved November 11, 2012, from



P2Pool. (n.d.). In
Bitcoin Wiki
. Retrieved November 11, 2012, from


Block Chain. (n.d.). In
Bitcoin Wiki
. Retrieved November 11, 2012, from


Transactions. (n.d.). In
Bitcoin Wiki
. Retrieved November 11, 2012, from


Johnson, D., Menezes, A., & Vanstone, S. (2001).

The elliptic curve digital signature algorithm
. Retrieved from

Appendix A































ef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f OP_CHECKSIG"










Figure 1: The SHA
256 Hash of the Genesis Block as it was first found

#include <iostream>

#include <cmath>

inline float fast_log(float val)


int * const exp_ptr = reinterpret_cast <int *>(&val);

int x = *exp_ptr;

const int

log_2 = ((x >> 23) & 255)


x &= ~(255 << 23);

x += 127 << 23;

*exp_ptr = x;

val = ((
1.0f/3) * val + 2) * val


return ((val + log_2) * 0.69314718f);


float difficulty(unsigned int bits)


static double max_body =
fast_log(0x00ffff), scaland = fast_log(256);

return exp(max_body

fast_log(bits & 0x00ffffff) + scaland * (0x1d

((bits & 0xff000000) >> 24)));


int main()


std::cout << difficulty(0x1b0404cb) << std::endl;

return 0;


Figure 2: C imple
mentation of difficulty calculation



# Copyright (c) 2011 The Bitcoin developers

# Distributed

under the MIT/X11 software license, see the accompanying

# file COPYING or


import time

import json


import hashlib

import struct

import re

import base64

import httplib

import sys

from multiprocessing import Process


MAX_NONCE = 1000000L

settings = {}

pp = pprint.PrettyPrinter(indent=4)

class BitcoinRPC:


def __init__(self, host, port, username, password):

authpair = "%s:%s" % (username, password)

self.authhdr = "Basic %s" % (base64.b64encode(authpair))

self.conn = httplib.HTTPConnection(host, port, False, 30)

def rpc(self, method, params=None):

self.OBJID += 1

obj = { 'version' : '1.1',

'method' : method,

'id' : self.OBJID }

if params is None:

obj['params'] = []


params'] = params

self.conn.request('POST', '/', json.dumps(obj),

{ 'Authorization' : self.authhdr,

type' : 'application/json' })

resp = self.conn.getresponse()

if resp is None:

print "JSON
RPC: no response"

return None

body =

resp_obj = json.loads(body)

if resp_obj is None:

print "JSON
RPC: cannot JSON
decode body"

n None

if 'error' in resp_obj and resp_obj['error'] != None:

return resp_obj['error']

if 'result' not in resp_obj:


RPC: no result in object"

return None

return resp_obj['result']

def getblockcount(self):

return self.rpc('getblockc

def getwork(self, data=None):

return self.rpc('getwork', data)

def uint32(x):

return x & 0xffffffffL

def bytereverse(x):

return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |

(((x) >> 8) & 0x0000ff00) | ((x) >> 24) ))

def bufreverse(in_buf):

out_words = []

for i in range(0, len(in_buf), 4):

word = struct.unpack('@I', in_buf[i:i+4])[0]

out_words.append(struct.pack('@I', bytereverse(word)))

return ''.join(out_words)

def wordreverse(in_buf):

out_words = []

for i in range(0, len(in_buf), 4):



return ''.join(out_words)

class Miner:

def __init__(self, id): = id

self.max_nonce = MAX_NONCE

def work(self, datastr, targetstr):

# decode work data hex string to binary

static_data = datastr.decode('hex')

static_data = bufreverse(static_data)

# the first 76b of 80b do not change

blk_hdr = static_data[:76]

# decode 256
bit target value

targetbin = targetstr.decode

targetbin = targetbin[::
1] # byte
swap and dword

targetbin_str = targetbin.encode('hex')

target = long(targetbin_str, 16)

# pre
hash first 76b of block header

static_hash = hashlib.sha256()


for nonce in xrange(self.max_nonce):

# encode 32
bit nonce value

nonce_bin = struct.pack("<I", nonce)

# hash final 4b, the nonce value

hash1_o = static_hash.copy()


hash1 = hash1_o.digest()

# sha256

hash of sha256 hash

hash_o = hashlib.sha256()


hash = hash_o.digest()

quick test for winning solution: high 32 bits zero?

if hash[
4:] != '


# convert binary hash to 256
bit Python long

hash = bufreverse(hash)

hash = wordreverse(hash)

hash_str = hash.

l = long(hash_str, 16)

# proof
work test: hash < target

if l < target:

int time.asctime(), "PROOF
WORK found: %064x" % (l,)

return (nonce + 1, nonce_bin)


print time.asctime(), "PROOF
WORK false


positive %064x" % (l,)

# return (nonce + 1, nonce_bin)

return (nonce + 1, None)

def submit_work(self, rpc, original_data,

nonce_bin = bufreverse(nonce_bin)

nonce = nonce_bin.encode('hex')

solution = original_data[:152] + nonce + original_data[160:256]

param_arr =
[ solution ]

result = rpc.getwork(param_arr)

print time.asctime(), "
> Upstream RPC result:", result

def iterate(self, rpc):

work = rpc.g

if work is None:



if 'data' not in work or 'target' not in work:



time_start = time.time()

(hashes_done, nonce_bin) =['data'],


time_end = time.time()

time_diff = time_end


self.max_nonce = long(

(hashes_done * settings['scantime']) / time_diff)

if self.max_nonce > 0xfffffffaL:

self.max_nonce = 0xfffffffaL

if settings['hashmeter']:

print "HashMeter(%d): %d hashes, %.2f Khash/sec" % (, hashes_done,

(hashes_done / 1000.0) / time_diff)

if nonce_bin is not None:

self.submit_work(rpc, work['data'], nonce_bin)

def loop(

rpc = BitcoinRPC(settings['host'], settings['port'],

settings['rpcuser'], settings['rpcpass'])

if rpc is None:


while True:


def miner_thread(id):

miner = Miner(id)


if __name__ == '__main__':

if len(sys.argv) != 2:

print "Usage: CONFIG


f = open(sys.argv[1])

for line in f:

# skip comment lines

m ='^
s*#', line)

if m:


# parse key=value lines

m ='^(
S.*)$', line)

if m is None:


settings[] =


if 'host' not in settings:

settings['host'] = ''

if 'port' not in settings:

settings['port'] = 8332

if 'threads' not in settings:

settings['threads'] = 1

if 'hashmeter' not in settings:

settings['hashmeter'] = 0

if 'scantime' not in settings:

settings['scantime'] = 30L

if 'rpcuser' not in settings or 'rpcpass' not in settings:

print "Missing username and/or password in cfg file"


settings['port'] = int(settings['port'])

settings['threads'] = int(settings['threads'])

settings['hashmeter'] = int(settings['hashmeter'])

scantime'] = long(settings['scantime'])

thr_list = []

for thr_id in range(settings['threads']):

p = Process(target=miner_thread, args=(thr_id,))



time.sleep(1) # stagger threads

print settings['threads'], "mining threads started"

print time.asctime(), "Miner Starts

%s:%s" % (settings['host'],


for thr_proc in thr_list:


except KeyboardInterrupt:


print time.asctime(), "Miner Stops

%s:%s" % (settings['host'],

Figure 3: Python Implementation of Bitcoin Miner[25]



Previous tx:

Index: 0

scriptSig: 304502206e21798a42fae0e854281abd38bacd1aeed3ee3738d9e1446618c4571d10



Value: 500000000

scriptPubKey: OP_DUP OP_HASH160 404371705fa9bd789a2fcd52d2c580b65d35549d


Figure 4: Bitcoin Transaction Data example[31]

The input in this transaction imports 50 BTC from output #0 in transaction f5d8... Then the output

50 BTC to a Bitcoin address (expressed here in hexadecimal 4043... instead of the normal
base58). When the recipient wants to spend this money, he will reference output #0 of this transaction
in an input of his own transaction.

Appendix B


igure 1: Graphic representation of a block[1]

Figure 2: Block Chain

Blocks in the main chain (black) are the longest series of blocks
that go from the genesis block (green) to the current block. Orphan blocks (purple) are blocks that are
not in the longest chain.


Figure 3: Visualization of transfer Inputs and Outputs