Mastering Bitcoin PDF
Mastering Bitcoin PDF
Mastering Bitcoin PDF
Andreas M. Antonopoulos
Mastering Bitcoin
by Andreas M. Antonopoulos
Copyright 2010 Andreas M. Antonopoulos LLC.. All rights reserved.
Printed in the United States of America.
Published by OReilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
OReilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editors: Mike Loukides and Allyson MacDonald Indexer: FIXME FIXME
Production Editor: Melanie Yarbrough Cover Designer: Karen Montgomery
Copyeditor: FIXME FIXME Interior Designer: David Futato
Proofreader: FIX ME! Illustrator: Rebecca Demarest
Nutshell Handbook, the Nutshell Handbook logo, and the OReilly logo are registered trademarks of OReilly
Media, Inc. !!FILL THIS IN!! and related trade dress are trademarks of OReilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and OReilly Media, Inc. was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-37404-4
[?]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What is Bitcoin? 1
History of Bitcoin 3
Bitcoin Uses, Users and Their Stories 4
Getting Started 6
Quick Start 7
Getting your first bitcoins 9
Sending and receiving bitcoins 10
iii
Using Bitcoin Cores JSON-RPC API from the command line 39
Getting information on the Bitcoin Core client status 41
Wallet setup and encryption 41
Wallet backup, plain-text dump and restore 42
Wallet addresses and receiving transactions 43
Exploring and decoding transactions 45
Exploring blocks 48
Creating, signing and submitting transactions based on unspent outputs 50
Alternative clients, libraries and toolkits 56
Libbitcoin and sx tools 56
pycoin 57
btcd 58
5. Transactions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Introduction 111
Transaction Lifecycle 111
Creating Transactions 112
Broadcasting Transactions to the Bitcoin Network 112
Propagating Transactions on the Bitcoin Network 113
iv | Table of Contents
Transaction Structure 113
Transaction Outputs and Inputs 114
Transaction Outputs 115
Transaction Inputs 117
Transaction Fees 120
Adding Fees to Transactions 121
Transaction Chaining and Orphan Transactions 122
Transaction Scripts and Script Language 123
Script Construction (Lock + Unlock) 123
Scripting Language 125
Turing Incompleteness 127
Stateless Verification 128
Standard Transactions 128
Pay to Public Key Hash (P2PKH) 128
Pay-to-Public-Key 131
Multi-Signature 132
Data Output (OP_RETURN) 133
Pay to Script Hash (P2SH) 134
Table of Contents | v
8. Mining and Consensus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Introduction 177
Bitcoin Economics and Currency Creation 178
De-centralized Consensus 181
Independent Verification of Transactions 182
Mining Nodes 183
Aggregating Transactions into Blocks 184
Transaction Age, Fees, and Priority 184
The Generation Transaction 186
Coinbase Reward and Fees 187
Structure of the Generation Transaction 188
Coinbase Data 189
Constructing the Block Header 191
Mining the Block 192
Proof-of-Work Algorithm 193
Difficulty Representation 198
Difficulty Target and Re-Targeting 199
Successfully Mining the Block 201
Validating a New Block 201
Assembling and Selecting Chains of Blocks 202
Blockchain Forks 204
Mining and the Hashing Race 209
The Extra Nonce Solution 210
Mining Pools 211
Consensus Attacks 214
vi | Table of Contents
Ethereum 232
Future of Currencies 233
Intended Audience
This book is mostly intended for coders. If you can use a programming language, this
book will teach you how cryptographic currencies work, how to use them and how to
develop software that works with them. The first few chapters are also suitable as an in-
depth introduction to bitcoin for non-coders - those trying to understand the inner
workings of bitcoin and crypto-currencies.
ix
Why Are There Bugs On The Cover?
The Leafcutter Ant is a species that exhibits highly complex behavior in a colony super-
organism, but each individual ant operates on a set of simple rules driven by social
interaction and the exchange of chemical scents (pheromones). Per Wikipedia: Next
to humans, leafcutter ants form the largest and most complex animal societies on Earth.
Leafcutter ants dont actually eat leaves, but rather use them to farm a fungus, which is
the central food source for the colony. Get that? These ants are farming!
While ants form a caste-based society and have a queen for producing offspring, there
is no central authority or leader in an ant colony. The highly intelligent and sophisticated
behavior exhibited by a multi-million member colony is an emergent property from the
interaction of the individuals in a social network.
Nature demonstrates that de-centralized systems can be resilient and can produce
emergent complexity and incredible sophistication without the need for a central au
thority, hierarchy or complex parts.
Bitcoin is a highly sophisticated de-centralized trust network that can support a myriad
of financial processes. Yet, each node in the bitcoin network follows a few simple math
ematical rules. The interaction between many nodes is what leads to the emergence of
the sophisticated behavior, not any inherent complexity or trust in any single node. Like
an ant colony, the bitcoin network is a resilient network of simple nodes following simple
rules that together can do amazing things without any central coordination.
x | Preface
This icon signifies a tip, suggestion, or general note.
Code Examples
The examples are illustrated in Python, C++ and using the command-line of a Unix-
like operating system such as Linux or Mac OSX. All code snippets are available in the
Github repository and can be accessed online at https://github.com/aantonop/bitcoin
book in the code subdirectory of the main repository.
All the code snippets can be replicated on most operating systems with a minimal in
stallation of compilers and interpreters for the corresponding languages. Where nec
essary, we provide basic installation instructions and step-by-step examples of the out
put of those instructions.
Some of the code snippets and code output have been re-formatted for print. In all such
cases, the lines have been split by a backslash \ character, followed by a newline char
acter. When transcribing the examples, remove those two characters and join the lines
again and you should see identical results as shown in the example.
All the code snippets use real values and calculations where possible, so that you can
build from example to example and see the same results in any code you write to calculate
the same values. For example, the private keys and corresponding public keys and ad
dresses are all real. The sample transactions, blocks and blockchain references have all
been introduced in the actual bitcoin blockchain and are part of the public ledger, so
you can review them on any bitcoin system.
Preface | xi
Using Code Examples
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not need
to contact us for permission unless youre reproducing a significant portion of the code.
For example, writing a program that uses several chunks of code from this book does
not require permission. Selling or distributing a CD-ROM of examples from OReilly
books does require permission. Answering a question by citing this book and quoting
example code does not require permission. Incorporating a significant amount of ex
ample code from this book into your products documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: Mastering Bitcoin by Andreas M. Antono
poulos (OReilly). Copyright 2014 Andreas M. Antonopoulos, 978-1449374044.
Some editions of this books are offered under an open source license, such as CC-BY-
NC (creativecommons.org) in which case the terms of that licenses apply.
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at permissions@oreilly.com.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
xii | Preface
OReilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://shop.oreilly.com/product/
0636920032281.do.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Preface | xiii
Acknowledgments
This book represents the efforts and contributions of many people. I am grateful for all
the help I received from friends, colleagues and even complete strangers, who joined
me in this effort to write the definitive technical book on crypto-currencies and bitcoin.
It is impossible to make a distinction between the bitcoin technology and the bitcoin
community, and this book is as much a product of that community as it is a book on
the technology. My work on this book was encouraged, cheered on, supported and
rewarded by the entire bitcoin community from the very beginning until the very end.
More than anything, this book has allowed me to be part of a wonderful community for
two years and I cant thank you enough for accepting me in this community. There are
far too many people to mention by name - people Ive met at conferences, events, sem
inars, meetups, pizza gatherings and small private gatherings, as well as many who
communicated with me by twitter, on reddit, on bitcointalk.org and on github who have
had an impact on this book. Every idea, analogy, question, answer, and explanation you
find in this book was at some point inspired, tested or improved through my interactions
with the community. Thank you all for your support, without you this book would not
have happened. I am forever grateful.
The journey to becoming an author starts long before the first book, of course. My first
language (and schooling) was Greek, so I had to take a remedial English Writing course
in my first year of university. I owe thanks to Diana Kordas, my English Writing teacher,
who helped me build confidence and skills that year. Later, as a professional, I developed
my technical writing skills on the topic of data centers, writing for Network World
magazine. I owe thanks to John Dix and John Gallant who gave me my first writing job
as a columnist at Network World and to my editor Michael Cooney and my colleague
Johna Till Johnson who edited my columns and made them fit for publication. Writing
500 words a week for four years gave me enough experience to eventually consider
becoming an author. Thanks to Jean for her early encouragement to become an author
and for always believing and insisting that I had a book in me.
Thanks also to those who supported me when I submitted my book proposal to OReilly,
by providing references and reviewing the proposal. Specifically, thanks to John Gallant,
Gregory Ness, Richard Stiennon, Joel Snyder, Adam B. Levine, Sandra Gittlen, John Dix,
Johna Till Johnson, Roger Ver and Jon Matonis. Special thanks to Richard Kagan and
Tymon Mattoszko who reviewed early versions of the proposal and Matthew Owain
Taylor who copy-edited the proposal.
Thanks to Cricket Liu, author of OReilly title DNS and BIND who introduced me to
OReilly. Thanks also to Michael Loukides and Allyson MacDonald at OReilly who
worked for months to help make this book happen. Allyson was especially patient when
xiv | Preface
deadlines were missed and deliverables delayed as life intervened in our planned sched
ule.
The first few drafts of the first few chapters were the hardest, because bitcoin is a difficult
subject to unravel. Every time I pulled on one thread of the bitcoin technology, I had to
pull in the whole thing. I repeatedly got stuck and a bit despondent as I struggled to
make the topic easy to understand and create a narrative around such a dense technical
subject. Eventually, I decided to tell the story of bitcoin through the stories of the people
using bitcoin and the whole book became a lot easier to write. I owe thanks to my friend
and mentor, Richard Kagan, who helped me unravel the story and get past the moments
of writers block, and Pamela Morgan who reviewed early drafts of each chapter and
asked the hard questions to make them better. Also, thanks to the developers of the San
Francisco Bitcoin Developers Meetup group and Taariq Lewis, the groups co-founder,
for helping to test the early material.
During the development of the book, I made early drafts available on Github and invited
public comments. More than a hundred comments, suggestions, corrections and con
tributions were submitted in response. Those contributions are explicitly acknowl
edged, with my thanks, in Early Release Draft (Github Contributions) on page xv.
Special thanks to Minh T. Nguyen who volunteered to manage the Github contributions
and added many significant contributions himself. Thanks also to Andrew Naugler for
infographic design.
Once the book was drafted, it went through several rounds of technical review. Thanks
to Cricket Liu and Lorne Lantz for their thorough review, comments and support.
Several bitcoin developers contributed code samples, reviews, comments and encour
agement. Thanks to Amir Taaki for example code snippets and many great comments,
Vitalik Buterin and Richard Kiss for help with elliptic curve math and code contribu
tions, Gavin Andresen for corrections, comments and encouragement, Michalis Kar
gakis for comments, contributions and btcd writeup.
I owe my love of words and books to my mother, Theresa, who raised me in a house
with books lining every wall. My mother also bought me my first computer in 1982,
despite being a self-described technophobe. My father, Menelaos, a civil engineer who
just published his first book at 80 years old, was the one who taught me logical and
analytical thinking and a love of science and engineering.
Thank you all for supporting me throughout this journey.
Preface | xv
(Name - Github ID)
Minh T. Nguyen - enderminh: Github contribution editor
Ed Eykholt - edeykholt
Michalis Kargakis - kargakis
Erik Wahlstrm - erikwam
Richard Kiss - richardkiss
Eric Winchell - winchell
Sergej Kotliar - ziggamon
Nagaraj Hubli - nagarajhubli
ethers
Alex Waters - alexwaters
Mihail Russu - MihailRussu
Ish Ot Jr. - ishotjr
James Addison - jayaddison
Nekomata - nekomata-3
Simon de la Rouviere - simondlr
Chapman Shoop - belovachap
Holger Schinzel - schinzelh
effectsToCause - vericoin
Stephan Oeste - Emzy
Joe Bauers - joebauers
Jason Bisterfeldt - jbisterfeldt
Ed Leafe - EdLeafe
xvi | Preface
Quick Glossary
This quick glossary contains many of the terms used in relation to bitcoin. These terms
are used throughout the book, so bookmark this for a quick reference and clarification.
address (aka public key)
A bitcoin address looks like 1DSrfJdB2AnWaFNgSbv3MZC2m74996JafV - they consist
of a string of letters and numbers starting with a 1 (number one). Just like you
ask others to send an email to your email address, you would ask others to send
you bitcoin to your bitcoin address.
bip
Bitcoin Improvement Proposals. A set of proposals that members of the bitcoin
community have submitted to improve bitcoin. For example BIP0021 is a proposal
to improve the bitcoin URI scheme.
bitcoin
The name of the currency unit (the coin), the network and the software
block
A grouping of transactions, marked with a timestamp, and a fingerprint of the
previous block. The block header is hashed to find a proof-of-work, thereby vali
dating the transactions. Valid blocks are added to the main blockchain by network
consensus.
blockchain
A list of validated blocks, each linking to its predecessor all the way to the genesis
block.
confirmations
Once a transaction is included in a block, it has one confirmation. As soon as
another block is mined on the same blockchain, the transaction has two confirma
tions etc. Six or more confirmations is considered sufficient proof that a transaction
cannot be reversed.
difficulty
A network-wide setting that controls how much computation is required to find a
proof-of-work.
difficulty target
A difficulty at which all the computation in the network will find blocks approxi
mately every 10 minutes.
difficulty re-targeting
A network-wide re-calculation of the difficulty which occurs once every 2106 blocks
and considers the hashing power of the previous 2106 blocks.
Preface | xvii
fees
The sender of a transaction often includes a fee to the network for processing their
requested transaction. Most transactions require a minimum fee of 0.5mBTC.
hash
A digital fingerprint of some binary input.
genesis block
The first block in the blockchain, used to initialize the crypto-currency
miner
A network node that finds valid proof-of-work for new blocks, by repeated hashing
network
A peer-to-peer network that propagates transactions and blocks to every bitcoin
node on the network.
proof-of-work
A piece of data that requires significant computation to find. In bitcoin, miners
must find a numeric solution to the SHA256 algorithm that meets a network wide
target, the difficulty target.
reward
An amount included in each new block as a reward by the network to the miner
who found the proof-of-work solution. It is currently 25BTC per block.
secret key (aka private key)
The secret number that unlocks bitcoins sent to the corresponding address. A secret
key looks like 5J76sF8L5jTtzE96r66Sf8cka9y44wdpJjMwCxR3tzLh3ibVPxh
transaction
In simple terms, a transfer of bitcoins from one address to another. More precisely,
a transaction is a signed data structure expressing a transfer of value. Transactions
are transmitted over the bitcoin network, collected by miners and included into
blocks, made permanent on the blockchain.
wallet
Software that holds all your bitcoin addresses and secret keys. Use it to send, receive
and store your bitcoin.
xviii | Preface
CHAPTER 1
Introduction
What is Bitcoin?
Bitcoin is a collection of concepts and technologies that form the basis of a digital money
ecosystem. Units of currency called bitcoins are used to store and transmit value among
participants in the bitcoin network. Bitcoin users communicate with each other using
the bitcoin protocol primarily via the Internet, although other transport networks can
also be used. The bitcoin protocol stack, available as open source software, can be run
on a wide range of computing devices, including laptops and smartphones, making the
technology easily accessible.
Users can transfer bitcoin over the network to do just about anything that can be done
with conventional currencies, such as buy and sell goods, send money to people or
organizations, or extend credit. Bitcoin technology includes features that are based on
encryption and digital signatures to ensure the security of the bitcoin network. Bitcoins
can be purchased, sold and exchanged for other currencies at specialized currency ex
changes. Bitcoin in a sense is the perfect form of money for the Internet because it is
fast, secure, and borderless.
Unlike traditional currencies, bitcoins are entirely virtual. There are no physical coins
or even digital coins per se. The coins are implied in transactions which transfer value
from sender to recipient. Users of bitcoin own keys which allow them to prove owner
ship of transactions in the bitcoin network, unlocking the value to spend it and transfer
it to a new recipient. Those keys are often stored in a digital wallet on each users com
puter. Possession of the key that unlocks a transaction is the only prerequisite to spend
ing bitcoins, putting the control entirely in the hands of each user.
Bitcoin is a fully-distributed, peer-to-peer system. As such there is no central server
or point of control. Bitcoins are created through a process called mining, which in
volves looking for a solution to a difficult problem. Any participant in the bitcoin net
work (i.e., any device running the full bitcoin protocol stack) may operate as a miner,
1
using their computers processing power to attempt to find solutions to this problem.
Every 10 minutes on average, a new solution is found by someone who then is able to
validate the transactions of the past 10 minutes and is rewarded with brand new bitcoins.
Essentially, bitcoin mining de-centralizes the currency-issuance and clearing functions
of a central bank and replaces the need for any central bank with this global competition.
The bitcoin protocol includes built-in algorithms that regulate the mining function
across the network. The difficulty of the problem that miners must solve is adjusted
dynamically so that, on average, someone finds a correct answer every 10 minutes re
gardless of how many miners (and CPUs) are working on the problem at any moment.
The protocol also halves the rate at which new bitcoins are created every 4 years, and
limits the total number of bitcoins that will be created to a fixed total of 21 million coins.
The result is that the number of bitcoins in circulation closely follows an easily pre
dictable curve that reaches 21 million by the year 2140. Due to bitcoins diminishing
rate of issuance, over the long term, the bitcoin currency is deflationary. Furthermore,
bitcoin cannot be inflated by printing new money above and beyond the expected
issuance rate.
Behind the scenes, bitcoin is also the name of the protocol, a network and a distributed
computing innovation. The bitcoin currency is really only the first application of this
invention. As a developer, I see bitcoin as akin to the Internet of money, a network for
propagating value and securing the ownership of digital assets via distributed compu
tation. Theres a lot more to bitcoin than first meets the eye.
In this chapter well get started by explaining some of the main concepts and terms,
getting the necessary software and using bitcoin for simple transactions. In following
chapters well start unwrapping the layers of technology that make bitcoin possible and
examine the inner workings of the bitcoin network and protocol.
Issuers of paper money are constantly battling the counterfeiting problem by using
increasingly sophisticated papers and printing technology. Physical money addresses
the double-spend issue easily because the same paper note cannot be in two places at
once. Of course, conventional money is also often stored and transmitted digitally. In
2 | Chapter 1: Introduction
this case the counterfeiting and double-spend issues are handled by clearing all elec
tronic transactions through central authorities that have a global view of the currency
in circulation. For digital money, which cannot take advantage of esoteric inks or holo
graphic strips, cryptography provides the basis for trusting the legitimacy of a users
claim to value. Specifically, cryptographic digital signatures enable a user to sign a digital
asset or transaction proving the ownership of that asset. With the appropriate archi
tecture, digital signatures also can be used to address the double-spend issue.
When cryptography started becoming more broadly available and understood in the
late 1980s, many researchers began trying to use cryptography to build digital curren
cies. These early digital currency projects issued digital money, usually backed by a
national currency or precious metal such as gold.
While these earlier digital currencies worked, they were centralized and as a result they
were easy to attack by governments and hackers. Early digital currencies used a central
clearinghouse to settle all transactions at regular intervals, just like a traditional banking
system. Unfortunately, in most cases these nascent digital currencies were targeted by
worried governments and eventually litigated out of existence. Some failed in spectac
ular crashes when the parent company liquidated abruptly. To be robust against inter
vention by antagonists, whether legitimate governments or criminal elements, a de-
centralized digital currency was needed to avoid a single point of attack. Bitcoin is such
a system, completely de-centralized by design, and free of any central authority or point
of control that can be attacked or corrupted.
Bitcoin represents the culmination of decades of research in cryptography and dis
tributed systems and includes four key innovations brought together in a unique and
powerful combination. Bitcoin consists of:
History of Bitcoin
Bitcoin was invented in 2008 by Satoshi Nakamoto with the publication of a paper titled
Bitcoin: A Peer-to-Peer Electronic Cash System. Satoshi Nakamoto combined several
prior inventions such as b-money and HashCash to create a completely de-centralized
electronic cash system that does not rely on a central authority for currency issuance or
settlement and validation of transactions. The key innovation was to use a distributed
computation system (called a Proof-Of-Work algorithm) to conduct a global elec
tion every 10 minutes, allowing the de-centralized network to arrive at consensus about
History of Bitcoin | 3
the state of transactions. This elegantly solves the issue of double-spend where a single
currency unit can be spent twice. Previously, the double-spend problem was a weakness
of digital currency and was addressed by clearing all transactions through a central
clearinghouse.
The bitcoin network started in 2009, based on a reference implementation published
by Nakamoto and since revised by many other programmers. The distributed compu
tation that provides security and resilience for bitcoin has increased exponentially and
now exceeds that combined processing capacity of the worlds top super-computers.
Bitcoins total market value is estimated at between 5 and 10 billion US dollars, de
pending on the dollar/bitcoin exchange rate. The largest transaction processed so far
by the network was $150 million US dollars, transmitted instantly and processed
without any fees.
Satoshi Nakamoto withdrew from the public in April of 2011, leaving the responsibility
of developing the code and network to a thriving group of volunteers. The name Satoshi
Nakamoto is an alias and the identity of the person or people behind this invention is
currently unknown. However, neither Satoshi Nakamoto nor anyone else exerts control
over the bitcoin system, which operates based on fully transparent mathematical prin
ciples. The invention itself is groundbreaking and has already spawned new science in
the fields of distributed computing, economics and econometrics.
4 | Chapter 1: Introduction
North American Low Value Retail
Alice lives in Northern Californias Bay Area. She has heard about bitcoin from her
techie friends and wants to start using it. We will follow her story as she learns about
bitcoin, acquires some and then spends some of her bitcoin to buy a cup of coffee
at Bobs Cafe in Palo Alto. This story will introduce us to the software, the exchanges
and basic transactions from the perspective of a retail consumer.
North American High Value Retail
Carol is an art gallery owner in San Francisco. She sells expensive paintings for
bitcoin. This story will introduce the risks of a 51% consensus attack for retailers
of high-value items.
Offshore Contract Services
Bob, the cafe owner in Palo Alto is building a new website. He has contracted with
an Indian web developer, Gopesh, who lives in Bangalore, India. Gopesh has agreed
to be paid in bitcoin. This story will examine the use of bitcoin for outsourcing,
contract services and international wire transfers.
Charitable Donations
Eugenia is the director of a childrens charity in the Philippines. Recently she has
discovered bitcoin and wants to use it to reach a whole new group of foreign and
domestic donors to fundraise for her charity. Shes also investigating ways to use
bitcoin to distribute funds quickly to areas of need. This story will show the use of
bitcoin for global fundraising across currencies and borders and the use of an open
ledger for transparency in charitable organizations.
Import/Export
Mohammed is an electronics importer in Dubai. Hes trying to use bitcoin to buy
electronics from the USA and China for import into the U.A.E. to accelerate the
process of payments for imports. This story will show how bitcoin can be used for
large business-to-business international payments tied to physical goods.
Mining for Bitcoin
Jing is a computer engineering student in Shanghai. He has built a mining rig to
mine for bitcoins, using his engineering skills to supplement his income. This story
will examine the industrial base of bitcoin, the specialized equipment used to
secure the bitcoin network and issue new currency.
Each of the stories above is based on real people and real industries that are currently
using bitcoin to create new markets, new industries and innovative solutions to global
economic issues.
Mobile Bitcoin
Mobile clients for smartphones, such as those based on the Android system, can either
operate as full clients, light clients or web clients. Some mobile clients are synchronized
with a web or desktop client, providing a multi-platform wallet across multiple devices
but with a common source of funds.
The choice of bitcoin client depends on how much control the user wants over funds.
A full client will offer the highest level of control and independence for the user, but in
turn puts the burden of backups and security on the user. On the other end of the range
of choices, a web client is the easiest to set up and use, but the tradeoff with a web client
is that counterparty risk is introduced because security and control is shared by the user
and the owner of the web service. If a web-wallet service is compromised, as many have
6 | Chapter 1: Introduction
been, the users can lose all their funds. Conversely, if a user has a full client without
adequate backups, they may lose their funds through a computer mishap.
For the purposes of this book, we will be demonstrating the use of a variety of bitcoin
clients, from the reference implementation (the Satoshi client) to web-wallets. Some of
the examples will require the use of the reference client which exposes APIs to the wallet,
network and transaction services. If you are planning to explore the programmatic
interfaces into the bitcoin system, you will need the reference client.
Quick Start
Alice, who we introduced in Bitcoin Uses, Users and Their Stories on page 4, is not a
technical user and only recently heard about bitcoin from a friend. She starts her journey
by visiting the official website bitcoin.org, where she finds a broad selection of bitcoin
clients. Following the advice on the bitcoin.org site, she chooses the lightweight bitcoin
client Multibit.
Alice follows a link from the bitcoin.org site to download and install Multibit on her
desktop. Multibit is available for Windows, Mac OS and Linux desktops.
Once Alice has downloaded and installed the Multibit application, she runs it and is
greeted by a welcome screen:
Getting Started | 7
Figure 1-1. The Multibit Bitcoin Client - Welcome Screen
Multibit automatically creates a wallet and a new bitcoin address for Alice, which Alice
can see by clicking on the Request tab:
Figure 1-2. Alices new bitcoin address, in the Request tab of the Multibit client
The most important part of this screen is Alices bitcoin address. Like an email address,
Alice can share this address and anyone can use it to send money directly to her new
wallet. On the screen it appears as a long string of letters and numbers:
8 | Chapter 1: Introduction
1Cdid9KFAaatwczBwBttQcwXYCpvK8h7FK. Next to the wallets bitcoin address, there is a
QR code, a form of barcode that contains the same information in a format that can be
easily scanned by a smartphones camera. The QR code is the black and white square
on the right side of the window. Alice can copy the bitcoin address or the QR code onto
her clipboard by clicking on the copy button adjacent to each of them. Clicking on the
QR code itself will magnify it, so that it can be easily scanned by a smartphone camera.
Alice can also print the QR code as a way to easily give her address to others without
them having to type the long string of letters and numbers.
Getting Started | 9
bitcoin exchange, you can then buy or sell bitcoins quickly just as you could with foreign
currency with a brokerage account.
A more complete list can be found at http://bitcoincharts.com/markets/, a site that offers
price quotes and other market data across many dozens of currency exchanges.
There are three other methods for getting bitcoins as a new user:
Find a friend who has bitcoins and buy some from them directly. Many bitcoin
users started this way.
Use a classified service like localbitcoins.com to find a seller in your area to buy
bitcoins for cash in an in-person transaction.
Sell a product or service for bitcoin. If youre a programmer, sell your programming
skills. If you have an online store, see (to come) to sell in bitcoin.
Use a bitcoin ATM in your city. A map of bitcoin ATMs can be found at http://
www.coindesk.com/bitcoin-atm-map/
Alice was introduced to bitcoin by a friend and so she has an easy way of getting her
first bitcoin while she waits for her account on a California currency market to be
verified and activated.
10 | Chapter 1: Introduction
Next, Joe has to figure out the exchange rate so that he can give the correct amount of
bitcoin to Alice. There are hundreds of applications and web sites that can provide the
current market rate, here are some of the most popular:
bitcoincharts.com, a market data listing service that shows the market rate of bitcoin
across many exchanges around the globe, denominated in different local currencies
bitcoinaverage.com, a site that provides a simple view of the volume-weighted-
average for each currency
ZeroBlock, a free Android and iOS application that can display a bitcoin price from
different exchanges
bitcoinwisdom.com, another market data listing service
Figure 1-3. ZeroBlock - A bitcoin market-rate application for Android and iOS
Using one of the applications or websites above, Joe determines the price of bitcoin to
be approximately $100 US dollars per bitcoin. At that rate he should give Alice 0.10
bitcoin, also known as 100 milliBits, in return for the $10 US dollars she gave him.
Once Joe has established a fair exchange price, he opens his mobile wallet application
and selects to send bitcoin. He is presented with a screen requesting two inputs:
Getting Started | 11
Figure 1-4. Bitcoin mobile wallet - Send bitcoin screen
In the input field for the bitcoin address, there is a small icon that looks like a QR code.
This allows Joe to scan the barcode with his smartphone camera so that he doesnt have
to type in Alices bitcoin address (1Cdid9KFAaatwczBwBttQcwXYCpvK8h7FK), which is
quite long and difficult to type. Joe taps on the QR code icon and activates the smart
phone camera, scanning the QR code from Alices printed wallet that she brought with
her. The mobile wallet application fills in the bitcoin address and Joe can check that it
scanned correctly by comparing a few digits from the address with the address printed
by Alice.
Joe then enters the bitcoin value for the transaction, 0.10 bitcoin. He carefully checks
to make sure he has entered the correct amount, as he is about to transmit money and
any mistake could be costly. Finally, he presses Send to transmit the transaction. Joes
mobile bitcoin wallet constructs a transaction that assigns 0.10 bitcoin to the address
provided by Alice, sourcing the funds from Joes wallet and signing the transaction with
Joes private keys. This tells the bitcoin network that Joe has authorized a transfer of
value from one of his addresses to Alices new address. As the transaction is transmitted
via the peer-to-peer protocol, it quickly propagates across the bitcoin network. In less
than a second, most of the well-connected nodes in the network receive the transaction
and see Alices address for the first time.
If Alice has a smartphone or laptop with her, she will also be able to see the transaction.
The bitcoin ledger - a constantly growing file that records every bitcoin transaction that
has ever occurred - is public, meaning that all she has to do is look up her own address
12 | Chapter 1: Introduction
and see if any funds have been sent to it. She can do this quite easily at the blockchain.info
website by entering her address in the search box. The website will show her a page
(https://blockchain.info/address/1Cdid9KFAaatwczBwBttQcwXYCpvK8h7FK) listing
all the transactions to and from that address. If Alice is watching that page, it will update
to show a new transaction transferring 0.10 bitcoin to her balance soon after Joe hits
Send.
Confirmations
At first, Alices address will show the transaction from Joe as Unconfirmed. This means
that the transaction has been propagated to the network but has not yet been included
in the bitcoin transaction ledger, known as the blockchain. To be included, the trans
action must be picked up by a miner and included in a block of transactions. Once a
new block is created, in approximately 10 minutes, the transactions within the block
will be accepted as confirmed by the network and can be spent. The transaction is seen
by all instantly, but it is only trusted by all when it is included in a newly mined block.
Alice is now the proud owner of 0.10 bitcoin which she can spend. In the next chapter
we will look at her first purchase with bitcoin and examine the underlying transaction
and propagation technologies in more detail.
Getting Started | 13
CHAPTER 2
How Bitcoin Works
blockchain.info
blockexplorer.com
insight.bitpay.com
blockr.io
Each of these has a search function that can take an address, transaction hash or block
number and find the equivalent data on the bitcoin network and blockchain. With each
example, we will provide a URL that takes you directly to the relevant entry, so you can
study it in detail.
15
Bitcoin Overview
In the overview diagram below, we see that the bitcoin system consists of users with
wallets containing keys, transactions which are propagated across the network and
miners who produce (through competitive computation) the consensus blockchain, the
authoritative ledger of all transactions. In this chapter, we will trace a single transaction
as it travels across the network and examine the interactions between each part of the
bitcoin system, at a high level. Subsequent chapters will delve into the technology behind
wallets, mining and merchant systems.
The payment request QR code above encodes the following URL, defined in BIP0021.
bitcoin:1GdK9UzpHBzqzX2A9JFP3Di4weBwqgmoQA?\
amount=0.015&\
label=Bob%27s%20Cafe&\
message=Purchase%20at%20Bob%27s%20Cafe
The bitcoin network can transact in fractional values, e.g. from milli-
bitcoins (1/1000th of a bitcoin) down to 1/100,000,000th of a bit
coin, which is known as a Satoshi. Throughout this book well use the
term bitcoins to refer to any quantity of bitcoin currency, from the
smallest unit (1 Satoshi) to the total number (21,000,000) of all bit
coins that will ever be mined.
Bitcoin Transactions
In simple terms, a transaction tells the network that the owner of a number of bitcoins
has authorized the transfer of some of those bitcoins to another owner. The new owner
can now spend these bitcoins by creating another transaction that authorizes transfer
to another owner, and so on, in a chain of ownership.
Transactions are like lines in a double-entry bookkeeping ledger. In simple terms, each
transaction contains one or more inputs, which are debits against a bitcoin account.
On the other side of the transaction, there are one or more outputs, which are credits
added to a bitcoin account. The inputs and outputs (debits and credits) do not neces
sarily add up to the same amount. Instead, outputs add up to slightly less than inputs
and the difference represents an implied transaction fee, a small payment collected by
the miner who includes the transaction in the ledger.
The transaction also contains proof of ownership for each amount of bitcoin (inputs)
whose value is transferred, in the form of a digital signature from the owner, which can
be independently validated by anyone. In bitcoin terms, spending is signing a trans
action which transfers value from a previous transaction over to a new owner identified
by a bitcoin address.
Bitcoin Transactions | 19
Figure 2-4. A chain of transactions, where the output of one transaction is the input of
the next transaction
Alices payment to Bobs Cafe utilizes a previous transaction as its input. In the previous
chapter Alice received bitcoin from her friend Joe in return for cash. That transaction
has a number of bitcoins locked (encumbered) against Alices key. Her new transaction
to Bobs Cafe references the previous transaction as an input and creates new outputs
to pay for the cup of coffee and receive change. The transactions form a chain, where
the inputs from the latest transaction correspond to outputs from previous transactions.
Alices key provides the signature which unlocks those previous transaction outputs,
thereby proving to the bitcoin network that she owns the funds. She attaches the pay
ment for coffee to Bobs address, thereby encumbering that output with the require
ment that Bob produces a signature in order to spend that amount. This represents a
transfer of value between Alice and Bob.
Bitcoin Transactions | 21
Finally, another transaction form that is seen often on the bitcoin ledger is a transaction
that distributes one input to multiple outputs representing multiple recipients. This type
of transaction is sometimes used by commercial entities to distribute funds, such as
when processing payroll payments to multiple employees.
Constructing a Transaction
Alices wallet application contains all the logic for selecting appropriate inputs and out
puts to build a transaction to Alices specification. Alice only needs to specify a desti
nation and an amount and the rest happens in the wallet application without her seeing
the details. Importantly, a wallet application can construct transactions even if it is
completely offline. Like writing a cheque at home and later sending it to the bank in an
envelope, the transaction does not need to be constructed and signed while connected
to the bitcoin network. It only has to be sent to the network eventually for it to be
executed.
"unspent_outputs":[
{
"tx_hash":"186f9f998a5...2836dd734d2804fe65fa35779",
"tx_index":104810202,
"tx_output_n": 0,
"script":"76a9147f9b1a7fb68d60c536c2fd8aeaa53a8f3cc025a888ac",
"value": 10000000,
"value_hex": "00989680",
"confirmations":0
}
]
}
The response above shows that the bitcoin network knows of one unspent output (one
that has not been redeemed yet) under the ownership of Alices address
1Cdid9KFAaatwczBwBttQcwXYCpvK8h7FK. The response includes the reference to the
transaction in which this unspent output is contained (the payment from Joe) and its
value in Satoshis, at 10 million, equivalent to 0.10 bitcoin. With this information, Alices
wallet application can construct a transaction to transfer that value to new owner ad
dresses.
Use the following link to look up the transaction from Joe to Alice:
https://blockchain.info/tx/
7957a35fe64f80d234d76d83a2a8f1a0d8149a41d81de548f0a65a8a999f6f18
Constructing a Transaction | 23
As you can see, Alices wallet contains enough bitcoins in a single unspent output to pay
for the cup of coffee. Had this not been the case, Alices wallet application might have
to rummage through a pile of smaller unspent outputs, like picking coins from a purse
until it could find enough to pay for coffee. In both cases, there might be a need to get
some change back, which we will see in the next section, as the wallet application creates
the transaction outputs (payments).
Use the following link to look up the transaction from Alice to Bobs Cafe:
https://blockchain.info/tx/
0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2
Constructing a Transaction | 25
How it propagates
Alices wallet application can send the new transaction to any of the other bitcoin clients
it is connected to over any Internet connection: wired, WiFi, or mobile. Her bitcoin
wallet does not have to be connected to Bobs bitcoin wallet directly and she does not
have to use the Internet connection offered by the cafe, though both those options are
possible too. Any bitcoin network node (other client) that receives a valid transaction
it has not seen before, will immediately forward it to other nodes to which it is connected.
Thus, the transaction rapidly propagates out across the peer-to-peer network, reaching
a large percentage of the nodes within a few seconds.
Bobs view
If Bobs bitcoin wallet application is directly connected to Alices wallet application, Bobs
wallet application may be the first node to receive the transaction. However, even if
Alices wallet sends the transaction through other nodes, it will reach Bobs wallet within
a few seconds. Bobs wallet will immediately identify Alices transaction as an incoming
payment because it contains outputs redeemable by Bobs keys. Bobs wallet application
can also independently verify that the transaction is well-formed, uses previously-
unspent inputs and contains sufficient transaction fees to be included in the next block.
At this point Bob can assume, with little risk, that the transaction will shortly be included
in a block and confirmed.
Bitcoin Mining
The transaction is now propagated on the bitcoin network. It does not become part of
the shared ledger (the blockchain) until it is verified and included in a block by a process
called mining. See Introduction on page 177 for a detailed explanation.
The bitcoin system of trust is based on computation. Transactions are bundled into
blocks, which require an enormous amount of computation to prove, but only a small
amount of computation to verify as proven. This process is called mining and serves
two purposes in bitcoin:
A good way to describe mining is like a giant competitive game of sudoku that resets
every time someone finds a solution and whose difficulty automatically adjusts so that
it takes approximately 10 minutes to find a solution. Imagine a giant sudoku puzzle,
several thousand rows and columns in size. If I show you a completed puzzle you can
verify it quite quickly. However, if the puzzle has a few squares filled and the rest is
empty, it takes a lot of work to solve! The difficulty of the sudoku can be adjusted by
changing its size (more or fewer rows and columns), but it can still be verified quite
easily even if it is very large. The puzzle used in bitcoin is based on a cryptographic
hash and exhibits similar characteristics: it is asymmetrically hard to solve but easy to
verify, and its difficulty can be adjusted.
In Bitcoin Uses, Users and Their Stories on page 4 we introduced Jing, a computer
engineering student in Shanghai. Jing is participating in the bitcoin network as a miner.
Every 10 minutes or so, Jing joins thousands of other miners in a global race to find a
solution to a block of transactions. Finding such a solution, the so-called Proof-of-
Work, requires quadrillions of hashing operations per second across the entire bitcoin
network. The algorithm for Proof-of-Work involves repeatedly hashing the header of
the block and a random number with the SHA256 cryptographic algorithm until a
solution matching a pre-determined pattern emerges. The first miner to find such a
solution wins the round of competition and publishes that block into the blockchain.
Jing started mining in 2010 using a very fast desktop computer to find a suitable Proof-
of-Work for new blocks. As more miners started joining the bitcoin network, the dif
ficulty of the problem increased rapidly. Soon, Jing and other miners upgraded to more
specialized hardware, such as Graphical Processing Units (GPUs), as used in gaming
desktops or consoles. As this book is written, by 2014, the difficulty is so high that it is
only profitable to mine with Application Specific Integrated Circuits (ASIC), essentially
hundreds of mining algorithms printed in hardware, running in parallel on a single
silicon chip. Jing also joined a mining pool, which much like a lottery-pool allows
several participants to share their efforts and the rewards. Jing now runs two USB-
connected ASIC machines to mine for bitcoin 24 hours a day. He pays his electricity
costs by selling the bitcoin he is able to generate from mining, creating some income
from the profits. His computer runs a copy of bitcoind, the reference bitcoin client, as
a back-end to his specialized mining software.
Bitcoin Mining | 27
Mining transactions in blocks
A transaction transmitted across the network is not verified until it becomes part of the
global distributed ledger, the blockchain. Every ten minutes on average, miners generate
a new block that contains all the transactions since the last block. New transactions are
constantly flowing into the network from user wallets and other applications. As these
are seen by the bitcoin network nodes, they get added to a temporary pool of unverified
transactions maintained by each node. As miners build a new block, they add unverified
transactions from this pool to a new block and then attempt to solve a very hard problem
(aka Proof-of-Work) to prove the validity of that new block. The process of mining is
explained in detail in Introduction on page 177.
Transactions are added to the new block, prioritized by the highest-fee transactions first
and a few other criteria. Each miner starts the process of mining a new block of trans
actions as soon as they receive the previous block from the network, knowing they have
lost that previous round of competition. They immediately create a new block, fill it
with transactions and the fingerprint of the previous block and start calculating the
Proof-of-Work for the new block. Each miner includes a special transaction in their
block, one that pays their own bitcoin address a reward of newly created bitcoins (cur
rently 25 BTC per block). If they find a solution that makes that block valid, they win
this reward because their successful block is added to the global blockchain and the
reward transaction they included becomes spendable. Jing, who participates in a mining
pool, has set up his software to create new blocks that assign the reward to a pool address.
From there, a share of the reward is distributed to Jing and other miners in proportion
to the amount of work they contributed in the last round.
Alices transaction was picked up by the network and included in the pool of unverified
transactions. Since it had sufficient fees, it was included in a new block generated by
Jings mining pool. Approximately 5 minutes after the transaction was first transmitted
by Alices wallet, Jings ASIC miner found a solution for the block and published it as
block #277316, containing 419 other transactions. Jings ASIC miner published the new
block on the bitcoin network, where other miners validated it and started the race to
generate the next block.
You can see the block that includes Alices transaction here: https://blockchain.info/
block-height/277316
A few minutes later, a new block, #277317 is mined by another miner. As this new block
is based on the previous block (#277316) that contained Alices transaction, it added
even more computation on top of that block, thereby strengthening the trust in those
transactions. One block mined on top of the one containing the transaction is called
one confirmation for that transaction. As the blocks pile on top of each other, it be
comes exponentially harder to reverse the transaction, thereby making it more and more
trusted by the network.
Figure 2-10. Alices transaction as part of a transaction chain from Joe to Gopesh
31
Running Bitcoin Core for the first time
If you download an installable package, such as an EXE, DMG or PPA, you can install
it the same way as any application on your operating system. For Windows, run the EXE
and follow the step-by-step instructions. For Mac OS, launch the DMG and drag the
Bitcoin-QT icon into your Applications folder. For Ubuntu, double-click on the PPA in
your File Explorer and it will open the package manager to install the package. Once
you have completed installation you should have a new application Bitcoin-Qt in your
application list. Double-click on the icon to start the bitcoin client.
The first time you run Bitcoin Core it will start downloading the blockchain, a process
that may take several days. Leave it running in the background until it displays
Synchronized and no longer shows Out of sync next to the balance.
When the git cloning operation has completed, you will have a complete local copy of
the source code repository in the directory bitcoin. Change to this directory by typing
cd bitcoin at the prompt:
$ cd bitcoin
By default, the local copy will be synchronized with the most recent code, which may
be an unstable or beta version of bitcoin. Before compiling the code, we want to select
a specific version by checking out a release tag. This will synchronize the local copy with
a specific snapshot of the code repository identified by a keyword tag. Tags are used by
the developers to mark specific releases of the code by version number. First, to find the
available tags, we use the git tag command:
$ git tag
v0.1.5
v0.1.6test1
v0.2.0
v0.2.10
v0.2.11
v0.2.12
v0.8.4rc2
v0.8.5
v0.8.6
v0.8.6rc1
v0.9.0rc1
The list of tags shows all the released versions of bitcoin. By convention, release candi
dates, which are intended for testing, have the suffix rc. Stable releases that can be run
on production systems have no suffix. From the list above, we select the highest version
release, which at this time is v0.9.0rc1. To synchronize the local code with this version,
we use the git checkout command:
$ git checkout v0.9.0rc1
Note: checking out 'v0.9.0rc1'.
The Bitcoin Core build process was changed to use the autogen/
configure/make system starting with version 0.9. Older versions use
a simple Makefile and work slightly differently from the example
below. Follow the instructions for the version you want to compile.
The autogen/configure/make introduced in 0.9 is likely to be the build
system used for all future versions of the code and is the system
demonstrated in the examples below.
$ ./autogen.sh
configure.ac:12: installing `src/build-aux/config.guess'
configure.ac:12: installing `src/build-aux/config.sub'
configure.ac:37: installing `src/build-aux/install-sh'
configure.ac:37: installing `src/build-aux/missing'
src/Makefile.am: installing `src/build-aux/depcomp'
$
The autogen.sh script creates a set of automatic configuration scripts that will inter
rogate your system to discover the correct settings and ensure you have all the necessary
libraries to compile the code. The most important of these is the configure script that
offers a number of different options to customize the build process. Type ./configure
--help to see the various options:
$ ./configure --help
Configuration:
-h, --help display this help and exit
--help=short display options specific to this package
--help=recursive display the short help of all the included packages
-V, --version display version information and exit
[... many more options and variables are displayed below ...]
Optional Features:
--disable-option-checking ignore unrecognized --enable/--with options
--disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
--enable-FEATURE[=ARG] include FEATURE [ARG=yes]
The configure script allows you to enable or disable certain features of bitcoind through
the use of the --enable-FEATURE and --disable-FEATURE flags, where FEATURE is re
placed by the feature name, as listed in the help output above. In this chapter, we will
build the bitcoind client with all the default features. We wont be using the configuration
flags, but you should review them to understand what optional features are part of the
client. Next, we run the configure script to automatically discover all the necessary
libraries and create a customized build script for our system:
$ ./configure
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
If all goes well, the configure command will end by creating the customized build
scripts that will allow us to compile bitcoind. If there are any missing libraries or errors,
the configure command will terminate with an error instead of creating the build
scripts as shown above. If an error occurs, it is most likely a missing or incompatible
library. Review the build documentation again and make sure you install the missing
pre-requisites. Then run configure again and see if that fixes the error. Next, we will
compile the source code, a process that can take up to an hour to complete. During the
compilation process you should see output every few seconds or every few minutes, or
an error if something goes wrong. The compilation process can be resumed at any time
if interrupted. Type make to start compiling:
$ make
Making all in src
make[1]: Entering directory `/home/ubuntu/bitcoin/src'
make all-recursive
make[2]: Entering directory `/home/ubuntu/bitcoin/src'
Making all in .
make[3]: Entering directory `/home/ubuntu/bitcoin/src'
CXX addrman.o
CXX alert.o
CXX rpcserver.o
CXX bloom.o
CXX chainparams.o
CXX test_bitcoin-wallet_tests.o
CXX test_bitcoin-rpc_wallet_tests.o
CXXLD test_bitcoin
make[4]: Leaving directory `/home/ubuntu/bitcoin/src/test'
make[3]: Leaving directory `/home/ubuntu/bitcoin/src/test'
make[2]: Leaving directory `/home/ubuntu/bitcoin/src'
make[1]: Leaving directory `/home/ubuntu/bitcoin/src'
make[1]: Entering directory `/home/ubuntu/bitcoin'
make[1]: Nothing to be done for `all-am'.
make[1]: Leaving directory `/home/ubuntu/bitcoin'
$
If all goes well, bitcoind is now compiled. The final step is to install the bitcoind exe
cutable into the system path using the make command:
$ sudo make install
Making install in src
Making install in .
$ which bitcoin-cli
/usr/local/bin/bitcoin-cli
The default installation of bitcoind puts it in /usr/local/bin. When we first run bit
coind it will remind us to create a configuration file with a strong password for the
JSON-RPC interface. We run it by typing bitcoind into the terminal:
$ bitcoind
Error: To use the "-server" option, you must set a rpcpassword in the configuration file:
/home/ubuntu/.bitcoin/bitcoin.conf
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=2XA4DuKNCbtZXsBQRRNDEwEY2nM6M4H9Tx5dFjoAVVbK
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %s | mail -s "Bitcoin Alert" admin@foo.com
Edit the configuration file in your preferred editor and set the parameters, replacing the
password with a strong password as recommended by bitcoind. Do not use the password
shown below. Create a file inside the .bitcoin directory so that it is named .bitcoin/
bitcoin.conf and enter a username and password:
rpcuser=bitcoinrpc
rpcpassword=2XA4DuKNCbtZXsBQRRNDEwEY2nM6M4H9Tx5dFjoAVVbK
While youre editing this configuration file, you may want to set a few other options,
such as txindex (See Transaction database index and txindex option on page 48). For
a full listing of the available options type bitcoind --help.
Now, run the Bitcoin Core client. The first time you run it, it will rebuild the bitcoin
blockchain by downloading all the blocks. This is a multi-gigabyte file and will take on
average 2 days to download in full. You can shorten the blockchain initialization time
by downloading a partial copy of the blockchain using a bittorrent client from http://
sourceforge.net/projects/bitcoin/files/Bitcoin/blockchain/.
It will take some time, perhaps more than a day, for the bitcoind client
to catch up to the current blockchain height as it downloads blocks
from other bitcoin clients. You can check its current progress using
getinfo to see the number of known blocks.
We can verify the wallet has been encrypted by running getinfo again. This time you
will notice a new entry unlocked_until that is a counter showing how long the wallet
decryption password will be stored in memory, keeping the wallet unlocked. At first
this will be set to zero, meaning the wallet is locked:
$ bitcoin-cli getinfo
{
"version" : 90000,
"unlocked_until" : 0,
"errors" : ""
}
$
To unlock the wallet, we issue the walletpassphrase command that takes two param
eters, the password and a number of seconds until the wallet is locked again automati
cally (a time counter):
$ bitcoin-cli walletpassphrase foo 360
$
Confirm the wallet is unlocked and see the timeout by running getinfo again:
$ bitcoin-cli getinfo
{
"version" : 90000,
"unlocked_until" : 1392580909,
"errors" : ""
}
Now, to restore the backup file, use the importwallet command. If your wallet is locked,
you will need to unlock it first (see walletpassphrase above) in order to import the
backup file:
$ bitcoin-cli importwallet wallet.backup
$
The dumpwallet command can be used to dump the wallet into a text file that is human-
readable:
$ bitcoin-cli dumpwallet wallet.txt
$ more wallet.txt
# Wallet dump created by Bitcoin v0.9.0rc1-beta (2014-01-31 09:30:15 +0100)
# * Created on 2014-02- 8dT20:34:55Z
# * Best block at time of backup was 286234 (0000000000000000f74f0bc9d3c186267bc45c7b91c49a0386538
# mined on 2014-02- 8dT20:24:01Z
The transactions received by the entire wallet can also be displayed using the listtran
sactions command:
$ bitcoin-cli listtransactions
[
{
"account" : "",
"address" : "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL",
"category" : "receive",
"amount" : 0.05000000,
"confirmations" : 0,
"txid" : "9ca8f969bd3ef5ec2a8685660fdbf7a8bd365524c2e1fc66c309acbae2c14ae3",
"time" : 1392660908,
"timereceived" : 1392660908
}
]
We can list all addresses in the entire wallet using the getaddressesbyaccount com
mand:
$ bitcoin-cli getaddressesbyaccount ""
[
"1LQoTPYy1TyERbNV4zZbhEmgyfAipC6eqL",
"17vrg8uwMQUibkvS2ECRX4zpcVJ78iFaZS",
"1FvRHWhHBBZA8cGRRsGiAeqEzUmjJkJQWR",
"1NVJK3JsL41BF1KyxrUyJW5XHjunjfp2jz",
"14MZqqzCxjc99M5ipsQSRfieT7qPZcM7Df",
"1BhrGvtKFjTAhGdPGbrEwP3xvFjkJBuFCa",
"15nem8CX91XtQE8B1Hdv97jE8X44H3DQMT",
"1Q3q6taTsUiv3mMemEuQQJ9sGLEGaSjo81",
"1HoSiTg8sb16oE6SrmazQEwcGEv8obv9ns",
"13fE8BGhBvnoy68yZKuWJ2hheYKovSDjqM",
"1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL",
"1KHUmVfCJteJ21LmRXHSpPoe23rXKifAb2",
"1LqJZz1D9yHxG4cLkdujnqG5jNNGmPeAMD"
]
The transaction form shown above with the command gettransaction is the simplified
form. To retrieve the full transaction code and decode it we will use two commands,
getrawtransaction and decoderawtransaction. First, getrawtransaction takes the
To decode this hex string, we can use the decoderawtransaction command. Copy and
paste the hex as the first parameter of decoderawtransaction to get the full contents
interpreted as a JSON data structure (for formatting reasons the hex string is shortened
in the example below):
$ bitcoin-cli decoderawtransaction 0100000001d717...388ac00000000
{
"txid" : "9ca8f969bd3ef5ec2a8685660fdbf7a8bd365524c2e1fc66c309acbae2c14ae3",
"version" : 1,
"locktime" : 0,
"vin" : [
{
"txid" : "d3c7e022ea80c4808e64dd0a1dba009f3eaee2318a4ece562f8ef815952717d7",
"vout" : 0,
"scriptSig" : {
"asm" : "3045022100a4ebbeec83225dedead659bbde7da3d026c8b8e12e61a2df0dd0\
758e227383b302203301768ef878007e9ef7c304f70ffaf1f2c975b192d34c5b9b2ac1b\
d193dfba201 04793ac8a58ea751f9710e39aad2e296cc14daa44fa59248be58ede65e4\
c4b884ac5b5b6dede05ba84727e34c8fd3ee1d6929d7a44b6e111d41cc79e05dbfe5cea",
"hex" : "483045022100a4ebbeec83225dedead659bbde7da3d026c8b8e12e61a2df0d\
d0758e227383b302203301768ef878007e9ef7c304f70ffaf1f2c975b192d34c5b9b2ac\
1bd193dfba2014104793ac8a58ea751f9710e39aad2e296cc14daa44fa59248be58ede6\
5e4c4b884ac5b5b6dede05ba84727e34c8fd3ee1d6929d7a44b6e111d41cc79e05dbfe5cea"
},
"sequence" : 4294967295
}
],
"vout" : [
{
"value" : 0.05000000,
"n" : 0,
"scriptPubKey" : {
"asm" : "OP_DUP OP_HASH160 07bdb518fa2e6089fd810235cf1100c9c13d1fd2\
OP_EQUALVERIFY OP_CHECKSIG",
"hex" : "76a91407bdb518fa2e6089fd810235cf1100c9c13d1fd288ac",
"reqSigs" : 1,
"type" : "pubkeyhash",
"addresses" : [
"1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL"
]
Above, we see the new information in the entries blockhash, the hash of the block in
which the transaction was included, and blockindex with value 18, indicating that our
transaction was the 18th transaction in that block.
Exploring blocks
Commands: getblock, getblockhash
Now that we know which block our transaction was included in, we can query that
block. We use the getblock command with the block hash as the parameter:
$ bitcoin-cli getblock 000000000000000051d2e759c63a26e247f185ecb7926ed7a6624bc31c2a717b true
{
"hash" : "000000000000000051d2e759c63a26e247f185ecb7926ed7a6624bc31c2a717b",
"confirmations" : 2,
"size" : 248758,
"height" : 286384,
"version" : 2,
"merkleroot" : "9891747e37903016c3b77c7a0ef10acf467c530de52d84735bd55538719f9916",
"tx" : [
"46e130ab3c67d31d2b2c7f8fbc1ca71604a72e6bc504c8a35f777286c6d89bf0",
"2d5625725b66d6c1da88b80b41e8c07dc5179ae2553361c96b14bcf1ce2c3868",
"923392fc41904894f32d7c127059bed27dbb3cfd550d87b9a2dc03824f249c80",
"f983739510a0f75837a82bfd9c96cd72090b15fa3928efb9cce95f6884203214",
"190e1b010d5a53161aa0733b953eb29ef1074070658aaa656f933ded1a177952",
"ee791ec8161440262f6e9144d5702f0057cef7e5767bc043879b7c2ff3ff5277",
"4c45449ff56582664abfadeb1907756d9bc90601d32387d9cfd4f1ef813b46be",
"3b031ed886c6d5220b3e3a28e3261727f3b4f0b29de5f93bc2de3e97938a8a53",
"14b533283751e34a8065952fd1cd2c954e3d37aaa69d4b183ac6483481e5497d",
"57b28365adaff61aaf60462e917a7cc9931904258127685c18f136eeaebd5d35",
"8c0cc19fff6b66980f90af39bee20294bc745baf32cd83199aa83a1f0cd6ca51",
"1b408640d54a1409d66ddaf3915a9dc2e8a6227439e8d91d2f74e704ba1cdae2",
],
"time" : 1392660808,
"nonce" : 3888130470,
"bits" : "19015f53",
"difficulty" : 3129573174.52228737,
"chainwork" : "000000000000000000000000000000000000000000001931d1658fc04879e466",
"previousblockhash" : "0000000000000000177e61d5f6ba6b9450e0dade9f39c257b4d48b4941ac77e7",
"nextblockhash" : "0000000000000001239d2c3bf7f4c68a4ca673e434702a57da8fe0d829a92eb6"
}
The block contains 367 transactions and as you see above, the 18th transaction listed
(9ca8f9) is the txid of the one crediting 50 milliBits to our address. The height entry
tells us this is the 286384th block in the blockchain.
We can also retrieve a block by its block height using the getblockhash command,
which takes the block height as the parameter and returns the block hash for that block:
$ bitcoin-cli getblockhash 0
000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
Above, we retrieve the block hash of the genesis block, the first block mined by Satoshi
Nakamoto, at height zero. Retrieving this block shows:
$ bitcoin-cli getblock 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
{
"hash" : "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
"confirmations" : 286388,
"size" : 285,
"height" : 0,
"version" : 1,
"merkleroot" : "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"tx" : [
"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
],
"time" : 1231006505,
"nonce" : 2083236893,
"bits" : "1d00ffff",
"difficulty" : 1.00000000,
"chainwork" : "0000000000000000000000000000000000000000000000000000000100010001",
"nextblockhash" : "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
}
We see that the transaction 9ca8f9 created an output (with vout index 0) assigned to
the address 1hvzSo for the amount of 50 millibits, which at this point has received 7
confirmations. Transactions use previously created outputs as their inputs by referring
to them by the previous txid and vout index. We will now create a transaction that will
spend the 0th vout of the txid 9ca8f9 as its input and assign it to a new output that
sends value to a new address.
First, lets look at the specific output in more detail. We use the gettxout to get the
details of this unspent output above. Transaction outputs are always referenced by txid
and vout, and these are the parameters we pass to gettxout:
$ bitcoin-cli gettxout 9ca8f969bd3ef5ec2a8685660fdbf7a8bd365524c2e1fc66c309acbae2c14ae3 0
{
"bestblock" : "0000000000000001405ce69bd4ceebcdfdb537749cebe89d371eb37e13899fd9",
"confirmations" : 7,
"value" : 0.05000000,
"scriptPubKey" : {
"asm" : "OP_DUP OP_HASH160 07bdb518fa2e6089fd810235cf1100c9c13d1fd2\
What we see above is the output that assigned 50 millibits to our address 1hvz. To
spend this output we will create a new transaction. First, lets make an address to which
we will send the money:
$ bitcoin-cli getnewaddress
1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb
We will send 25 millibits to the new address 1LnfTn we just created in our wallet. In
our new transaction, we will spend the 50 millibit output and send 25 millibits to this
new address. Because we have to spend the whole output from the previous transaction,
we must also generate some change. We will generate change back to the 1hvz address,
sending the change back to the address from which the value originated. Finally, we will
also have to pay a fee for this transaction. To pay the fee, we will reduce the change
output by 0.5 millibits, and return 24.5 millibits in change. The difference between the
sum of the new outputs (25mBTC + 24.5mBTC = 49.5mBTC) and the input (50mBTC)
will be collected as a transaction fee by the miners.
We use the createrawtransaction to create the transaction described above. As pa
rameters to createrawtransaction we provide the transaction input (the 50 millibit
unspent output from our confirmed transaction) and the two transaction outputs
(money sent to the new address and change sent back to the previous address):
$ bitcoin-cli createrawtransaction \
'[{"txid" : "9ca8f969bd3ef5ec2a8685660fdbf7a8bd365524c2e1fc66c309acbae2c14ae3", "vout" : 0}]' \
'{"1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb": 0.025, \
"1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL": 0.0245}'
0100000001e34ac1e2baac09c366fce1c2245536bda8f7db0f6685862aecf53ebd69f9a89c\
0000000000ffffffff02a0252600000000001976a914d90d36e98f62968d2bc9bbd6810756\
4a156a9bcf88ac50622500000000001976a91407bdb518fa2e6089fd810235cf1100c9c13d\
1fd288ac00000000
The createrawtransaction command produces a raw hex string that encodes the
transaction details we supplied. Lets confirm everything is correct by decoding this raw
string using the decoderawtransaction command:
$ bitcoin-cli decoderawtransaction \
0100000001e34ac1e2baac09c366fce1c2245536bda8f7db0f6685862aecf53ebd69f9a89c\
Now, the inputs used in the transaction contain a scriptSig, which is a digital signature
proving ownership of address 1hvz and removing the encumbrance on the output so
that it can be spent. The signature makes this transaction verifiable by any node in the
bitcoin network.
ae74538baa914f3799081ba78429d5d84f36a0127438e9f721dff584ac17b346
As before, we can also examine this in more detail using the getrawtransaction and
decodetransaction commands. These commands will return the exact same hex string
that we produced and decoded previously just before we sent it on the network.
libbitcoin and sx tools, a C++ multi-threaded full node client and library with
command-line tools (https://libbitcoin.dyne.org/)
bitcoinj, a Java full node client library (https://code.google.com/p/bitcoinj/)
btcd, a Go language full node bitcoin client (https://opensource.conformal.com/
wiki/btcd)
Bits of Proof (BOP), a Java enterprise-class implementation of bitcoin (https://
bitsofproof.com)
picocoin, a C implementation of a light-weight client library for bitcoin (https://
github.com/jgarzik/picocoin)
pybitcointools, a Python bitcoin library (https://github.com/vbuterin/pybitcoin
tools)
pycoin, another Python bitcoin library (https://github.com/richardkiss/pycoin)
Many more libraries exist in a variety of other programming languages and more are
created all the time.
You should now have the sx tools installed. Type sx with no parameters to display the
help text, which lists all the available commands (See Appendix A)
pycoin
The Python library pycoin (http://github.com/richardkiss/pycoin), originally written
and maintained by Richard Kiss, is a Python-based library that supports manipulation
of bitcoin keys and transactions, even supporting the scripting language enough to
properly deal with non-standard transactions.
The pycoin library supports both Python 2 (2.7.x) and Python 3 (after 3.3), and comes
with some handy command-line utilities, ku and tx.
To install:
Installing pycoin 0.42 under Python 3 in an virtual environment (venv).
$ python3 -m venv /tmp/pycoin
$ . /tmp/pycoin/bin/activate
$ pip install pycoin==0.42
Downloading/unpacking pycoin==0.42
Downloading pycoin-0.42.tar.gz (66kB): 66kB downloaded
Running setup.py (path:/tmp/pycoin/build/pycoin/setup.py) egg_info for package pycoin
def get_address(which):
while 1:
print("enter the %s address=> " % which, end='')
address = input()
is_valid = is_address_valid(address)
if is_valid:
return address
print("invalid address, please try again")
src_address = get_address("source")
spendables = spendables_for_address(src_address)
print(spendables)
while 1:
print("enter the WIF for %s=> " % src_address, end='')
wif = input()
is_valid = is_wif_valid(wif)
if is_valid:
break
print("invalid wif, please try again")
key = Key.from_text(wif)
if src_address not in (key.address(use_uncompressed=False), key.address(use_uncompressed=True)):
print("** WIF doesn't correspond to %s" % src_address)
print("The secret exponent is %d" % key.secret_exponent())
dst_address = get_address("destination")
For many examples using the command line utilities ku and tx, see (to come).
btcd
btcd is a full node bitcoin implementation written in Go. It currently properly down
loads, validates, and serves the block chain using the exact rules (including bugs) for
Installing btcd
To install btcd, for Windows, download and run the msi available at https://github.com/
conformal/btcd/releases or run the following command on Linux, assuming you already
have installed the Go language:
$ go get github.com/conformal/btcd/...
To update btcd to the latest version, just run:
$ go get -u -v github.com/conformal/btcd/...
Controlling btcd
btcd has a number of configuration options, which can be viewed by running:
$ btcd --help
btcd comes prepacked with some goodies such as btcctl, a command line utility that
can be used to both control and query btcd via RPC. btcd does not enable its RPC server
by default; you must configure at minimum both an RPC username and password:
[Application Options]
rpcuser=myuser
rpcpass=SomeDecentp4ssw0rd
[Application Options]
rpcuser=myuser
rpcpass=SomeDecentp4ssw0rd
Or if you want to override the configuration files from the command line:
Introduction
Ownership of bitcoin is established through digital keys, bitcoin addresses and digital
signatures. The digital keys are not actually stored in the network, but are instead created
and stored by end-users in a file, or simple database, called a wallet. The digital keys in
a users wallet are completely independent of the bitcoin protocol and can be generated
and managed by the users wallet software without reference to the blockchain or access
to the Internet. Keys enable many of the interesting properties of bitcoin, including de-
centralized trust and control, ownership attestation and the cryptographic-proof secu
rity model.
HNFUzKACoVNLnyx4PlW7hJg3dpko2UlDwttaxaU
Pan4afMmK9ZAtHMKB4PqJgYFe8VDIp0x7OpruTFugxA5hBTE=
Every bitcoin transaction requires a valid signature to be included in the blockchain,
which can only be generated with valid digital keys, therefore anyone with a copy of
those keys has control of the bitcoin in that account. Keys come in pairs consisting of a
private (secret) and public key. Think of the public key as similar to a bank account
number and the private key as similar to the secret PIN number, or signature on a cheque
that provides control over the account. These digital keys are very rarely seen by the
users of bitcoin. For the most part, they are stored inside the wallet file and managed
by the bitcoin wallet software.
In the payment portion of a bitcoin transaction, the recipients public key is represented
by its digital fingerprint, called a bitcoin address, which is used in the same way as the
beneficiary name on a cheque (i.e. Pay to the order of ). In most cases, a bitcoin address
is generated from and corresponds to a public key. However, not all bitcoin addresses
represent public keys; they can also represent other beneficiaries such as scripts, as we
will see later in this chapter. This way, bitcoin addresses abstract the recipient of funds,
making transaction destinations flexible, similar to paper cheques: a single payment
61
instrument that can be used to pay into peoples accounts, company accounts, pay for
bills or pay to cash. The bitcoin address is the only representation of the keys that users
will routinely see, as this is the part they need to share with the world.
In this chapter we will introduce wallets, which contain cryptographic keys. We will
look at how keys are generated, stored and managed. We will review the various en
coding formats used to represent private and public keys, addresses and script addresses.
Finally we will look at special uses of keys: to sign messages, to prove ownership and to
create vanity addresses and paper wallets.
In most wallet implementations, the private and public keys are stor
ed together as a key pair for convenience. However, the public key can
be calculated from the private key, so storing only the private key is
also possible.
Private Keys
A private key is simply a number, picked at random. Ownership and control over the
private key is the root of user control over all funds associated with the corresponding
bitcoin address. The private key is used to create signatures that are required to spend
bitcoins by proving ownership of funds used in a transaction. The private key must
remain secret at all times, as revealing it to a third party is equivalent to giving them
control over the bitcoins secured by that key. The private key must also be backed up
and protected from accidental loss, since if lost it cannot be recovered and the funds
secured by it are forever lost too.
The bitcoin private key is just a number. You can pick your private
keys randomly using just a coin, pencil and paper: Toss a coin 256
times and you have the binary digits of a random private key you can
use in a bitcoin wallet. The public key can be then generated from the
private key.
Introduction | 63
is not predictable or repeatable. Bitcoin software uses the underlying operating systems
random number generators to produce 256 bits of entropy (randomness). Usually, the
OS random number generator is initialized by a human source of randomness, which
is why you may be asked to wiggle your mouse around for a few seconds. For the truly
paranoid, nothing beats dice, pencil and paper.
More accurately, the private key can be any number between 1 and n - 1, where n is a
constant (n = 1.158 * 1077, slightly less than 2256) defined as the order of the elliptic curve
used in bitcoin (see Elliptic Curve Cryptography Explained on page 65). To create such
a key, we randomly pick a 256-bit number and check that it is less than n - 1. In
programming terms, this is usually achieved by feeding a larger string of random bits,
collected from a cryptographically-secure source of randomness, into the SHA-256 hash
algorithm which will conveniently produce a 256-bit number. If the result is less than
n - 1, we have a suitable private key. Otherwise, we simply try again with another
random number.
Below is a randomly generated private key shown in hexadecimal format (256 binary
digits shown as 64 hexadecimal digits, each 4 bits):
Randomly generated private key (k).
1E99423A4ED27608A15A2616A2B0E9E52CED330AC530EDCC32C8FFC6A526AEDD
To generate a new key with the Bitcoin Core Client (see Chapter 3), use the getnewad
dress command. For security reasons it displays the public key only, not the private
key. To ask bitcoind to expose the private key, use the dumpprivkey command. The
dumpprivkey shows the private key in a base-58 checksum encoded format called the
Wallet Import Format (WIF), which we will examine in more detail in Private Key
The dumpprivkey command opens the wallet and extracts the private key that was gen
erated by the getnewaddress command. It is not otherwise possible for bitcoind to know
the private key from the public key, unless they are both stored in the wallet.
You can also use the command-line sx tools (see Libbitcoin and sx tools on page
56) to generate and display private keys:
Public Keys
The public key is calculated from the private key using elliptic curve multiplication,
which is irreversible: K = k * G where k is the private key, G is a constant point called
the Generator Point and K is the resulting public key. The reverse operation, known as
finding the discrete logarithm" calculating k if you know K is as difficult as trying
all possible values of k, i.e., a brute-force search. Before we demonstrate how to generate
a public key from a private key, lets look at Elliptic Curve Cryptography in a bit more
detail.
Introduction | 65
Figure 4-2. An Elliptic Curve
Bitcoin uses a specific elliptic curve and set of mathematical constants, as defined in a
standard called secp256k1, established by the National Institute of Standards and Tech
nology (NIST). The secp256k1 curve is defined by the following function, which pro
duces an elliptic curve:
y 2 = ( x 3 + 7)over( p )
or
y 2 mod p = ( x 3 + 7) mod p
The mod p (modulo prime number p) indicates that this curve is over a finite field of
prime order p, also written as p , where p = 2256 - 232 - 29 - 28 - 27 - 26 - 24 - 1, a very large
prime number.
Because this curve is defined over a finite field of prime order instead of over the real
numbers it looks like a pattern of dots scattered in two dimensions, which makes it
difficult to visualize. However, the math is identical as that of an elliptic curve over the
real numbers shown above. As an example, below is the same elliptic curve over a much
smaller finite field of prime order 17, showing a pattern of dots on a grid. The secp256k1
bitcoin elliptic curve can be thought of as a much more complex pattern of dots on a
unfathomably large grid.
So for example, below is a point P with coordinates (x,y) that is a point on the secp256k1
curve. You can check this yourself using Python:
P = (55066263022277343669578718895168534326250603453777594175500187360389116729240,\
32670510020758816978083085130507043184471273380659243275938904335757337482424)
Python 3.4.0 (default, Mar 30 2014, 19:23:13)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> p = 115792089237316195423570985008687907853269984665640564039457584007908834671663
>>> x = 55066263022277343669578718895168534326250603453777594175500187360389116729240
>>> y = 32670510020758816978083085130507043184471273380659243275938904335757337482424
>>> (x ** 3 + 7 - y**2) % p
0
Introduction | 67
In elliptic curve math, there is a point called the point at infinity, which roughly cor
responds to the role of 0 in addition. On computers, its sometimes represented by x =
y = 0 (which doesnt satisfy the elliptic curve equation but its an easy separate case
that can be checked).
There is also an operator +, called addition which has some properties similar to the
traditional addition of real numbers that grade school children learn. Given two points
P1 and P2 on the elliptic curve, there is a third point P3 = P1 + P2, also on the elliptic
curve.
Geometrically, this third point P3 is calculated by drawing a line between P1 and P2. This
line will intersect the elliptic curve in exactly one additional place. Call this point P3' =
(x, y). Then reflect in the X axis to get P3 = (x, -y).
There are a couple of special cases which explain the need for the point at infinity.
If P1 and P2 are the same point, the line between P1 and P2 should extend to be the
tangent on the curve at this point P1. This tangent will intersect the curve in exactly one
new point. You can use techniques from calculus to determine the slope of the tangent
line. These techniques curiously work even though we are restricting our interest to
points on the curve with two integer coordinates!
In some cases (i.e., if P1 and P2 have the same x values but different y values), the tangent
line will be exactly vertical, in which case P3 = point at infinity.
If P1 is the point at infinity, then the sum P1 + P2 = P2. Similary, if P2 is the point at
infinity, then P1 + P2 = P1. This shows how the point at infinity plays the roll of 0.
It turns out that + is associative, which means that (A+B)+C = A+(B+C). That means we
can write A+B+C without parentheses without any ambiguity.
Now that we have defined addition, we can define multiplication in the standard way
that extends addition. For a point P on the elliptic curve, if k is a whole number, then
kP = P + P + P + + P (k times). Note that k is sometimes confusingly called an
exponent in this case.
K = k *G
A private key can be converted into a public key, but a public key
cannot be converted back into a private key because the math only
works one way.
Implementing the elliptic curve multiplication above, we take the private key generated
previously and multiply it by G:
Multiply the private key k with the generator point G to find the public key K.
K = 1E99423A4ED27608A15A2616A2B0E9E52CED330AC530EDCC32C8FFC6A526AEDD * G
Introduction | 69
Figure 4-4. Elliptic Curve Cryptography: Visualizing the multiplication of a point G by
an integer k on an elliptic curve
Bitcoin Addresses
A bitcoin address is a string of digits and characters that can be shared with anyone who
wants to send you money. Addresses produced from public keys consist of a string of
numbers and letters, beginning with the digit 1. Heres an example of a bitcoin address:
A = RIPEMD160(SHA256(K ))
Bitcoin Addresses | 71
or a script hash. In the next section we will examine the mechanics of Base58Check
encoding and decoding, and the resulting representations.
Figure 4-5. Public Key to Bitcoin Address: Conversion of a public key into a bitcoin ad
dress
Base58Check Encoding
To add extra security against typos or transcription errors, Base58Check is a Base-58
encoding format, frequently used in bitcoin, which has a built-in error-checking code.
The checksum is an additional four bytes added to the end of the data that is being
encoded. The checksum is derived from the hash of the encoded data and can therefore
be used to detect and prevent transcription and typing errors. When presented with a
Base58Check code, the decoding software will calculate the checksum of the data and
compare it to the checksum included in the code. If the two do not match, that indicates
that an error has been introduced and the Base58Check data is invalid. For example,
this prevents a mistyped bitcoin address from being accepted by the wallet software as
a valid destination, an error which would otherwise result in loss of funds.
To convert data (a number) into a Base58Check format, we first add a prefix to the data,
called the version byte, which serves to easily identify the type of data that is encoded.
For example, in the case of a bitcoin address the prefix is zero (0x00 in hex), whereas
the prefix used when encoding a private key is 128 (0x80 in hex). A list of common
version prefixes is shown below in Table 4-1.
Next compute the double-SHA checksum, meaning we apply the SHA256 hash-
algorithm twice on the previous result (prefix and data):
checksum = SHA256(SHA256(prefix+data))
From the resulting 32-byte hash (hash-of-a-hash), we take only the first four bytes.
These four bytes serve as the error-checking code, or checksum. The checksum is con
catenated (appended) to the end.
Bitcoin Addresses | 73
The result of the above is now a prefix, the data and a checksum. This result is encoded
using the base-58 alphabet described in the section above.
Figure 4-6. Base58Check Encoding: A base-58, versioned and checksummed format for
unambiguously encoding bitcoin data
In bitcoin, most of the data presented to the user is Base58Check encoded to make it
compact, easy to read and easy to detect errors. The version prefix in Base58Check
encoding is used to create easily distinguishable formats, which when encoded in
Base-58 contain specific characters at the beginning of the Base58Check encoded pay
load, making it easy for humans to identify the type of data that is encoded and how to
use it. This is what differentiates, for example, a Base58Check encoded bitcoin address
that starts with a 1 from a Base58Check encoded private key WIF format that starts
with a 5. Some example version prefixes and the resulting Base-58 characters are
shown below:
int main()
{
// Private secret key.
bc::ec_secret secret = bc::decode_hash(
"038109007313a5807b2eccc082c8c3fbb988a973cacf1a7df9ce725c31b14776");
// Get public key.
bc::ec_point public_key = bc::secret_to_public_key(secret);
std::cout << "Public key: " << bc::encode_hex(public_key) << std::endl;
bc::data_chunk unencoded_address;
// Reserve 25 bytes
// [ version:1 ]
// [ hash:20 ]
// [ checksum:4 ]
unencoded_address.reserve(25);
// Version byte, 0 is normal BTC address (P2PKH).
unencoded_address.push_back(0);
Bitcoin Addresses | 75
// Hash data
bc::extend_data(unencoded_address, hash);
// Checksum is computed by hashing data, and adding 4 bytes from hash.
bc::append_checksum(unencoded_address);
// Finally we must encode the result in Bitcoin's base58 encoding
assert(unencoded_address.size() == 25);
const std::string address = bc::encode_base58(unencoded_address);
The code uses a pre-defined private key, so that it produces the same bitcoin address
every time it is run:
Example 4-2. Compiling and running the addr code
# Compile the addr.cpp code
$ g++ -o addr addr.cpp $(pkg-config --cflags --libs libbitcoin)
# Run the addr executable
$ ./addr
Public key: 0202a406624211f2abbdc68da3df929f938c3399dd79fac1b51b0e4ad1d26a47aa
Address: 1PRTTaJesdNovgne6Ehcdu1fpEdX7913CK
Key Formats
Private Key Formats
The private key can be represented in a number of different formats, all of which cor
respond to the same 256-bit number. These formats include:
Table 4-2. Private Key Representations (Encoding Formats)
Type Prefix Description
Hex None 64 hexadecimal digits
WIF 5 Base58Check encoding: Base-58 with version prefix of 128 and 32-bit checksum
WIF-compressed K or L As above, with added suffix 0x01 before encoding
Bitcoin Addresses | 77
Heres the public key generated by the private key we created above, shown as the co
ordinates x and y.
Public Key K defined as a point K = (x,y).
x = F028892BAD...DC341A
y = 07CF33DA18...505BDB
Heres the same public key shown as a 520-bit number (130 hex digits) with the prefix
04 followed by x and then y coordinates, as 04 x y:
Uncompressed Public Key K shown in hex (130 hex digits) as 04xy.
K = 04F028892BAD...505BDB
Heres the same public key generated previously, shown as a compressed public key
stored in 264-bits (66 hex digits) with the prefix 03 indicating the y coordinate is odd:
Compressed Public Key K shown in hex (66 hex digits) as K = {02 or 03} x.
K = 03F028892BAD...DC341A
The compressed public key, above, corresponds to the same private key, meaning that
it is generated from the same private key. However it looks different from the uncom
pressed public key. More importantly, if we convert this compressed public key to a
bitcoin address using the double-hash function (RIPEMD160(SHA256(K))) it will pro
Bitcoin Addresses | 79
duce a different bitcoin address. This can be confusing, because it means that a single
private key can produce a public key expressed in two different formats (compressed
and uncompressed) which produce two different bitcoin addresses. However, the pri
vate key is identical for both bitcoin addresses.
Compressed public keys are gradually becoming the default across bitcoin clients, which
is having a significant impact on reducing the size of transactions and therefore the
blockchain. However, not all clients support compressed public keys yet. Newer clients
that support compressed public keys have to account for transactions from older clients
which do not support compressed public keys. This is especially important when a wallet
application is importing private keys from another bitcoin wallet application, because
the new wallet needs to scan the blockchain to find transactions corresponding to these
imported keys. Which bitcoin addresses should the bitcoin wallet scan for? The bitcoin
addresses produced by uncompressed public keys, or the bitcoin addresses produced
by compressed public keys? Both are valid bitcoin addresses, and can be signed for by
the private key, but they are different addresses!
To resolve this issue, when private keys are exported from a wallet, the Wallet Import
Format that is used to represent them is implemented differently in newer bitcoin wal
lets, to indicate that these private keys have been used to produce compressed public
keys and therefore compressed bitcoin addresses. This allows the importing wallet to
distinguish between private keys originating from older or newer wallets and search the
blockchain for transactions with bitcoin addresses corresponding to the uncompressed,
or the compressed public keys respectively. Lets look at how this works in more detail,
in the next section.
# Multiply the EC generator point G with the private key to get a public key point
public_key = bitcoin.base10_multiply(bitcoin.G, decoded_private_key)
print "Public Key (x,y) coordinates is:", public_key
Heres another example, using the Python ECDSA library for the Elliptic Curve math
and without using any specialized bitcoin libraries:
Example 4-5. A script demonstrating Elliptic Curve math used for bitcoin keys
import ecdsa
import random
from ecdsa.util import string_to_number, number_to_string
# secp256k1, http://www.oid-info.com/get/1.3.132.0.10
_p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
_r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
_b = 0x0000000000000000000000000000000000000000000000000000000000000007L
_a = 0x0000000000000000000000000000000000000000000000000000000000000000L
_Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
_Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
curve_secp256k1 = ecdsa.ellipticcurve.CurveFp(_p, _a, _b)
generator_secp256k1 = ecdsa.ellipticcurve.Point(curve_secp256k1, _Gx, _Gy, _r)
oid_secp256k1 = (1, 3, 132, 0, 10)
SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1)
ec_order = _r
curve = curve_secp256k1
generator = generator_secp256k1
def random_secret():
random_char = lambda: chr(random.randint(0, 255))
convert_to_int = lambda array: int("".join(array).encode("hex"), 16)
byte_array = [random_char() for i in range(32)]
return convert_to_int(byte_array)
def get_point_pubkey(point):
if point.y() & 1:
key = '03' + '%064x' % point.x()
else:
key = '02' + '%064x' % point.x()
return key.decode('hex')
Wallets
Wallets are containers for private keys, usually implemented as structured files or simple
databases. Another method for making keys is deterministic key generation. Here you
derive each new private key, using a one-way hash function from a previous private key,
linking them in a sequence. As long as you can re-create that sequence, you only need
the first key (known as a seed or master key) to generate them all. In this section we will
examine the different methods of key generation and the wallet structures that are built
around them.
Wallets | 85
Figure 4-8. Type-0 Non-Deterministic (Random) Wallet: A Collection of Randomly
Generated Keys
The mnemonic code represents 128 to 256 bits which are used to derive a longer (512
bit) seed through the use of the key-stretching function PBKDF2. The resulting seed is
used to create a deterministic wallet and all of its derived keys.
Here are some examples of mnemonic codes and the seeds they produce:
Table 4-6. 128-bit entropy mnemonic code and resulting seed
entropy input (128 0c1e24e5917779d297e14d45f14e1a1a
bits)
mnemonic (12 army van defense carry jealous true garbage claim echo media make crunch
words)
seed (512 bits) 3338a6d2ee71c7f28eb5b882159634cd46a898463e9d2d0980f8e80dfbba5b0fa0291e5fb88\
8a599b44b93187be6ee3ab5fd3ead7dd646341b2cdb8d08d13bf7
Wallets | 87
Table 4-7. 256-bit entropy mnemonic code and resulting seed
entropy input (256 2041546864449caff939d32d574753fe684d3c947c3346713dd8423e74abcf8c
bits)
mnemonic (24 cake apple borrow silk endorse fitness top denial coil riot stay wolf luggage oxygen faint major edit measure
words) invite love trap field dilemma oblige
seed (512 bits) 3972e432e99040f75ebe13a660110c3e29d131a2c808c7ee5f1631d0a977fcf473bee22\
fce540af281bf7cdeade0dd2c1c795bd02f1e4049e205a0158906c343
Figure 4-9. Type-2 Hierarchical Deterministic Wallet: A Tree of Keys Generated from a
Seed
HD wallets offer two major advantages over random (non-deterministic) keys. First,
the tree structure can be used to express additional organizational meaning, such as
when a specific branch of sub-keys is used to receive incoming payments and a different
branch is used to receive change from outgoing payments. Branches of keys can also be
used in a corporate setting, allocating different branches to departments, subsidiaries,
specific functions or accounting categories.
The second advantage of HD wallets is that users can create a sequence of public keys
without having access to the corresponding private keys. This allows HD wallets to be
used on an insecure server or in a receive-only capacity, issuing a different public key
for each transaction. The public keys do not need to be pre-loaded or derived in advance,
yet the server doesnt have the private keys that can spend the funds.
Wallets | 89
Figure 4-10. Creating master keys and chain code from a root seed
The root seed is input into the HMAC-SHA512 algorithm and the resulting hash is used
to create a master private key (m) and a master chain code. The master private key (m)
then generates a corresponding master public key (M), using the normal elliptic curve
multiplication process m * G that we saw previously in this chapter. The chain code is
used to introduce entropy in the function that creates child keys from parent keys, as
we will see in the next section.
The chain code is used to introduce seemingly random data to the process, so that the
index is not sufficient to derive other child keys. Thus, having a child key does not make
it possible to find its siblings, unless you also have the chain code. The initial chain code
seed (at the root of the tree) is made from random data, while subsequent chain codes
are derived from each parent chain code.
These three items are combined and hashed to generate children keys, as follows:
The parent public key, chain code and the index number are combined and hashed with
the HMAC-SHA512 algorithm to produce a 512 bit hash. The resulting hash is split
into two halfs. The right-half 256 bits of the hash output become the chain code for the
Figure 4-11. Extending a parent private key to create a child private key
Changing the index allows us to extend the parent and create the other children in the
sequence, e.g. Child 0, Child 1, Child 2 etc. Each parent key can have 2 billion children
keys.
Repeating the process one level down the tree, each child can in turn become a parent
and create its own children, in an infinite number of generations.
Wallets | 91
A child private key, the corresponding public key and the bitcoin
address are all indistinguishable from keys and addresses created
randomly. The fact that they are part of a sequence is not visible,
outside of the HD wallet function that created them. Once created,
they operate exactly as normal keys.
Extended keys
As we saw above, the key derivation function can be used to create children at any level
of the tree, based on the three inputs: a key, a chain code and the index of the desired
child. The two essential ingredients are the key and chain code and combined these are
called an extended key. The term extended key could also be thought of as extensible
key because such a key can be used to derive children.
Extended keys are stored and represented simply as the concatenation of the 256 bit key
and 256 bit chain code into a 512 bit sequence. There are two types of extended keys:
An extended private key is the combination of a private key and chain code and can be
used to derive child private keys (and from them, child public keys). An extended public
key is a public key and chain code, which can be used to create child public keys, as
described in Generating a public key on page 68.
Think of an extended key as the root of a branch in the tree structure of the HD wallet.
With the root of the branch, you can derive the rest of the branch. The extended private
key can create a complete branch, whereas the extended public key can only create a
branch of public keys.
Extended keys are encoded using Base58Check, to easily export and import between
different BIP0032 compatible wallets. The Base58Check coding for extended keys uses
a special version number that results in the prefix xprv and xpub when encoded in
base 58 characters, to make them easily recognizable. Since the extended key is 512 or
513 bits, it is also much longer than other Base58Check encoded strings we have seen
previously.
Heres an example of an extended private key, encoded in Base58Check:
xprv9tyUQV64JT5qs3RSTJkXCWKMyUgoQp7F3hA1xzG6ZGu6u6Q9VMNjGr67Lctvy5P8oyaYAL9CAWrUE9i6GoNMKUga5biW6H
Heres the corresponding extended public key, also encoded in Base58Check:
xpub67xpozcx8pe95XVuZLHXZeG6XWXHpGq6Qv5cmNfi7cS5mtjJ2tgypeQbBs2UAR6KECeeMVKZBPLrtJunSDMstweyLXhRgP
Wallets | 93
Figure 4-12. Extending a parent public key to create a child public key
When the hardened private derivation function is used, the resulting child private key
and chain code are completely different from what would result from the normal der
ivation function. The resulting branch of keys can be used to produce extended public
keys which are not vulnerable, since the chain code they contain cannot be exploited to
reveal any private keys. Hardened derivation is therefore used to create a gap in the
tree above the level where extended public keys are used.
In simple terms, if you want to use the convenience of an extended public key to derive
branches of public keys, without exposing yourself to the risk of a leaked chain code,
you should derive it from a hardened parent, rather than a normal parent. As a best
practice, the level-1 children of the master keys are always derived through the hardened
derivation, to prevent compromise of the master keys.
Wallets | 95
key is therefore displayed as 0, whereas the first hardened child (index 0x80000000) is
displayed as 0. In sequence then, the second hardened key would have index 0x80000001
and would be displayed as 1', and so on. When you see an HD wallet index i', that means
231+i.
Wallets | 97
$ cat m | sx hd-priv 0 | sx hd-to-wif # show the private key of m/0 as a WIF
L1pbvV86crAGoDzqmgY85xURkz3c435Z9nirMt52UbnGjYMzKBUN
$ cat m | sx hd-pub 0 | sx hd-to-address # show the bitcoin address of M/0
1CHCnCjgMNb6digimckNQ6TBVcTWBAmPHK
$ cat m | sx hd-priv 0 | sx hd-priv 12 --hard | sx hd-priv 4 # generate m/0/12'/4
xprv9yL8ndfdPVeDWJenF18oiHguRUj8jHmVrqqD97YQHeTcR3LCeh53q5PXPkLsy2kRaqgwoS6YZBLatRZR\
yUeAkRPe1kLR1P6Mn7jUrXFquUt
Vanity Addresses
Vanity addresses are valid bitcoin addresses that contain human-readable messages, for
example 1LoveBPzzD72PUXLzCkYAtGFYmK5vYNR33 is a valid address that contains
the letters forming the word Love as the first four Base-58 letters. Vanity addresses
require generating and testing billions of candidate private keys, until one derives a
bitcoin address with the desired pattern. While there are some optimizations in the
vanity generation algorithm, the process essentially involves picking a private key at
random, deriving the public key, deriving the bitcoin address and checking to see if it
matches the desired vanity pattern, repeating billions of times until a match is found.
Once a vanity address matching the desired pattern is found, the private key from which
it was derived can be used by the owner to spend bitcoins in exactly the same way as
any other address. Vanity addresses are no less or more secure than any other address.
They depend on the same Elliptic Curve Cryptography (ECC) and Secure Hash Algo
rithm (SHA) as any other address. You can no easier find the private key of an address
starting with a vanity pattern than you can any other address.
In our first chapter, we introduced Eugenia, a childrens charity director operating in
the Philippines. Lets say that Eugenia is organizing a bitcoin fundraising drive and wants
Lets look at the pattern 1Kids as a number and see how frequently we might find this
pattern in a bitcoin address. An average desktop computer PC, without any specialized
hardware, can search approximately 100,000 keys per second.
Table 4-12. The frequency of a vanity pattern (1KidsCharity) and average time-to-find
on a desktop PC
Length Pattern Frequency Average Search Time
1 1K 1 in 58 keys < 1 milliseconds
2 1Ki 1 in 3,364 50 milliseconds
3 1Kid 1 in 195,000 < 2 seconds
4 1Kids 1 in 11 million 1 minute
5 1KidsC 1 in 656 million 1 hour
6 1KidsCh 1 in 38 billion 2 days
7 1KidsCha 1 in 2.2 trillion 3-4 months
8 1KidsChar 1 in 128 trillion 13-18 years
9 1KidsChari 1 in 7 quadrillion 800 years
10 1KidsCharit 1 in 400 quadrillion 46,000 years
11 1KidsCharity 1 in 23 quintillion 2.5 million years
As you can see, Eugenia wont be creating the vanity address 1KidsCharity any time
soon, even if she had access to several thousand computers. Each additional character
increases the difficulty by a factor of 58. Patterns with more than seven characters are
usually found by specialized hardware, such as custom-built desktops with multiple
Graphical Processing Units (GPUs). These are often re-purposed bitcoin mining rigs
that are no longer profitable for bitcoin mining but can be used effectively to find vanity
int main()
{
std::random_device random;
std::default_random_engine engine(random());
// Loop continuously...
while (true)
{
// Generate a random secret.
bc::ec_secret secret = random_secret(engine);
// Get the address.
std::string address = bitcoin_address(secret);
// Does it match our search string? (1kid)
if (match_found(address))
{
// Success!
std::cout << "Found vanity address! " << address << std::endl;
std::cout << "Secret: " << bc::encode_hex(secret) << std::endl;
return 0;
}
}
// Should never reach here!
The example code must be compiled using a C++ compiler and linked against the lib
bitcoin library (which must be first installed on that system). To run the example, run
the vanity-minder executable with no parameters and it will attempt to find a vanity
address starting with 1kid:
Example 4-8. Compiling and running the vanity-miner example
$ # Compile the code with g++
$ g++ -o vanity-miner vanity-miner.cpp $(pkg-config --cflags --libs libbitcoin)
$ # Run the example
$ ./vanity-miner
Found vanity address! 1KiDzkG4MxmovZryZRj8tK81oQRhbZ46YT
Secret: 57cc268a05f83a23ac9d930bc8565bac4e277055f4794cbd1a39e5e71c038f3f
$ # Run it again for a different result
$ ./vanity-miner
real 0m8.868s
user 0m8.828s
sys 0m0.035s
The example code will take a few seconds to find a match for the three-character pattern
kid, as we can see when we use the time Unix command to measure the execution
time. Change the search pattern in the source code and see how much longer it takes
for four- or five-character patterns!
Paper Wallets
Paper wallets are bitcoin private keys printed on paper. Often the paper wallet also
includes the corresponding bitcoin address, for convenience, but this is not necessary
since it can be derived from the private key. Paper wallets are a very effective way to
create backups or offline bitcoin storage, also known as cold storage. As a backup
mechanism, a paper wallet can provide security against the loss of key due to a computer
mishap such as a hard drive failure, theft, or accidental deletion. As a cold storage
mechanism, if the paper wallet keys are generated offline and never stored on a computer
system, they are much more secure against hackers, key-loggers and other online com
puter threats.
Paper wallets come in many shapes, sizes and designs, but at a very basic level are just
a key and an address printed on paper. Heres the simplest form of a paper wallet:
Table 4-14. A very simple paper wallet - a printout of the bitcoin address and private
key
Public Address 1424C2F4bC9JidNjjTUZCbUxv6Sa1Mt62x
Private Key (WIF) 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn
Paper wallets can be generated easily using a tool such as the client-side Javascript gen
erator at bitaddress.org. This page contains all the code necessary to generate keys and
paper wallets, even while completely disconnected from the Internet. To use it, save the
HTML page on your local drive or on an external USB flash drive. Disconnect from the
Internet and open the file in a browser. Even better, boot your computer using a pristine
operating system, such as a CDROM bootable Linux OS. Any keys generated with this
tool while offline can be printed on a local printer over a USB cable (not wirelessly),
thereby creating paper wallets whose keys exist only on the paper and have never been
stored on any online system. Put these paper wallets in a fire-proof safe and send
The disadvantage of the simple paper wallet system is that the printed keys are vulnerable
to theft. A thief who is able to gain access to the paper can either steal it or photograph
the keys and take control of the bitcoins locked with those keys. A more sophisticated
paper wallet storage system uses BIP0038 encrypted private keys. The keys printed on
the paper wallet are protected by a passphrase that the owner has memorized. Without
the passphrase, the encrypted keys are useless. Yet, they still are superior to a passphrase
protected wallet because the keys have never been online and must be physically re
trieved from a safe or other physically secured storage.
While you can deposit funds into a paper wallet several times, you
should withdraw all funds only once, spending everything. This is
because in the process of unlocking and spending funds you ex
pose the private key and because some wallets may generate a change
address if you spend less than the whole amount. One way to do this
is to withdraw the entire balance stored in the paper wallet and send
any remaining funds to a new paper wallet.
Paper wallets come in many designs and sizes, with many different features. Some are
intended to be given as gifts and have seasonal themes, such as Christmas and New
Years themes. Others are designed for storage in a bank vault or safe with the private
key hidden in some way, either with opaque scratch-off stickers, or folded and sealed
with tamper-proof adhesive foil.
Figure 4-17. The bitcoinpaperwallet.com paper wallet with the private key concealed.
Other designs feature additional copies of the key and address, in the form of detachable
stubs similar to ticket stubs, allowing you to store multiple copies to protect against fire,
flood or other natural disasters.
Introduction
Transactions are the most important part of the bitcoin system. Everything else in bit
coin is designed to ensure that transactions can be created, propagated on the network,
validated, and finally added to the global ledger of transactions, the blockchain. Trans
actions are data structures that encode the transfer of value between participants in the
bitcoin system. Each transaction is a public entry in bitcoins global double-entry book
keeping ledger, the blockchain.
In this chapter we will examine all the various forms of transactions, what they contain,
how to create them, how they are verified, and how they become part of the permanent
record of all transactions.
Transaction Lifecycle
A transactions lifecycle starts with the transactions creation, also known as origination.
The transaction is then signed, with one or more signatures indicating the authorization
to spend the funds referenced by the transaction. The transaction is then broadcast on
the bitcoin network, where each network node (participant) validates and propagates
the transaction until it reaches (almost) every node in the network. Finally, the trans
action is verified by a mining node and included in a block of transactions that is re
corded on the blockchain.
Once recorded on the blockchain and confirmed by sufficient subsequent blocks (con
firmations), the transaction is a permanent part of the bitcoin ledger and is accepted as
valid by all participants. The funds allocated to a new owner by the transaction can then
be spent in a new transaction, extending the chain of ownership and beginning the
lifecycle of a transaction again.
111
Creating Transactions
In some ways it helps to think of a transaction in the same way as a paper cheque. Like
a cheque, a transaction is an instrument that expresses the intent to transfer money and
is not visible to the financial system until it is submitted for execution. Like a cheque,
the originator of the transaction does not have to be the one signing the transaction.
Transactions can be created online or offline by anyone, even if the person creating the
transaction is not an authorized signer on the account. For example an accounts payable
clerk might process payable cheques for signature by the CEO. Similarly, an accounts
payable clerk can create bitcoin transactions and then have the CEO apply digital sig
natures to make them valid. While a cheque references a specific account as the source
of the funds, a bitcoin transaction references a specific previous transaction as its source,
rather than an account.
Once a transaction has been created, it is signed by the owner (or owners) of the source
funds. If it was properly formed and signed, the signed transaction is now valid and
contains all the information needed to execute the transfer of funds. Finally, the valid
transaction has to reach the bitcoin network so that it can be propagated until it reaches
a miner for inclusion in the pubic ledger, the blockchain.
Transaction Structure
A transaction is a data structure that encodes a transfer of value from a source of funds,
called an input, to a destination, called an output. Transaction inputs and outputs are
not related to accounts or identities. Instead you should think of them as bitcoin
amounts, chunks of bitcoin, being locked with a specific secret which only the owner,
or person who knows the secret, can unlock.
A transaction contains a number of fields, as follows:
Table 5-1. The structure of a transaction
Size Field Description
4 bytes Version Specifies which rules this transaction follows
1-9 bytes (VarInt) Input Counter How many inputs are included
Variable Inputs One or more Transaction Inputs
1-9 bytes (VarInt) Output Counter How many outputs are included
Variable Outputs One or more Transaction Outputs
4 bytes Locktime A unix timestamp or block number
A UTXO can have an arbitrary value denominated as a multiple of satoshis. Just like
dollars can be divided down to two decimal places as cents, bitcoins can be divided
down to eight decimal places as satoshis. While UTXO can be any arbitrary value, once
created it is indivisible just like a coin that cannot be cut in half. If a UTXO is larger
than the desired value of a transaction, it must still be consumed in its entirety and
change must be generated in the transaction. In other words, if you have a 20 bitcoin
UTXO and want to pay 1 bitcoin, your transaction must consume the entire 20 bitcoin
UTXO and produce two outputs: one paying 1 bitcoin to your desired recipient and
another paying 19 bitcoin in change back to your wallet. As a result, most bitcoin trans
actions will generate change.
What comes first? Inputs or outputs, the chicken or the egg? Strictly
speaking, outputs come first because coinbase transactions, which
generate new bitcoin, have no inputs and create outputs from nothing.
Transaction Outputs
Every bitcoin transaction creates outputs, which are recorded on the bitcoin ledger.
Almost all of these outputs, with one exception (see Data Output (OP_RETURN) on
page 133) create spendable chunks of bitcoin called unspent transaction outputs or UTXO,
which are then recognized by the whole network and available for the owner to spend
in a future transaction. Sending someone bitcoin is creating an unspent transaction
output (UTXO) registered to their address and available for them to spend.
The transaction scripting language, used in the locking script mentioned above, is dis
cussed in detail in Transaction Scripts and Script Language on page 123
Table 5-2. The structure of a transaction output
Size Field Description
8 bytes Amount Bitcoin Value in Satoshis (10-8 bitcoin)
1-9 bytes (VarInt) Locking-Script Size Locking-Script length in bytes, to follow
Variable Locking-Script A script defining the conditions needed to spend the output
In the example below, we use the blockchain.info API to find the unspent outputs (UT
XO) of a specific address:
Example 5-1. A script that calls the blockchain.info API to find the UTXO related to an
address
# get unspent outputs from blockchain API
import json
import requests
# example address
address = '1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX'
Running the script, we see a list of transaction IDs, a colon, the index number of the
specific unspent transaction output (UTXO), and the value of that UTXO in Satoshis.
The locking script is not shown in this output:
Example 5-2. Running the get-utxo.py script
$ python get-utxo.py
ebadfaa92f1fd29e2fe296eda702c48bd11ffd52313e986e99ddad9084062167:1 - 8000000 Satoshis
6596fd070679de96e405d52b51b8e1d644029108ec4cbfe451454486796a1ecf:0 - 16050000 Satoshis
74d788804e2aae10891d72753d1520da1206e6f4f20481cc1555b7f2cb44aca0:0 - 5000000 Satoshis
b2affea89ff82557c60d635a2a3137b8f88f12ecec85082f7d0a1f82ee203ac4:0 - 10000000 Satoshis
...
Transaction Inputs
In simple terms, transaction inputs are pointers to UTXO. They point to a specific
UTXO by reference to the transaction hash and sequence number where the UTXO is
recorded in the blockchain. To spend UTXO, a transaction input also includes
unlocking-scripts that satisfy the spending conditions set by the UTXO. The unlocking
script is usually a signature proving ownership of the bitcoin address that is in the
locking script.
When a user makes a payment, their wallet constructs a transaction by selecting from
the available UTXO. For example, to make a 0.015 bitcoin payment, the wallet app may
select a 0.01 UTXO and a 0.005 UTXO, using them both to add up to the desired payment
amount.
In the example below, we show the use of a greedy algorithm to select from available
UTXO in order to make a specific payment amount. In the example, the available UTXO
class OutputInfo:
def __repr__(self):
return "<%s:%s with %s Satoshis>" % (self.tx_hash, self.tx_index,
self.value)
def main():
if len(argv) > 1:
target = long(argv[1])
else:
target = 55000000
print "For transaction amount %d Satoshis (%f bitcoin) use: " % (target, target/10.0**8)
print select_outputs_greedy(unspent, target)
if __name__ == "__main__":
main()
If we run the select-utxo.py script without a parameter it will attempt to construct a set
of UTXO (and change) for a payment of 55000000 Satoshis (0.55 bitcoin). If you provide
a target payment amount as a parameter, the script will select UTXO to make that target
payment amount. Below, we run the script trying to make a payment of 0.5 bitcoin or
50000000 Satoshis:
Example 5-4. Running the select-utxo.py script
$ python select-utxo.py 50000000
For transaction amount 50000000 Satoshis (0.500000 bitcoin) use:
([<7dbc497969c7475e45d952c4a872e213fb15d45e5cd3473c386a71a1b0c136a1:0 with 25000000 Satoshis>, \
<7f42eda67921ee92eae5f79bd37c68c9cb859b899ce70dba68c48338857b7818:0 with 16100000 Satoshis>, \
<6596fd070679de96e405d52b51b8e1d644029108ec4cbfe451454486796a1ecf:0 with 16050000 Satoshis>],\
'Change: 7150000 Satoshis')
Once the UTXO is selected, the wallet then produces unlocking scripts containing sig
natures for each of the UTXO, thereby making them spendable by satisfying their lock
ing script conditions. The wallet adds these UTXO references and unlocking scripts as
inputs to the transaction.
Table 5-3. The structure of a transaction input
Size Field Description
32 bytes Transaction Hash Pointer to the transaction containing the UTXO to be spent
4 bytes Output Index The index number of the UTXO to be spent, first one is 0
1-9 bytes (VarInt) Unlocking-Script Size Unlocking-Script length in bytes, to follow
Variable Unlocking-Script A script that fulfills the conditions of the UTXO locking-script.
4 bytes Sequence Number Currently-disabled Tx-replacement feature, set to 0xFFFFFFFF
Transaction Fees
Most transactions include transaction fees, which compensate the bitcoin miners for
securing the network. Mining and the fees and rewards collected by miners are discussed
in more detail in Introduction on page 177. This section examines how transaction fees
are included in a typical transaction. Most wallets calculate and include transaction fees
automatically. However, if you are constructing transactions programmatically, or using
a command line interface, you must manually account for and include these fees.
Transaction fees serve as an incentive to include (mine) a transaction into the next block
and also as a disincentive against spam transactions or any kind of abuse of the system,
by imposing a small cost on every transaction. Transaction fees are collected by the
miner who mines the block that records the transaction on the blockchain.
Transaction fees are calculated based on the size of the transaction in kilobytes, not the
value of the transaction in bitcoin. Overall, transaction fees are set based on market
forces within the bitcoin network. Miners prioritize transactions based on many dif
ferent criteria, including fees and may even process transactions for free under certain
circumstances. Transaction fees affect the processing priority, meaning that a transac
tion with sufficient fees is likely to be included in the next-most mined block, while a
transaction with insufficient or no fees may be delayed, on a best-effort basis and pro
cessed after a few blocks or not at all. Transaction fees are not mandatory and transac
tions without fees may be processed eventually; however, including transaction fees
encourages priority processing.
Over time, the way transaction fees are calculated and the effect they have on transaction
prioritization has been evolving. At first, transaction fees were fixed and constant across
the network. Gradually, the fee structure has been relaxed so that it may be influenced
by market forces, based on network capacity and transaction volume. The current min
imum transaction fee is fixed at 0.0001 bitcoin or a tenth of a milli-bitcoin per kilobyte,
recently decreased from one milli-bitcoin. Most transactions are less than one kilobyte;
however, those with multiple inputs or outputs can be larger. In future revisions of the
bitcoin protocol it is expected that wallet applications will use statistical analysis to
calculate the most appropriate fee to attach to a transaction based on the average fees
of recent transactions.
The current algorithm used by miners to prioritize transactions for inclusion in a block
based on their fees will be examined in detail in Introduction on page 177.
Lets see how this works in practice, by looking at Alices coffee purchase again. Alice
wants to spend 0.015 bitcoin to pay for coffee. To ensure this transaction is processed
promptly, she will want to include a transaction fee, say 0.001. That will mean that the
total cost of the transaction will be 0.016. Her wallet must therefore source a set of UTXO
that adds up to 0.016 bitcoin or more and if necessary create change. Lets say her wallet
has a 0.2 bitcoin UTXO available. It will therefore need to consume this UTXO, create
one output to Bobs Cafe for 0.015, and a second output with 0.184 bitcoin in change
back to her own wallet, leaving 0.001 bitcoin unallocated, as an implicit fee for the
transaction.
Now lets look at a different scenario. Eugenia, our childrens charity director in the
Philippines has completed a fundraiser to purchase school books for the children. She
received several thousand small donations from people all around the world, totaling
50 bitcoin. Now she wants to purchase hundreds of school books from a local publisher,
paying in bitcoin. The charity received thousands of small donations from all around
the world, so her wallet is full of very small payments (UTXO).
Turing Incompleteness
The bitcoin transaction script language contains many operators but is deliberately
limited in one important way there are no loops or complex flow control capabilities
other than conditional flow control. This ensures that the language is not Turing Com
plete, meaning that scripts have limited complexity and predictable execution times.
Script is not a general-purpose language. These limitations ensure that the language
cannot be used to create an infinite loop or other form of logic bomb that could be
embedded in a transaction in a way that causes a Denial-of-Service attack against the
bitcoin network. Remember, every transaction is validated by every full node on the
Stateless Verification
The bitcoin transaction script language is stateless, in that there is no state prior to
execution of the script, or state saved after execution of the script. Therefore, all the
information needed to execute a script is contained within the script. A script will pre
dictably execute the same way on any system. If your system verifies a script, you can
be sure that every other system in the bitcoin network will also verify the script, meaning
that a valid transaction is valid for everyone and everyone knows this. This predictability
of outcomes is an essential benefit of the bitcoin system.
Standard Transactions
In the first few years of bitcoins development, the developers introduced some limita
tions in the types of scripts that could be processed by the reference client. These lim
itations are encoded in a function called isStandard() which defines five types of
standard transactions. These limitations are temporary and may be lifted by the time
you read this. Until then, the five standard types of transaction scripts are the only ones
that will be accepted by the reference client and most miners who run the reference
client. While it is possible to create a non-standard transaction containing a script that
is not one of the standard types, you must find a miner who does not follow these
limitations, to mine that transaction into a block.
Check the source code of the bitcoin core client (the reference implementation) to see
what is currently allowed as a valid transaction script.
The five standard types of transaction scripts are Pay-to-Public-Key-Hash (P2PKH),
Public-Key, Multi-Signature (limited to 15 keys), Pay-to-Script-Hash (P2SH) and Data
Output (OP_RETURN), which are described in more detail below.
The Cafe Public Key Hash is equivalent to the bitcoin address of the Cafe, without
the Base58Check encoding. Most applications would show the Public Key Hash in hex
adecimal encoding and not the familiar bitcoin address Base58Check format that begins
with a 1.
The locking script above can be satisfied with an unlocking script of the form:
<Cafe Signature> <Cafe Public Key>
The two scripts together would form the combined validation script below:
<Cafe Signature> <Cafe Public Key> OP_DUP OP_HASH160 \
<Cafe Public Key Hash> OP_EQUAL OP_CHECKSIG
When executed, this combined script will evaluate to TRUE if, and only if, the unlocking
script matches the conditions set by the locking script. In other words, the result will
be TRUE if the unlocking script has a valid signature from the Cafes private key which
corresponds to the public key hash set as an encumbrance.
Heres a step-by-step execution of the combined script, which will prove this is a valid
transaction:
Pay-to-Public-Key
Pay-to-Public-Key is a simpler form of a bitcoin payment than Pay-to-Public-Key-Hash.
With this script form, the public key itself is stored in the locking script, rather than a
public-key-hash as with P2PKH above, which is much shorter. Pay-to-Public-Key-Hash
was invented by Satoshi to make bitcoin addresses shorter, for ease of use. Pay-to-Public-
Key is now most often seen in coinbase transactions, generated by older mining software
that has not been updated to use P2PKH.
A Pay-to-Public-Key locking script looks like this:
<Public Key A> OP_CHECKSIG
Multi-Signature
Multi-signature scripts set a condition where N public keys are recorded in the script
and at least M of those must provide signatures to release the encumbrance. This is also
known as an M-of-N scheme, where N is the total number of keys and M is the threshold
of signatures required for validation. For example, a 2-of-3 multi-signature is one where
3 public keys are listed as potential signers and at least 2 of those must be used to create
signatures for a valid transaction to spend the funds. At this time, standard multi-
signature scripts are limited to at most 15 listed public keys, meaning you can do any
thing from a 1-of-1 to a 15-of-15 multi-signature or any combination within that range.
The limitation to 15 listed keys may be lifted by the time of publication of this book, so
check the isStandard() function to see what is currently accepted by the network.
The general form of a locking script setting an M-of-N multi-signature condition is:
M <Public Key 1> <Public Key 2> ... <Public Key N> N OP_CHECKMULTISIG
where N is the total number of listed public keys and M is the threshold of required
signatures to spend the output.
A locking script setting a 2-of-3 multi-signature condition looks like this:
2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG
The locking script above can be satisfied with an unlocking script containing pairs of
signatures and public keys:
OP_0 <Signature B> <Signature C>
or any combination of two signatures from the private keys corresponding to the three
listed public keys.
Note: The prefix OP_0 is required because of a bug in the original implementation of
CHECKMULTISIG where one item too many is popped off the stack. It is ignored by
CHECKMULTISIG and is simply a placeholder.
The two scripts together would form the combined validation script below:
OP_0 <Signature B> <Signature C>\
2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG
As you can see from the tables above, with P2SH the complex script that details the
conditions for spending the output (redeem script) is not presented in the locking script.
Instead, only a hash of it is in the locking script and the redeem script itself is presented
later, as part of the unlocking script when the output is spent. This shifts the burden in
fees and complexity from the sender to the recipient (spender) of the transaction.
Lets look at Mohammeds company, their complex multi-signature script and the re
sulting P2SH scripts.
First, the multi-signature script that Mohammeds company uses for all incoming pay
ments from customers:
2 <Mohammed's Public Key> <Partner1 Public Key> <Partner2 Public Key> \
<Partner3 Public Key> <Attorney Public Key> 5 OP_CHECKMULTISIG
If the placeholders above are replaced by actual public keys (shown below as 520 bit
numbers starting with 04) you can see that this script becomes very long:
2
04C16B8698A9ABF84250A7C3EA7EEDEF9897D1C8C6ADF47F06CF73370\
Pay-to-Script-Hash Addresses
Another important part of the P2SH feature is the ability to encode a script hash as an
address, as defined in BIP0013. P2SH addresses are Base58Check encodings of the 20-
byte hash of a script, just like bitcoin addresses are Base58Check encodings of the 20-
byte hash of a public key. P2SH addresses use the version prefix 5, which results in
Base58Check encoded addresses that start with a 3. For example, Mohammeds com
plex script, hashed and Base58Check encoded as P2SH address becomes 39RF6JqABiH
dYHkfChV6USGMe6Nsr66Gzw. Now, Mohammed can give this address to his customers
Benefits of Pay-to-Script-Hash
The Pay-to-Script-Hash feature offers the following benefits compared to the direct use
of complex scripts in locking outputs:
Complex scripts are replaced by shorter fingerprint in the transaction output, mak
ing the transaction smaller
Scripts can be coded as an address, so the sender and the senders wallet dont need
complex engineering to implement P2SH
P2SH shifts the burden of constructing the script to the recipient not the sender
P2SH shifts the burden in data storage for the long script from the output (which
is in the UTXO set and therefore impacts memory) to the input (only stored on the
blockchain)
P2SH shifts the burden in data storage for the long script from the present time
(payment) to a future time (when it is spent)
P2SH shifts the transaction fee cost of a long script from the sender to the recipient
who has to include the long redeem script to spend it
P2SH locking scripts contain the hash of a redeem script which gives
no clues as to the content of the redeem script itself. The P2SH
transaction will be considered valid and accepted even if the re
deem script is invalid. You may accidentally lock bitcoin in such a
way that it cannot later be spent.
139
protocol. We use the term extended bitcoin network to refer to the overall network
that includes the bitcoin P2P protocol, pool mining protocols, the Stratum protocol,
and any other related protocols connecting the components of the bitcoin system.
Figure 6-1. A bitcoin network node with all four functions: Wallet, Miner, full Block
chain database, and Network routing
All nodes include the routing function to participate in the network and may include
other functionality. All nodes validate and propagate transactions and blocks, and dis
cover and maintain connections to peers. In the full node example above, the routing
function is indicated by an orange circle named Network Routing Node.
Some nodes, called full nodes, also maintain a complete and up-to-date copy of the
blockchain. Full nodes can autonomously and authoritatively verify any transaction
without external reference. Some nodes maintain only a subset of the blockchain and
verify transactions using a method called Simplified Payment Verification or SPV. These
nodes are known as SPV or Lightweight nodes. In the full node example above, the full
node blockchain database function is indicated by a blue circle named Full Blockchain.
SPV nodes are drawn without the blue circle, showing that they do not have a full copy
of the blockchain.
Figure 6-3. The extended bitcoin network showing various node types, gateways and
protocols
(See https://github.com/bitcoin/bitcoin/blob/
d3cb2b8acfce36d359262b4afd7e7235eff106b0/src/net.cpp#L562 for an example of the
version network message)
The peer node responds with verack to acknowledge and establish a connection, and
optionally sends its own version message if it wishes to reciprocate the connection and
connect back as a peer.
How does a new node find peers? While there are no special nodes in bitcoin, there are
some long running stable nodes that are listed in the client as seed nodes. While a new
node does not have to connect with the seed nodes, it can use them to quickly discover
other nodes in the network. In the Bitcoin Core client, the option to use the seed nodes
is controlled by the option switch -dnsseed, which is set to 1, to use the seed nodes, by
default. Alternatively, a bootstrapping node that knows nothing of the network must be
given the IP address of at least one bitcoin node after which it can establish connections
through further introductions. The command line argument -seednode can be used to
connect to one node just for introductions, using it as a DNS seed. After the initial seed
node is used to form introductions, the client will disconnect from it and use the newly
discovered peers.
Once one or more connections are established, the new node will send an addr message
containing its own IP address, to its neighbors. The neighbors will in turn forward the
addr message to their neighbors, ensuring that the newly connected node becomes well
known and better connected. Additionally, the newly connected node can send ge
taddr to the neighbors, asking them to return a list of IP addresses of other peers. That
way, a node can find peers to connect to and advertise its existence on the network for
other nodes to find it.
A node must connect to a few different peers in order to establish diverse paths into the
bitcoin network. Paths are not reliable, nodes come and go, and so the node must con
tinue to discover new nodes as it loses old connections as well as assist other nodes when
they bootstrap. Only one connection is needed to bootstrap, as the first node can offer
introductions to its peer nodes and those peers can offer further introductions. Its also
unnecessary and wasteful of network resources to connect to more than a handful of
nodes. After bootstrapping, a node will remember its most recent successful peer con
nections, so that if it is rebooted it can quickly reestablish connections with its former
peer network. If none of the former peers respond to its connection request, the node
can use the seed nodes to bootstrap again.
On a node running the Bitcoin Core client, you can list the peer connections with the
command getpeerinfo:
$ bitcoin-cli getpeerinfo
[
{
"addr" : "85.213.199.39:8333",
"services" : "00000001",
"lastsend" : 1405634126,
"lastrecv" : 1405634127,
"bytessent" : 23487651,
Full Nodes
Full nodes are nodes that maintain a full blockchain with all transactions. More accu
rately they probably should be called full blockchain nodes. In the early years of bitcoin,
all nodes were full nodes and currently the Bitcoin Core client is a full blockchain node.
In the last two years, however, new forms of bitcoin clients have been introduced that
do not maintain a full blockchain but run as lightweight clients. These are examined in
more detail in the next section.
Exchanging Inventory
The first thing a full node will do once it connects to peers is try to construct a complete
blockchain. If it is a brand-new node and has no blockchain at all, then it only knows
one block (the genesis block), which is statically embedded in the client software. Start
ing with block #0, the genesis block, the new node will have to download hundreds of
thousands of blocks to synchronize with the network and re-establish the full block
chain.
The process of syncing the blockchain starts with the version message, as that con
tains BestHeight, a nodes current blockchain height (number of blocks). A node will
see the version messages from its peers, know how many blocks they each have and be
able to compare to how many blocks it has in its own blockchain. Peered nodes will
exchange a getblocks message that contains the hash (fingerprint) of the top block on
their local blockchain. One of the peers will be able to identify the received hash as
belonging to a block that is not at the top, but rather belongs to an older block, thus
deducing that its own local blockchain is longer than its peers.
The peer that has the longer blockchain has more blocks than the other node and can
identify which blocks the other node needs in order to catch up. It will identify the first
500 blocks to share and transmit their hashes using an inv (inventory) message. The
To get the block headers, SPV nodes use a getheaders message instead of getblocks.
The responding peer will send up to 2000 block headers using a single headers message.
The process is otherwise the same as that used by a full node to retrieve full blocks. SPV
nodes also set a filter on the connection to peers, to filter the stream of future blocks
and transactions sent by the peers. Any transactions of interest are retrieved using a
getdata request. The peer generates a tx message containing the transactions, in re
sponse.
Because SPV nodes need to retrieve specific transactions in order to selectively verify
them, they also create a privacy risk. Unlike full-blockchain nodes, which collect all
transactions within each block, the SPV nodes requests for specific data can inadver
tently reveal the addresses in their wallet. For example, a third party monitoring a net
work could keep track of all the transactions requested by a wallet on an SPV node and
use those to associate bitcoin addresses with the user of that wallet, destroying the users
privacy.
Shortly after the introduction of SPV/lightweight nodes, the bitcoin developers added
a feature called bloom filters to address the privacy risks of SPV nodes. Bloom filters
allow SPV nodes to receive a subset of the transactions without revealing precisely which
addresses they are interested in, through a filtering mechanism that uses probabilities
rather than fixed patterns.
Figure 6-8. An example of a simplistic bloom filter, with 16 bit field and 3 hash func
tions
The bloom filter is initialized so that the array of bits is all zeros. To add a pattern to the
bloom filter, the pattern is hashed by each hash function in turn. Applying the first hash
function to the input results in a number between 1 and N. The corresponding bit in
the array (indexed from 1 to N) is found and set to 1, thereby recording the output of
the hash function. Then, the next hash function is used to set another bit and so on and
so forth. Once all M hash functions have been applied, the search pattern will be re
corded in the bloom filter as M bits have been changed from 0 to 1.
Heres an example of adding a pattern A to the simple bloom filter shown above:
Adding a second pattern is as simple as repeating this process. The pattern is hashed by
each hash function in turn and the result is recorded by setting the bits to 1. Note that
as a bloom filter is filled with more patterns, a hash function result may coincide with
a bit that is already set to 1 in which case the bit is not changed. In essence, as more
patterns record on overlapping bits, the bloom filter starts to become saturated with
more bits set to 1 and the accuracy of the filter decreases. This is why the filter is a
probabilistic data structure it gets less accurate as more patterns are added. The ac
curacy depends on the number of patterns added versus the size of the bit array (N) and
number of hash functions (M). A larger bit array and more hash functions can record
more patterns with higher accuracy. A smaller bit array or fewer hash functions will
record fewer patterns and produce less accuracy.
Below is an example of adding a second pattern B to the simple bloom filter:
To test if a pattern is part of a bloom filter, the pattern is hashed by each hash function
and the resulting bit pattern is tested against the bit array. If all the bits indexed by the
hash functions are set to 1, then the pattern is probably recorded in the bloom filter.
Since the bits may be set because of overlap from multiple patterns, the answer is not
certain, but is rather probabilistic. In simple terms, a bloom filter positive match is a
Maybe, Yes.
Below is an example of testing the existence of pattern X in the simple bloom filter.
The corresponding bits are set to 1, so the pattern is probably a match:
On the contrary, if a pattern is tested against the bloom filter and any one of the bits is
set to 0, then this proves that the pattern was not recorded in the bloom filter. A negative
result is not a probability, it is a certainty. In simple terms, a negative match on a bloom
filter is a Definitely No.
Below is an example of testing the existence of pattern Y in the simple bloom filter.
One of the corresponding bits is set to 0, so the pattern is definitely not a match:
Transaction Pools
Almost every node on the bitcoin network maintains a temporary list of unconfirmed
transactions called the memory pool or transaction pool. Nodes use this pool to keep
track of transactions that are known to the network but are not yet included in the
blockchain. For example, a node that holds a users wallet will use the transaction pool
to track incoming payments to the users wallet that have been received on the network
but are not yet confirmed.
As transactions are received and verified, they are added to the transaction pool and
relayed to the neighboring nodes to propagate on the network.
Some node implementations also maintain a separate pool of orphaned transactions as
detailed in (to come). If a transactions inputs refer to a transaction that is not yet known,
a missing parent, then the orphan transaction will be stored temporarily in the orphan
pool until the parent transaction arrives.
When a transaction is added to the transaction pool, the orphan pool is checked for any
orphans that reference this transactions outputs (its children). Any matching orphans
are then validated. If valid, they are removed from the orphan pool and added to the
transaction pool, completing the chain that started with the parent transaction. In light
of the newly added transaction which is no longer an orphan, the process is repeated
recursively looking for any further descendants, until no more descendants are found.
Through this process, the arrival of a parent transaction triggers a cascade reconstruc
tion of an entire chain of interdependent transactions by re-uniting the orphans with
their parents all the way down the chain.
Both the transaction pool and orphan pool (where implemented) are stored in local
memory and are not saved on persistent storage, rather they are dynamically populated
from incoming network messages. When a node starts, both pools are empty and are
gradually populated with new transactions received on the network.
Some implementations of the bitcoin client also maintain a UTXO database or UTXO
pool, which is the set of all unspent outputs on the blockchain. While the name UTXO
pool sounds similar to the transaction pool, it represents a different set of data. Unlike
the transaction and orphan pools, the UTXO pool is not initialized empty but instead
contains millions of entries of unspent transaction outputs including some dating back
to 2009. The UTXO pool may be housed in local memory or as an indexed database
table on persistent storage.
Whereas the transaction and orphan pools represent a single nodes local perspective
and may vary significantly from node to node depending upon when the node was
Alert Messages
Alert messages are a seldom used function, which is nevertheless implemented in most
nodes. Alert messages are bitcoins emergency broadcast system, a means by which the
core bitcoin developers can send an emergency text message to all bitcoin nodes. This
feature is implemented to allow the core developer team to notify all bitcoin users of a
serious problem in the bitcoin network, such as a critical bug that requires user action.
The alert system has only been used a handful of times, most notably early 2013 when
a critical database bug caused a multi-block fork to occur in the bitcoin blockchain.
Alert messages are propagated by the alert message. The alert message contains several
fields, including:
Alerts are cryptographically signed by a public key. The corresponding private key is
held by a few selected members of the core development team. The digital signature
ensures that fake alerts will not be propagated on the network.
Each node receiving this alert message will verify it, check for expiration, and propagate
it to all its peers, thus ensuring rapid propagation across the entire network. In addition
to propagating the alert, each node may implement a user interface function to present
the alert to the user.
In the Bitcoin Core client, the alert is configured with the command line option -
alertnotify, which specifies a command to run when an alert is received. The alert
message is passed as a parameter to the alertnotify command. Most commonly, the
alertnotify command is set to generate an email message to the administrator of the
node, containing the alert message. The alert is also displayed as a pop-up dialog in the
graphical user interface (bitcoin-Qt) if it is running.
Other implementations of the bitcoin protocol may handle the alert in different ways.
Many hardware-embedded bitcoin mining systems do not implement the alert message
Introduction
The blockchain data structure is an ordered back-linked list of blocks of transactions.
The blockchain can be stored as a flat file, or in a simple database. The bitcoin core client
stores the blockchain metadata using Googles LevelDB database. Blocks are linked
back, each referring to the previous block in the chain. The blockchain is often vi
sualized as a vertical stack, with blocks layered on top of each other and the first block
ever serving as the foundation of the stack. The visualization of blocks stacked on top
of each other results in the use of terms like height to refer to the distance from the
first block, and top or tip to refer to the most recently added block.
Each block within the blockchain is identified by a hash, generated using the SHA256
cryptographic hash algorithm on the header of the block. Each block also references a
previous block, known as the parent block, through the previous block hash field in
the block header. In other words, each block contains the hash of its parent inside its
own header. The sequence of hashes linking each block to its parent, creates a chain
going back all the way to the first block ever created, known as the genesis block.
While a block has just one parent, it can temporarily have multiple children. Each of
the children refers to the same block as its parent and contains the same (parent) hash
in the previous block hash field. Multiple children arise during a blockchain fork, a
temporary situation that occurs when different blocks are discovered almost simulta
neously by different miners (see Blockchain Forks on page 204). Eventually, only one
child block becomes part of the blockchain and the fork is resolved. Even though a
block may have more than one child, each block can have only one parent. This is because
a block has one single previous block hash field referencing its single parent.
The previous block hash field is inside the block header and thereby affects the cur
rent blocks hash. The childs own identity changes if the parents identity changes. When
the parent is modified in any way, the parents hash changes. The parents changed hash
163
necessitates a change in the previous block hash pointer of the child. This in turn
causes the childs hash to change, which requires a change in the pointer of the grand
child, which in turn changes the grandchild and so on. This cascade effect ensures that
once a block has many generations following it, it cannot be changed without forcing
a recalculation of all subsequent blocks. Because such a recalculation would require
enormous computation, the existence of a long chain of blocks makes the blockchains
deep history immutable, a key feature of bitcoins security.
One way to think about the blockchain is like layers in a geological formation, or glacier
core sample. The surface layers may change with the seasons, or even be blown away
before they have time to settle. But once you go a few inches deep, geological layers
become more and more stable. By the time you look a few hundred feet down, you are
looking at a snapshot of the past that has remained undisturbed for millennia or millions
of years. In the blockchain, the most recent few blocks may be revised if there is a chain
recalculation due to a fork. The top six blocks are like a few inches of topsoil. But once
you go deeper into the blockchain, beyond 6 blocks, blocks are less and less likely to
change. After 100 blocks back there is so much stability that the coinbase transaction,
the transaction containing newly-mined bitcoins, can be spent. A few thousand blocks
back (a month) and the blockchain is settled history. It will never change.
Structure of a Block
A block is a container data structure that aggregates transactions for inclusion in the
public ledger, the blockchain. The block is made of a header, containing metadata, fol
lowed by a long list of transactions that make up the bulk of its size. The block header
is 80 bytes, whereas the average transaction is at least 250 bytes and the average block
contains more than 500 transactions. A complete block, with all transactions, is there
fore 1000 times larger than the block header.
Table 7-1. The structure of a block
Size Field Description
4 bytes Block Size The size of the block, in bytes, following this field
80 bytes Block Header Several fields form the block header (see below)
1-9 bytes (VarInt) Transaction Counter How many transactions follow
Variable Transactions The transactions recorded in this block
Block Header
The block header consists of three sets of block metadata. First, there is a reference to
a previous block hash, which connects this block to the previous block in the blockchain.
We will examine this in more detail in Chapter 7. The second set of metadata, namely
the difficulty, timestamp and nonce, relate to the mining competition, as detailed in
The Nonce, Difficulty Target, and Timestamp are used in the mining process and will
be discussed in more detail in Introduction on page 177.
"05cfd38f6ae6aa83674cc99e4d75a1458c165b7ab84725eda41d018a09176634"
]
}
Looking at this new block, the node finds the previousblockhash field, which contains
the hash of its parent block. It is a hash known to the node, that of the last block on the
chain at height 277,314. Therefore, this new block is a child of the last block on the chain
and extends the existing blockchain. The node adds this new block to the end of the
chain, making the blockchain longer with a new height of 277,315.
Since the merkle tree is a binary tree, it needs an even number of leaf nodes. If there is
an odd number of transactions to summarize, the last transaction hash will be duplicated
to create an even number of leaf nodes, also known as a balanced tree. This is shown in
the example below, where transaction C is duplicated:
Figure 7-3. An even number of data elements, by duplicating one data element
The same method for constructing a tree from four transactions can be generalized to
construct trees of any size. In bitcoin it is common to have several hundred to more
than a thousand transactions in a single block, which are summarized in exactly the
To prove that a specific transaction is included in a block, a node only needs to produce
log2(N) 32-byte hashes, constituting an authentication path or merkle path connecting
the specific transaction to the root of the tree. This is especially important as the number
of transactions increases, because the base-2 logarithm of the number of transactions
increases much more slowly. This allows bitcoin nodes to efficiently produce paths of
ten or twelve hashes (320-384 bytes) which can provide proof of a single transaction
out of more than a thousand transactions in a megabyte sized block. In the example
below, a node can prove that a transaction K is included in the block by producing a
merkle path that is only four 32-byte hashes long (128 bytes total). The path consists of
the four hashes (noted in blue in the diagram below) HL, HIJ, HMNOP and HABCDEFGH. With
those four hashes provided as an authentication path, any node can prove that HK (noted
in green in the diagram below) is included in the merkle root by computing four addi
tional pair-wise hashes HKL, HIJKL and HIJKLMNOP (outlined in a dotted line in the diagram
below) that lead to the merkle root.
The code in Example 7-1 demonstrates the process of creating a merkle tree from the
leaf-node hashes up to the root, using the libbitcoin library for some helper functions:
Example 7-1. Building a merkle tree
#include <bitcoin/bitcoin.hpp>
int main()
{
// Replace these hashes with ones from a block to reproduce the same merkle root.
bc::hash_digest_list tx_hashes{{
bc::decode_hash("0000000000000000000000000000000000000000000000000000000000000000"),
bc::decode_hash("0000000000000000000000000000000000000000000000000000000000000011"),
bc::decode_hash("0000000000000000000000000000000000000000000000000000000000000022"),
}};
const bc::hash_digest merkle_root = create_merkle(tx_hashes);
std::cout << "Result: " << bc::encode_hex(merkle_root) << std::endl;
return 0;
}
Result: d47780c084bad3830bcdaf6eace035e4c6cbf646d103795d22104fb105014ba3
The efficiency of merkle trees becomes obvious as the scale increases. For example,
proving that a transaction is part of a block requires:
As you can see from the table above, while the block size increases rapidly, from 4KB
with 16 transactions to a block size of 16 MB to fit 65,535 transactions, the merkle path
required to prove the inclusion of a transaction increases much more slowly, from 128
bytes to only 512 bytes. With merkle trees, a node can download just the block headers
(80 bytes per block) and still be able to identify a transactions inclusion in a block by
retrieving a small merkle path from a full node, without storing or transmitting the vast
majority of the blockchain which may be several gigabytes in size. Nodes which do not
maintain a full blockchain, called Simplified Payment Verification or SPV nodes use
merkle paths to verify transactions without downloading full blocks.
Introduction
Mining is the process by which new bitcoin is added to the money supply. Mining also
serves to secure the bitcoin system against fraudulent transactions or transactions
spending the same amount of bitcoin more than once, known as a double-spend. Miners
provide processing power to the bitcoin network in exchange for the opportunity to be
rewarded bitcoin.
Miners validate new transactions and record them on the global ledger. A new block,
containing transactions that occurred since the last block, is mined every 10 minutes,
thereby adding those transactions to the blockchain. Transactions that become part of
a block and added to the blockchain are considered confirmed, which allows the new
owners of bitcoin to spend the bitcoin they received in those transactions.
Miners receive two types of reward for mining: new coins created with each new block
and transaction fees from all the transactions included in the block. To earn this reward,
the miners compete to solve a difficult mathematical problem based on a cryptographic
hash algorithm. The solution to the problem, called the Proof-of-Work, is included in
the new block and acts as proof that the miner expended significant computing effort.
The competition to solve the Proof-of-Work algorithm to earn reward and the right to
record transactions on the blockchain is the basis for bitcoins security model.
The process of new coin generation is called mining, because the reward is designed to
simulate diminishing returns, just like mining for precious metals. Bitcoins money
supply is created through mining, similar to how a central bank issues new money by
printing bank notes. The amount of newly created bitcoin a miner can add to a block
decreases approximately every four years (or precisely every 210,000 blocks). It started
at 50 bitcoin per block in January of 2009 and halved to 25 bitcoin per block in November
of 2012. It will halve again to 12.5 bitcoin per block sometime in 2016. Based on this
formula, bitcoin mining rewards decrease exponentially until approximately the year
177
2140 when all bitcoin (20.99999998 million) will have been issued. After 2140, no new
bitcoins will be issued.
Bitcoin miners also earn fees from transactions. Every transaction may include a trans
action fee, in the form of a surplus of bitcoin between the transactions inputs and out
puts. The winning bitcoin miner gets to keep the change on the transactions included
in the winning block. Today, the fees represent 0.5% or less of a bitcoin miners income,
the vast majority coming from the newly minted bitcoins. However, as the reward de
creases over time and the number of transactions per block increases, a greater pro
portion of bitcoin mining earnings will come from fees. After 2140, all bitcoin miner
earnings will be in the form of transaction fees.
The word mining is somewhat misleading. By evoking the extraction of precious
metals, it focuses our attention on the reward for mining, the new bitcoins in each block.
While mining is incentivized by this reward, the primary purpose of mining is not the
reward or the generation of new coins. If you view mining only as the process by which
coins are created you are mistaking the means (incentives) as a goal of the process.
Mining is the main process of the de-centralized clearinghouse, by which transactions
are validated and cleared. Mining secures the bitcoin system and enables the emergence
of network-wide consensus without a central authority.
Mining is the invention that makes bitcoin special, a de-centralized security mechanism
that is the basis for peer-to-peer digital cash. The reward of newly minted coins and
transaction fees is an incentive scheme that aligns the actions of miners with the security
of the network, while simultaneously implementing the monetary supply.
In this chapter, we will first examine mining as a monetary supply mechanism and then
look at the most important function of mining, the de-centralized emergent consensus
mechanism that underpins bitcoins security.
def max_money():
# 50 BTC = 50 0000 0000 Satoshis
current_reward = 50 * 10**8
total = 0
while current_reward > 0:
total += reward_interval * current_reward
current_reward /= 2
return total
Introduction | 179
Figure 8-1. Supply of bitcoin currency over time based on a geometrically decreasing
issuance rate
The finite and diminishing issuance creates a fixed monetary supply that resists infla
tion. Unlike a fiat currency, which can be printed in infinite numbers by a central bank,
bitcoin can never be inflated by printing.
Deflationary Money
The most important and debated consequence of a fixed and diminishing monetary
issuance is that the currency will tend to be inherently deflationary. Deflation is the
phenomenon of appreciation of value due to a mismatch in supply and demand that
drives up the value (and exchange rate) of a currency. The opposite of inflation, price
deflation means that the money has more purchasing power over time.
Many economists argue that a deflationary economy is a disaster that should be avoided
at all costs. That is because in a period of rapid deflation people will tend to hoard money
instead of spending it, hoping that prices will fall. Such a phenomenon unfolded during
Japans Lost Decade, when a complete collapse of demand pushed the currency into a
deflationary spiral.
Bitcoin experts argue that deflation is not bad per se. Rather, deflation is associated with
a collapse in demand because that is the only example of deflation we have to study. In
a fiat currency with the possibility of unlimited printing, it is very difficult to enter a
deflationary spiral unless there is a complete collapse in demand and an unwillingness
De-centralized Consensus
In the previous chapter we looked at the blockchain, the global public ledger (list) of all
transactions, which everyone in the bitcoin network accepts as the authoritative record
of ownership.
But how can everyone in the network agree on a single universal truth about who
owns what, without having to trust anyone? All traditional payment systems depend on
a trust model that has a central authority providing a clearinghouse service, basically
verifying and clearing all transactions. Bitcoin has no central authority, yet somehow
every node has a complete copy of a public ledger that it can trust as the authoritative
record. The blockchain is not created by a central authority, but is assembled inde
pendently by every node in the network. Somehow, every node in the network, acting
on information transmitted across insecure network connections can arrive at the same
conclusion and assemble a copy of the same public ledger as everyone else. This chapter
examines the process by which the bitcoin network achieves global consensus without
central authority.
Satoshi Nakamotos main invention is the decentralized mechanism for emergent con
sensus. Emergent, because consensus is not achieved explicitly there is no election or
fixed moment when consensus occurs. Instead, consensus is an emergent artifact of the
asynchronous interaction of thousands of independent nodes, all following simple rules.
All the properties of bitcoin, including currency, transactions, payments, and the secu
rity model that does not depend on central authority or trust, derive from this invention.
Bitcoins de-centralized consensus emerges from the interplay of four processes that
occur independently on nodes across the network:
In the next few sections we will examine these processes and how they interact to create
the emergent property of network-wide consensus that allows any bitcoin node to as
semble its own copy of the authoritative, trusted, public, global ledger.
Mining Nodes
Some of the nodes on the bitcoin network are specialized nodes called miners. In Chap
ter 1 we introduced Jing, a computer engineering student in Shanghai, China, who is a
bitcoin miner. Jing earns bitcoin by running a mining rig, which is a specialized
computer-hardware system designed to mine bitcoins. Jings specialized mining hard
ware is connected to a server running a full bitcoin node. Unlike Jing, some miners mine
without a full node as we will see in Mining Pools on page 211. Like every other full
node, Jings node receives and propagates unconfirmed transactions on the bitcoin net
work. Jings node, however, also aggregates these transactions into new blocks.
Jings node is listening for new blocks, propagated on the bitcoin network, as do all
nodes. However, the arrival of a new block has special significance for a mining node.
The competition among miners effectively ends with the propagation of a new block
which acts as an announcement of a winner. To a miner, receiving a new block means
someone else won the competition and they lost. However, the end of one round of a
competition is also the beginning of the next round. The new block is not just a check
ered flag, marking the end of the race, it is also the starting pistol starting the race for
the next block.
],
"time" : 1388185914,
"nonce" : 924591752,
"bits" : "1903a30c",
"difficulty" : 1180923195.25802612,
"chainwork" : "000000000000000000000000000000000000000000000934695e92aaf53afa1a",
"previousblockhash" : "0000000000000002a7bbd25a417c0374cc55261021e8a9ca74442b01284f0569",
"nextblockhash" : "000000000000000010236c269dd6ed714dd5db39d36b33959079d78dfd431ba7"
}
Unlike regular transactions, the generation transaction does not consume (spend) UT
XO as inputs. Instead, it has only one input, called the coinbase, which creates bitcoin
from nothing. The generation transaction has one output, payable to the miners own
bitcoin address. The output of the generation transaction sends the value of 25.09094928
bitcoins to the miners bitcoin address, in this case 1MxTkeEP2PmHSMze5tUZ1hAV3YT
Ku2Gh1N.
// Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
nSubsidy >>= halvings;
The initial subsidy is calculated in satoshis by multiplying 50 with the COIN constant
(100,000,000 satoshis). This sets the initial reward (nSubsidy) at 5 billion satoshis.
Next, the function calculates the number of halvings that have occurred by dividing
the current block height by the halving interval (SubsidyHalvingInterval). In the case
of block 277,316, with a halving interval every 210,000 blocks, the result is 1 halving.
The maximum number of halvings allowed is 64, so the code imposes a zero reward
(return only the fees) if the 64 halvings is exceeded.
Next, the function uses the binary-right-shift operator to divide the reward (nSubsi
dy) by 2 for each round of halving. In the case of block 277,316 this would binary-right-
shift the reward of 5 billion satoshis once (one halving) and result in 2.5 billion satoshis,
or 25 bitcoin. The binary-right-shift operator is used because it is more efficient for
division by 2 than integer or floating point division.
Finally, the coinbase reward (nSubsidy) is added to the transaction fees (nFees), and
the sum is returned.
In a generation transaction, the first two fields are set to values that do not represent a
UTXO reference. Instead of a Transaction Hash, the first field is filled with 32 bytes
all set to zero. The Output Index is filled with 4 bytes all set to 0xFF (255 decimal).
The Unlocking Script is replaced by coinbase data, an arbitrary data field used by the
miners.
Coinbase Data
Generation transactions do not have an unlocking script (a.k.a. scriptSig) field. Instead,
this field is replaced by coinbase data, which must be between 2 and 100 bytes. Except
for the first few bytes (see below) the rest of the coinbase data can be used by miners in
any way they want; it is arbitrary data.
In the genesis block, for example, Satoshi Nakamoto added the text The Times 03/Jan/
2009 Chancellor on brink of second bailout for banks in the coinbase data, using it as
a proof of the date and to convey a message. Currently, miners use the coinbase data to
include extra nonce values and strings identifying the mining pool, as we will see in the
following sections.
The first few bytes of the coinbase used to be arbitrary, but that is no longer the case.
As per Bitcoin Improvement Proposal 34 (BIP0034), version-2 blocks (blocks with the
version field set to 2) must contain the block height index as a script push operation
in the beginning of the coinbase field.
int main()
{
// Create genesis block.
bc::block_type block = bc::genesis_block();
// Genesis block contains a single coinbase transaction.
assert(block.transactions.size() == 1);
// Get first transaction in block (coinbase).
const bc::transaction_type& coinbase_tx = block.transactions[0];
// Coinbase tx has a single input.
assert(coinbase_tx.inputs.size() == 1);
const bc::transaction_input_type& coinbase_input = coinbase_tx.inputs[0];
// Convert the input script to its raw format.
We compile the code with the GNU C++ compiler and run the resulting executable:
Example 8-7. Compiling and running the satoshi-words example code
$ # Compile the code
$ g++ -o satoshi-words satoshi-words.cpp $(pkg-config --cflags --libs libbitcoin)
$ # Run the executable
$ ./satoshi-words
^D<GS>^A^DEThe Times 03/Jan/2009 Chancellor on brink of second bailout for banks
At the time block 277,316 was mined, the version number describing the block structure
is version 2, which is encoded in little-endian format in 4 bytes as 0x02000000.
Next, the mining node needs to add the Previous Block Hash. That is the hash of the
block header of block 277,315, the previous block received from the network, which
Jings node has accepted and selected as the parent of the candidate block 277,316. The
block header hash for block 277,315 is
0000000000000002a7bbd25a417c0374cc55261021e8a9ca74442b01284f0569.
The next step is to summarize all the transactions with a Merkle Tree, in order to add
the Merkle Root to the block header. The generation transaction is listed as the first
transaction in the block. Then, 418 more transactions are added after it, for a total of
419 transactions in the block. As we saw in the Merkle Trees on page 170, there must
The example shows that if we calculate the hash of the phrase "I am Satoshi Nakamo
to", it will produce
5d7c7ba21cbbcd75d14800b100252d5b428e5b1213d27c385bc141ca6b47989e. This
256-bit number is the hash or digest of the phrase and depends on every part of the
phrase. Adding a single letter, punctuation mark or any character will produce a different
hash.
Now, if we change the phrase, we will expect to see completely different hashes. Lets try
that by adding a number to the end of our phrase, using this simple Python script
Example 8-9. SHA256 A script for generating many hashes by iterating on a nonce
# example of iterating a nonce in a hashing algorithm's input
import hashlib
Running this will produce the hashes of several phrases, made different by adding a
number at the end of the text. By incrementing the number, we can get different hashes.
Example 8-10. SHA256 Output of a script for generating many hashes by iterating on a
nonce
$ python hash_example.py
I am Satoshi Nakamoto0 => a80a81401765c8eddee25df36728d732...
I am Satoshi Nakamoto1 => f7bc9a6304a4647bb41241a677b5345f...
I am Satoshi Nakamoto2 => ea758a8134b115298a1583ffb80ae629...
I am Satoshi Nakamoto3 => bfa9779618ff072c903d773de30c99bd...
I am Satoshi Nakamoto4 => bce8564de9a83c18c31944a66bde992f...
I am Satoshi Nakamoto5 => eb362c3cf3479be0a97a20163589038e...
I am Satoshi Nakamoto6 => 4a2fd48e3be420d0d28e202360cfbaba...
I am Satoshi Nakamoto7 => 790b5a1349a5f2b909bf74d0d166b17a...
I am Satoshi Nakamoto8 => 702c45e5b15aa54b625d68dd947f1597...
I am Satoshi Nakamoto9 => 7007cf7dd40f5e933cd89fff5b791ff0...
I am Satoshi Nakamoto10 => c2f38c81992f4614206a21537bd634a...
I am Satoshi Nakamoto11 => 7045da6ed8a914690f087690e1e8d66...
I am Satoshi Nakamoto12 => 60f01db30c1a0d4cbce2b4b22e88b9b...
I am Satoshi Nakamoto13 => 0ebc56d59a34f5082aaef3d66b37a66...
I am Satoshi Nakamoto14 => 27ead1ca85da66981fd9da01a8c6816...
I am Satoshi Nakamoto15 => 394809fb809c5f83ce97ab554a2812c...
I am Satoshi Nakamoto16 => 8fa4992219df33f50834465d3047429...
I am Satoshi Nakamoto17 => dca9b8b4f8d8e1521fa4eaa46f4f0cd...
I am Satoshi Nakamoto18 => 9989a401b2a3a318b01e9ca9a22b0f3...
I am Satoshi Nakamoto19 => cda56022ecb5b67b2bc93a2d764e75f...
Each phrase produces a completely different hash result. They seem completely random,
but you can re-produce the exact results in this example on any computer with Python
and see the same exact hashes.
The number used as a variable in such a scenario is called a nonce. The nonce is used
to vary the output of a cryptographic function, in this case to vary the SHA-256 finger
print of the phrase.
To make a challenge out of this algorithm, lets set an arbitrary target: find a phrase that
produces a hexadecimal hash that starts with a zero. Fortunately, this isnt so difficult!
If you notice above, we can see that the phrase I am Satoshi Nakamoto13 produces
the hash 0ebc56d59a34f5082aaef3d66b37a661696c2b618e62432727216ba9531041a5,
which fits our criteria. It took 13 attempts to find it. In terms of probabilities, if the
output of the hash function is evenly distributed we would expect to find a result with
a 0 as the hexadecimal prefix once every 16 hashes (one out of 16 hexadecimal digits 0
through F). In numerical terms, that means finding a hash value that is less than
import hashlib
import time
max_nonce = 2 ** 32 # 4 billion
if __name__ == '__main__':
nonce = 0
hash_result = ''
difficulty = 2 ** difficulty_bits
print "Difficulty: %ld (%d bits)" % (difficulty, difficulty_bits)
# make a new block which includes the hash from the previous block
# we fake a block of transactions - just a string
new_block = 'test block with transactions' + hash_result
if elapsed_time > 0:
Running the code above, you can set the desired difficulty (in bits, how many of the
leading bits must be zero) and see how long it takes for your computer to find a solution.
In the following examples, you can see how it works on an average laptop:
[...]
Difficulty: 8 (3 bits)
Starting search...
Success with nonce 9
Hash is 1c1c105e65b47142f028a8f93ddf3dabb9260491bc64474738133ce5256cb3c1
Elapsed Time: 0.0004 seconds
Hashing Power: 25065 hashes per second
Difficulty: 16 (4 bits)
Starting search...
Success with nonce 25
Hash is 0f7becfd3bcd1a82e06663c97176add89e7cae0268de46f94e7e11bc3863e148
Elapsed Time: 0.0005 seconds
Hashing Power: 52507 hashes per second
Difficulty: 32 (5 bits)
Starting search...
Success with nonce 36
Hash is 029ae6e5004302a120630adcbb808452346ab1cf0b94c5189ba8bac1d47e7903
Elapsed Time: 0.0006 seconds
Hashing Power: 58164 hashes per second
[...]
[...]
As you can see, increasing the difficulty by 1 bit causes an exponential increase in the
time it takes to find a solution. If you think of the entire 256-bit number space, each
time you constrain one more bit to zero, you decrease the search space by half. In the
example above, it takes 84 million hash attempts to find a nonce that produces a hash
with 26 leading bits as zero. Even at a speed of more than 120 thousand hashes per
second, it still requires ten minutes on a consumer laptop to find this solution.
At the time of writing this, the network is attempting to find a block whose header hash
is less than
000000000000004c296e6376db3a241271f43fd3f5de7ba18986e517a243baa7. As you
can see, there are a lot of zeroes at the beginning of that hash, meaning that the acceptable
range of hashes is much smaller, hence more difficult to find a valid hash. It will take
on average more than 150 quadrillion hash calculations per second for the network to
discover the next block. That seems like an impossible task, but fortunately the network
is bringing 100 Peta Hashes per second of processing power to bear, which will be able
to find a block in about 10 minutes on average.
Difficulty Representation
In Example 8-3 we saw that the block contains the difficulty target, in a notation called
difficulty bits or just bits, which in block 277,316 has the value of 0x1903a30c. This
notation expresses the difficulty target as a coefficient/exponent format, with the first
two hexadecimal digits for the exponent and the next six hex digits as the coefficient.
In this block, therefore, the exponent is 0x19 and the coefficient is 0x03a30c.
The formula to calculate the difficulty target from this representation is:
target = coefficient * 2^(8 * (exponent - 3))
Using that formula, and the difficulty bits value 0x1903a30c, we get:
target = 0x03a30c * 2(0x08 * (0x19 - 0x03))
target = 0x03a30c * 2(0x08 * 0x16)
target = 0x03a30c * 20xB0
which in decimal is:
target = 238,348 * 2176
target =
22,829,202,948,393,929,850,749,706,076,701,368,331,072,452,018,388,575,715,328
// Retarget
uint256 bnNew;
uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nActualTimespan;
bnNew /= Params().TargetTimespan();
The parameters Interval (2016 blocks) and TargetTimespan (two weeks as 1,209,600
seconds) are defined in chainparams.cpp
To avoid extreme volatility in the difficulty, the retargeting adjustment must be less than
a factor of four (4) per cycle. If the required difficulty adjustment is greater than a factor
of four, it will be adjusted by the maximum and not more. Any further adjustment will
be accomplished in the next retargeting period as the imbalance will persist through the
next 2016 blocks. Therefore, large discrepancies between hashing power and difficulty
may take several 2016 block cycles to balance out.
Note that the target difficulty is independent of the number of transactions or the value
of transactions. This means that the amount of hashing power and therefore electricity
expended to secure bitcoin is also entirely independent of the number of transactions.
Bitcoin can scale up, achieve broader adoption and remain secure without any increase
The independent validation of each new block by every node on the network ensures
that the miners cant cheat. In previous sections we saw how the miners get to write a
transaction that awards them the new bitcoins created within the block and claim the
transaction fees. Why doesnt the miner write themselves a transaction for a thousand
bitcoin instead of the correct reward? Because every node validates blocks according to
the same rules. An invalid coinbase transaction would make the entire block invalid,
which would result in the block being rejected and therefore that transaction would
never become part of the ledger. The miner has to construct a perfect block, based on
the shared rules that all nodes follow and mine it with a correct solution to the Proof-
of-Work. To do so they expend a lot of electricity in mining and if they cheat all the
electricity and effort is wasted. This is why independent validation is a key component
of decentralized consensus.
Figure 8-3. Visualization of a blockchain fork event - Two blocks found simultaneously
Lets assume for example that a miner in Canada finds a Proof-of-Work solution for a
block red that extends the blockchain, building on top of the parent block blue.
Almost simultaneously, an Australian miner who was also extending block blue, finds
a solution for block green, their candidate block. Now, there are two possible blocks,
one we call red, originating in Canada and one we call green, originating in Australia.
Both blocks are valid, both blocks contain a valid solution to the proof of work, both
Figure 8-4. Visualization of a blockchain fork event - Two blocks propagate, splitting
the network
From that moment, the bitcoin network nodes closest (topologically, not geographi
cally) to the Canadian node will hear about block red first and will create a new
greatest-cumulative-difficulty blockchain with red as the last block in the chain (e.g.
blue-red), ignoring the candidate block green that arrives a bit later. Meanwhile, nodes
closer to the Australian node will take that block as the winner and extend the blockchain
with green as the last block (e.g. blue-green), ignoring red when it arrives a few
seconds later. Any miners that saw red first will immediately build candidate blocks
that reference red as the parent and start trying to solve the PoW for these candidate
blocks. The miners that accepted green instead, will start building on top of green
and extending that chain.
Forks are almost always resolved within one block. As part of the networks hashing
power is dedicated to building on top of red as the parent, another part of the hashing
power is focused on building on top of green. Even if the hashing power is almost
evenly split, it is likely that one set of miners will find a solution and propagate it before
the other set of miners have found any solutions. Lets say for example that the miners
building on top of green find a new block pink that extends the chain (e.g. blue-
green-pink). They immediately propagate this new block and the entire network sees it
as a valid solution.
All nodes that had chosen green as the winner in the previous round will simply extend
the chain one more block. The nodes that chose red as the winner, however, will now
see two chains: blue-green-pink and blue-red. The chain blue-green-pink is now longer
(more cumulative difficulty) than the chain blue-red. As a result, those nodes will set
the chain blue-green-pink as main chain and change the blue-red chain to being a
secondary chain. This is a chain re-convergence, as those nodes are forced to revise their
view of the blockchain to incorporate the new evidence of a longer chain. Any miners
working on extending the chain blue-red will now stop that work because their candi
date block is an orphan, as its parent red is no longer on the longest chain. The
transactions within red are queued up again for processing in the next block, as that
block is no longer in the main chain. The entire network re-converges on a single
blockchain blue-green-pink, with pink as the last block in the chain. All miners im
mediately start working on candidate blocks that reference pink as their parent to
extend the blue-green-pink chain.
It is theoretically possible for a fork to extend to two blocks, if two blocks are found
almost simultaneously by miners on opposite sides of a previous fork. However, the
chance of that happening is very low. Whereas a one-block fork may occur every week,
a two-block fork is exceedingly rare.
Bitcoins block interval of 10 minutes is a design compromise between fast confirmation
times (settlement of transactions) and the probability of a fork. A faster block time would
make transactions clear faster but lead to more frequent blockchain forks, whereas a
slower block time would decrease the number of forks but make settlement slower.
In the chart below, we see the bitcoin networks hashing power increase over the past
two years. As you can see, the competition between miners and the growth of bitcoin
has resulted in an exponential increase in the hashing power (total hashes per second
across the network):
Figure 8-7. Total hashing power, giga-hashes per second, over two years
In the last two years, the ASIC mining chips have become denser and denser, approach
ing the cutting edge of silicon fabrication with a feature size (resolution) of 22 nano
meters (nm). Currently, ASIC manufacturers are aiming to overtake general purpose
CPU chip manufacturers, designing chips with a feature size of 16nm, because the
profitability of mining is driving this industry even faster than general computing. There
are no more giant leaps left in bitcoin mining, because the industry has reached the
forefront of Moores Law. Still, the mining power of the network continues to advance
at an exponential pace as the race for higher density chips is matched with a race for
higher density data centers where thousands of these chips can be deployed. Its no
longer about how much mining can be done with one chip but how many chips can be
squeezed into a building, while still dissipating the heat and providing adequate power.
Mining Pools
In this highly competitive environment, individual miners working alone (also known
as solo miners) dont stand a chance. The likelihood of them finding a block to offset
their electricity and hardware costs is so low that it represents a gamble, like playing the
lottery. Even the fastest consumer ASIC mining system cannot keep up with commercial
systems that stack tens of thousands of these chips in giant warehouses near hydro-
electric power stations. Miners now collaborate to form mining pools, pooling their
hashing power and sharing the reward among thousands of participants. By partici
pating in a pool, miners get a smaller share of the overall reward, but typically get
rewarded every day, reducing uncertainty.
Lets look at a specific example. Assume a miner has purchased mining hardware with
a combined hashing rate of 6,000 giga-hashes per second (GH/s) or 6 TH/s. In August
of 2014 this equipment costs approximately $10,000 USD. The hardware also consumes
3 kilowatts (kW) of electricity when running, 72 kW-hours a day, at a cost of $7 or $8
per day on average. At current bitcoin difficulty, the miner will be able to solo-mine a
block approximately once every 155 days, or every 5 months. If the miner does find a
single block in that timeframe, the payout of 25 bitcoin, at approximately $600 per
bitcoin will result in a single payout of $15,000 which will cover the entire cost of the
hardware and the electricity consumed over the time period, leaving a net profit of
approximately $3,000. However, the chance of finding a block in a 5-month period
depends on the miners luck. They might find two blocks in 5 months and make a very
large profit. Or they might not find a block for 10 months and suffer a financial loss.
Even worse, the difficulty of the bitcoin proof-of-work algorithm is likely to go up
significantly over that period, at the current rate of growth of hashing power, meaning
the miner has at most 6 months to break-even before the hardware is effectively obsolete
and must be replaced by more powerful mining hardware. If this miner participates in
Managed Pools
Most mining pools are managed, meaning that there is a company or individual run
ning a pool server. The owner of the pool server is called the pool operator and they
charge pool miners a percentage fee of the earnings.
The pool server runs specialized software and a pool-mining protocol that coordinates
the activities of the pool miners. The pool server is also connected to one or more full
bitcoin nodes and has direct access to a full copy of the blockchain database. This allows
the pool server to validate blocks and transactions on behalf of the pool miners, relieving
them of the burden of running a full node. For pool miners, this is an important con
sideration, as a full node requires a dedicated computer with at least 15-20 gigabytes of
persistent storage (disk) and at least 2 gigabytes of memory (RAM). Furthermore, the
bitcoin software running on the full node needs to be monitored, maintained and up
graded frequently. Any downtime caused by a lack of maintenance or lack of resources
will impact the miners profitability. For many miners the ability to mine without run
ning a full node is another big benefit of joining a managed pool.
Pool miners connect to the pool server using a mining protocol such as Stratum (STM)
or GetBlockTemplate (GBT). An older standard called GetWork (GWK) is now mostly
obsolete since late 2012, as it does not easily support mining at hash rates above 4 GH/
s. Both the STM and GBT protocols create block templates that contain a template of a
candidate block header. The pool server constructs a candidate block by aggregating
transactions, adding a coinbase transaction (with extra nonce space), calculating the
merkle root and linking to the previous block hash. The header of the candidate block
is then sent to each of the pool miners as a template. Each pool miner then mines using
the block template, at a lower difficulty than the bitcoin network difficulty and sends
any successful results back to the pool server to earn shares.
Consensus Attacks
Bitcoins consensus mechanism is, at least theoretically, vulnerable to attack by miners
(or pools) that attempt to use their hashing power to dishonest or destructive ends. As
Bitcoin was the result of twenty years of research in distributed systems and currencies
and brought a revolutionary new technology into the space: the de-centralized consen
sus mechanism based on Proof-of-Work. This invention at the heart of bitcoin has
ushered a wave of innovation in currencies, financial services, economics, distributed
systems, voting systems, corporate governance, and contracts.
In this chapter well examine the many offshoots of the bitcoin and blockchain inven
tions, the alternative chains, currencies, and applications built since the introduction of
this technology in 2009. Mostly, we will look at alt-coins, which are digital currencies
implemented using the same design pattern as bitcoin, but with a completely separate
blockchain and network.
For every alt-coin mentioned in this chapter, 50 or more will go unmentioned, eliciting
howls of anger from their creators and fans. The purpose of this chapter is not to evaluate
or qualify alt-coins, or to mention the most significant ones based on some subjective
assessment. Instead, we will highlight a few examples that show the breadth and variety
of the ecosystem, noting the first-of-a-kind for each innovation or significant differen
tiation. Some of the most interesting examples of alt-coins are in fact complete failures
from a monetary perspective. That perhaps makes them even more interesting for study
and highlights the fact that this chapter is not to be used as an investment guide.
With new coins introduced every day, it would be impossible not to miss some important
coin, perhaps the one that changes history. The rate of innovation is what makes this
space so exciting and guarantees this chapter will be incomplete and out-of-date as soon
as it is published.
219
A taxonomy of alternative currencies and chains
Bitcoin is an open source project, and its code has been used as the basis for many other
software projects. The most common form of software spawned from bitcoins source
code are alternative de-centralized currencies, or alt-coins, which use the same basic
building blocks to implement digital currencies.
There are a number of protocol layers implemented on top of bitcoins blockchain. These
meta-coins, meta-chains, or blockchain apps use the blockchain as an application plat
form or extend the bitcoin protocol by adding protocol layers. Examples include Col
ored Coins, Mastercoin, and Counterparty.
In the next section we will examine a few notable alt-coins, such as Litecoin, Dogecoin,
Freicoin, Primecoin, Peercoin, Darkcoin, and Zerocoin. These alt-coins are notable for
historical reasons or because they are good examples for a specific type of alt-coin in
novation, not because they are the most valuable or best alt-coins.
In addition to the alt-coins, there are also a number of alternative blockchain imple
mentations that are not really coins, which I call alt-chains. These alt-chains implement
a consensus algorithm and distributed ledger as a platform for contracts, name regis
tration, or other applications. Alt-chains use the same basic building blocks and some
times also use a currency or token as a payment mechanism, but their primary purpose
is not currency. We will look at Namecoin, Ethereum, and NXT as examples of alt-
chains.
In addition to the Proof-of-Work consensus mechanism used in bitcoin, alternatives
include experimental protocols based on Proof-of-Resource and Proof-of-Publishing.
We will examine Maidsafe and Twister as examples of these consensus mechanisms.
Finally, there are a number of bitcoin contenders that offer digital currency or digital
payment networks, but without using a de-centralized ledger or consensus mechanism
based on Proof-of-Work, such as Ripple and others. These non-blockchain technologies
are outside of the scope of this book and will not be covered in this chapter.
Meta-Coin Platforms
Meta-coins and meta-chains are software layers implemented on top of bitcoin, either
implementing a currency-inside-a-currency, or a platform/protocol overlay inside the
bitcoin system. These function layers extend the core bitcoin protocol and add features
and capabilities by encoding additional data inside bitcoin transactions and bitcoin
addresses. The first implementations of meta-coins used various hacks to add meta-
data to the bitcoin blockchain, such as using bitcoin addresses to encode data or using
unused transaction fields (e.g. the transaction sequence field) to encode meta-data about
the added protocol layer. Since the introduction of the OP_RETURN transaction script
Colored Coins
Colored Coins is a meta-protocol that overlays information on small amounts of bitcoin.
A colored coin is an amount of bitcoin repurposed to express another asset. Imagine
for example taking a $1 USD note and putting a stamp on it that said This is a 1 share
certificate of Acme Inc.. Now the $1 serves two purposes: it is a currency note and also
a share certificate. Because it is more valuable as a share, you would not want to use it
to buy candy, so effectively it is no longer useful as currency. Colored coins work in the
same way by converting a specific, very small, amount of bitcoin into a traded certificate
that represents another asset. The term color refers to the idea of giving special mean
ing through the addition of an attribute such as a color - it is a metaphor not an actual
color association. There are no colors in colored coins.
Colored coins are managed by specialized wallets that record and interpret the met
adata attached to the colored bitcoins. Using such a wallet, the user will convert an
amount of bitcoins from uncolored currency, into colored coins, by adding a label that
has a special meaning. For example, a label could represent stock certificates, coupons,
real property, commodities, collectible tokens, etc. It is entirely up to the users of colored
coins to assign and interpret the meaning of the color associated with specific coins.
To color the coins, the user defines the associated metadata, such as the type of issuance,
whether it can be subdivided into smaller units, a symbol and description, and other
related information. Once colored, these coins can be bought and sold, subdivided,
aggregated and receive dividend payments. The colored coins can also be uncolored
by removing the special association and redeem them for their face-value in bitcoin.
To demonstrate the use of colored coins, we have created a set of 20 colored coins with
symbol MasterBTC that represent coupons for a free copy of this book. Each unit of
MasterBTC, represented by these colored coins, can now be sold or given to any bitcoin
user with a colored-coin-capable wallet, who can then transfer them to others or redeem
them with the issuer for a free copy of the book. This example of colored coins can be
seen here: https://cpr.sm/FoykwrH6UY
Example 9-1. The metadata profile of the colored coins recorded as a coupon for a free
copy of the book
{
"source_addresses": [
"3NpZmvSPLmN2cVFw1pY7gxEAVPCVfnWfVD"
],
"contract_url": "https://www.coinprism.info/asset/3NpZmvSPLmN2cVFw1pY7gxEAVPCVfnWfVD",
"name_short": "MasterBTC",
"name": "Free copy of \"Mastering Bitcoin\"",
"issuer": "Andreas M. Antonopoulos",
Mastercoin
Mastercoin is a protocol layer on top of bitcoin that supports a platform for various
applications extending the bitcoin system. Mastercoin uses the currency MST as a token
for conducting Mastercoin transactions but it is not primarily a currency. Rather it is a
platform for building other things, such as user currencies, smart property tokens, de-
centralized asset exchanges, contracts, etc. Think of Mastercoin as an application-layer
protocol on top of bitcoins financial transaction transport-layer, just like HTTP runs
on top of TCP.
Mastercoin operates primarily through transactions sent to and from a special bitcoin
address called the exodus address (1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P), just like
HTTP uses a specific TCP port (port 80) to differentiate its traffic from the rest of the
TCP traffic. The Mastercoin protocol is gradually transitioning from using the speci
alized exodus address and multi-signatures to using the OP_RETURN bitcoin operator
to encode transaction metadata.
Counterparty
Counterparty is another protocol layer implemented on top of bitcoin. Counterparty
enables user currencies, tradable tokens, financial instruments, de-centralized asset ex
changes, and other features. Counterparty is implemented primarily using the OP_RE
TURN operator in bitcoins scripting language to record metadata enhancing bitcoin
transactions with additional meaning. Counterparty uses the currency XCP as a token
for conducting Counterparty transactions.
Alt-coins
The vast majority of alt-coins are derived from bitcoins source code, also known as
forks. Some are implemented from scratch based on the blockchain model but
without using any of bitcoins source code. Alt-coins and alt-chains (in the next section)
are both separate implementations of blockchain technology and both forms use their
own blockchain. The difference in the terms is to indicate that alt-coins are primarily
used as currency, whereas alt-chains are used for other purposes, not primarily currency.
Alt-coins | 223
Evaluating an alt-coin
With so many alt-coins out there, how does one decide which ones are worthy of at
tention? Some alt-coins attempt to achieve broad distribution and use as currencies.
Others are laboratories for experimenting on different features and monetary models.
Many are just get-rich-quick schemes by their creators. To evaluate alt-coins I look at
their defining characteristics and their market metrics.
Here are some questions to ask about how well an alt-coin differentiates from bitcoin:
Here are some of the key financial and market metrics to examine:
In this chapter we will concentrate primarily on the technical characteristics and inno
vation potential of alt-coins, focusing on the first set of questions.
Dogecoin
Dogecoin was released in December of 2013, based on a fork of Litecoin. Dogecoin is
notable because it has a monetary policy of rapid issuance and a very high currency cap,
to encourage spending and tipping. Dogecoin is also notable because it was started as
a joke but became quite popular, with a large and active community, before declining
rapidly in 2014.
Freicoin
Freicoin was introduced in July 2012. It is a demurrage currency, meaning that it has a
negative interest rate for stored value. Value stored in Freicoin is assessed a 4.5% APR
fee, to encourage consumption and discourage hoarding of money. Freicoin is notable
in that it implements a monetary policy that is the exact opposite of Bitcoins deflationary
policy. Freicoin has not seen success as a currency, but is an interesting example of the
variety of monetary policies that can be expressed by alt-coins.
Alt-coins | 225
for Proof-of-Work. In 2013 we saw the invention of an alternative to Proof-of-Work,
called Proof-of-Stake, which forms the basis of many modern alt-coins.
Proof-of-Stake is a system by which existing owners of a currency can stake currency
as interest-bearing collateral. Somewhat like a Certificate of Deposit (CD), participants
can reserve a portion of their currency holdings, while earning an investment return in
the form of new currency (issued as interest payments) and transaction fees.
Peercoin
Peercoin was introduced in August of 2012 and is the first alt-coin to use a hybrid Proof-
of-Work and Proof-of-Stake algorithm for issuance of new currency.
Myriad
Myriad was introduced in February 2014 and is notable because it uses five different
Proof-of-Work algorithms (SHA256d, Scrypt, Qubit, Skein or Myriad-Groestl) simul
taneously, with difficulty varying for each algorithm depending on miner participation.
The intent is to make Myriad immune to ASIC specialization and centralization as well
as much more resistant to consensus attacks, as multiple mining algorithms would have
to be attacked simultaneously.
Block generation: 30 second average (2.5 minutes target per mining algorithm)
Total currency: 2 billion by 2024
Consensus algorithm: Multi-Algorithm Proof-of-Work
Market capitalization: $120,000 USD in mid-2014
Blackcoin
Blackcoin was introduced in February 2014 and uses a Proof-of-Stake consensus algo
rithm. It is also notable for the introduction of multipools, a type of mining pool that
can switch between different alt-coins automatically, depending on profitability.
NXT
NXT (pronounced Next) is a pure Proof-of-Stake alt-coin, in that it does not use
Proof-of-Work mining. NXT is a from-scratch implementation of a crypto-currency,
not a fork of bitcoin or any other alt-coins. NXT implements many advanced features,
such as a name registry (similar to Namecoin), a de-centralized asset exchange (similar
to Colored Coins), integrated de-centralized and secure messaging (similar to Bitmes
sage) and stake delegation (delegate Proof-of-Stake to others). NXT adherents call it a
next-generation or 2.0 crypto-currency.
Alt-coins | 227
prime numbers, thereby producing a public record of scientific discovery in parallel to
the public ledger of transactions.
Curecoin
Curecoin was announced in May 2013. It combines a SHA256 Proof-of-Work algorithm
with protein folding research through the Folding@Home project. Protein folding is a
computationally intensive simulation of biochemical interactions of proteins, used to
discover new drug targets for curing diseases.
Gridcoin
Gridcoin was introduced in October 2013. It supplements scrypt-based Proof-of-Work
with subsidies for participation in BOINC open grid-computing. BOINC is an open
protocol for scientific research grid-computing, which allows participants to share their
spare computing cycles for a broad range of academic research computing. Gridcoin
uses BOINC as a general purpose computing platform, rather than to solve specific
science problems such as prime numbers or protein folding.
Monero
Alt-coins | 229
Monero is another implementation of CryptoNote. It has a slightly flatter issuance curve
than Bytecoin, issuing 80% of the currency in the first 4 years. It offers the same ano
nymity features inherited from CryptoNote.
Darkcoin
Darkcoin was launched in January of 2014. Darkcoin implements anonymous currency
using a re-mixing protocol for all transactions called DarkSend. Darkcoin is also notable
for using 11 rounds of different hash functions (blake, bmw, groestl, jh, keccak, skein,
luffa, cubehash, shavite, simd, echo) for the Proof-of-Work algorithm.
Non-currency alt-chains
Alt-chains are alternative implementations of the blockchain design pattern, which are
not primarily used as currency. Many include a currency, but the currency is used as a
token for allocating something else, such as a resource or a contract. The currency, in
other words, is not the main point of the platform, it is a secondary feature.
Namecoin
Namecoin was the first fork of the bitcoin code. Namecoin is a de-centralized key-
value registration and transfer platform using a blockchain. It supports a global domain
name registry similar to the domain-name registration system on the Internet. Name
coin is currently used as an alternative Domain Name Service (DNS) for the root-level
domain .bit. Namecoin can also be used to register names and key-value pairs in other
namespaces, for storing things like email addresses, encryption keys, SSL certificates,
file signatures, voting systems, stock certificates and a myriad of other applications.
The Namecoin system includes the namecoin currency (symbol NMC), which is used
to pay transaction fees for registration and transfer of names. At current prices, the fee
Namecoins namespaces are not restricted, and anyone can use any namespace in any
way. However, certain namespaces have an agreed upon specification so that when it is
read from the blockchain, software knows how to read and proceed from there. If it is
malformed, then whatever software you used to read from the specific namespace will
throw an error. Some of the popular namespaces are:
The Namecoin client is very similar to Bitcoin Core, as it is derived from the same source
code. Upon installation, the client will download a full copy of the namecoin blockchain
and then will be ready to query and register names. There are three main commands:
The name_new command registers a claim on the name, by creating a hash of the name
with a random key. The two strings returned by name_new are the hash and the random
key (a05555e0fc56c023 in the example above) that can be used to make the name reg
istration public. Once that claim has been recorded on the namecoin blockchain it can
Bitmessage
Bitmessage is a bitcoin alt-chain that implements a de-centralized secure messaging
service, essentially a server-less encrypted email system. Bitmessage allows users to
compose and send messages to each other, using a bitmessage address. The messages
operate in much the same way as a bitcoin transaction, but they are transient - they do
not persist beyond 2 days and if not delivered to the destination node in that time, they
are lost. Senders and recipients are pseudonymous, they have no identifiers other than
a bitmessage address, but are strongly authenticated, meaning that messages cannot be
spoofed. Bitmessages are encrypted to the recipient and therefore the bitmessage net
work is resistant to holistic surveillance - an eavesdropper has to compromise the re
cipients device in order to intercept messages.
Ethereum
Ethereum is a Turing-complete contract processing and execution platform based on a
blockchain ledger. It is not a clone of bitcoin, but a completely independent design and
implementation. Ethereum has a built-in currency, called ether, which is required in
Future of Currencies
The future of cryptographic currencies overall is even brighter than the future of bitcoin.
Bitcoin introduced a completely new form of de-centralized organization and consensus
that has spawned hundreds of incredible innovations. These inventions will likely affect
broad sectors of the economy, from distributed systems science, to finance, economics,
currencies, central banking, and corporate governance. Many human activities that
previously required centralized institutions or organizations to function as authoritative
or trusted points of control can now be de-centralized. The invention of the blockchain
and consensus system will significantly reduce the cost of organization and coordination
on large scale systems, while removing opportunities for concentration of power, cor
ruption and regulatory capture.
Securing bitcoin is challenging because bitcoin is not an abstract reference to value, like
a balance in a bank account. Bitcoin is very much like digital cash or gold. Youve prob
ably heard the expression Possession is nine tenths of the law. Well, in bitcoin, pos
session is ten tenths of the law. Possession of the keys to unlock the bitcoin, is equivalent
to possession of cash or a chunk of precious metal. You can lose it, misplace it, have it
stolen or accidentally give the wrong amount to someone. In every one of those cases,
the end-user would have no recourse, just as if they dropped cash on a public sidewalk.
However, bitcoin has capabilities that cash, gold and bank accounts do not. A bitcoin
wallet, containing your keys, can be backed up like any file. It can be stored in multiple
copies, even printed on paper for hard-copy backup. You cant backup cash, gold or
bank accounts. Bitcoin is different enough from anything that has come before that we
need to think about bitcoin security in a novel way too.
Security principles
The core principle in bitcoin is de-centralization and it has important implications for
security. A centralized model, such as a traditional bank or payment network, depends
on access control and vetting to keep bad actors out of the system. By comparison, a
de-centralized system like bitcoin pushes the responsibility and control to the end-users.
Since security of the network is based on Proof-of-Work, not access control, the network
can be open and no encryption is required for bitcoin traffic.
On a traditional payment network, such a credit card system, the payment is really
open-ended because it contains the users private identifier (the credit card number).
After the initial charge, anyone with access to the identifier can pull funds and charge
the owner again and again. Thus, the payment network has to be secured end-to-end
with encryption and must ensure that no eavesdroppers or intermediaries can com
promise the payment traffic, in transit or when it is stored (at rest). If a bad actor gains
235
access to the system, they can compromise current transactions and payment tokens
that can be used to create new transactions. Worse, when customer data is compromised,
the customers are exposed to identity theft and must take action to prevent fraudulent
use of the compromised accounts.
Bitcoin is dramatically different. A bitcoin transaction authorizes only a specific value
to a specific recipient and cannot be forged or modified. It does not reveal any private
information, such as the identities of the parties and cannot be used to authorize addi
tional payments. Therefore, a bitcoin payment network does not need to be encrypted
or protected from eavesdropping. In fact, you can broadcast bitcoin transactions over
an open public channel, such as unsecured Wifi or Bluetooth, with no loss of security.
Bitcoins de-centralized security model puts a lot of power in the hands of the end-users.
With that power comes responsibility for maintaining the secrecy of the keys. For most
users that is not easy to do, especially on general purpose computing devices, such as
Internet-connected smartphones or laptops. Whereas bitcoins de-centralized model
prevents the type of mass compromise seen with credit cards, many end-users are not
able to adequately secure their keys and get hacked one by one.
Hardware Wallets
In the longer term, bitcoin security will increasingly be implemented with hardware
tamper-proof wallets. Unlike a smartphone or desktop computer, a purpose-built bit
coin hardware wallet has only one purpose and function - holding bitcoins securely.
Without general purpose software to compromise and with limited interfaces, hardware
wallets can deliver an almost foolproof level of security to non-expert users. I expect to
see hardware wallets becoming the predominant method of bitcoin storage. For an
example of such a hardware wallet, see the Trezor (http://www.bitcointrezor.com/)
Diversifying Risk
Would you carry your entire net-worth in cash in your wallet? Most people would
consider that reckless, yet bitcoin users often keep all their bitcoin in a single wallet.
Instead, users should spread the risk among multiple and diverse bitcoin wallets. The
prudent user will keep only a small fraction, perhaps less than 5%, of their bitcoins in
Survivability
One important security consideration that is often overlooked is availability, especially
in the context of incapacity or death of the key holder. Bitcoin users are told to use
complex passwords and keep their keys secure and private, not sharing them with any
one. Unfortunately, that practice makes it almost impossible for the users family to
recover any funds if the user is not available to unlock them. In most cases in fact, the
families of bitcoin users may be completely unaware of the existence of bitcoin funds.
If you have a lot of bitcoin, you should consider sharing access details with a trusted
relative or lawyer. A more complex survivability scheme can be setup with multi-
signature access and estate planning through a lawyer specialized as a digital asset
executor.
Conclusion
Bitcoin is a completely new, unprecedented and complex technology. Over time we will
develop better security tools and practices that are easier to use by non-experts. For
now, bitcoin users can use many of the tips above to enjoy a secure and trouble-free
bitcoin experience.
DEPRECATED
ELECTRUM STYLE DETERMINISTIC KEYS AND ADDRESSES
genaddr Generate a Bitcoin address deterministically from a wallet
seed or master public key.
genpriv Generate a private key deterministically from a seed.
genpub Generate a public key deterministically from a wallet
seed or master public key.
mpk Extract a master public key from a deterministic wallet seed.
newseed Create a new deterministic wallet seed.
EXPERIMENTAL
APPS
wallet Experimental command line wallet.
OFFLINE BLOCKCHAIN
HEADERS
showblkhead Show the details of a block header.
241
hd-pub Create an HD public key from another HD private or public key.
hd-seed Create a random new HD key.
hd-to-address Convert an HD public or private key to a Bitcoin address.
hd-to-wif Convert an HD private key to a WIF private key.
MULTISIG ADDRESSES
scripthash Create BIP 16 script hash address from raw script hex.
STEALTH
stealth-addr See a stealth address from given input.
stealth-initiate Initiate a new stealth payment.
stealth-newkey Generate new stealth keys and an address.
stealth-show-addr Show details for a stealth address.
stealth-uncover Uncover a stealth address.
stealth-uncover-secret Uncover a stealth secret.
OFFLINE TRANSACTIONS
SCRIPTING
mktx Create an unsigned tx.
rawscript Create the raw hex representation from a script.
set-input Set a transaction input.
showscript Show the details of a raw script.
showtx Show the details of a transaction.
sign-input Sign a transaction input.
unwrap Validates checksum and recovers version byte and original data from hexstring.
validsig Validate a transaction input's signature.
wrap Adds version byte and checksum to hexstring.
ONLINE (BLOCKCHAIN.INFO)
BLOCKCHAIN QUERIES (blockchain.info)
bci-fetch-last-height Fetch the last block height using blockchain.info.
bci-history Get list of output points, values, and their spends
from blockchain.info
BLOCKCHAIN UPDATES
sendtx-bci Send tx to blockchain.info/pushtx.
ONLINE (BLOCKEXPLORER.COM)
BLOCKCHAIN QUERIES (blockexplorer.com)
blke-fetch-transaction Fetches a transaction from blockexplorer.com
ONLINE (OBELISK)
BLOCKCHAIN QUERIES
balance Show balance of a Bitcoin address in satoshis.
fetch-block-header Fetch raw block header.
fetch-last-height Fetch the last block height.
fetch-stealth Fetch a stealth information using a network connection to
make requests against the obelisk load balancer backend.
fetch-transaction Fetch a raw transaction using a network connection to
make requests against the obelisk load balancer backend.
UTILITY
EC MATH
ec-add-modp Calculate the result of INTEGER + INTEGER.
ec-multiply Multiply an integer and a point together.
ec-tweak-add Calculate the result of POINT + INTEGER * G.
FORMAT (BASE 58)
base58-decode Convert from base58 to hex
base58-encode Convert from hex to base58
FORMAT (BASE58CHECK)
base58check-decode Convert from base58check to hex
base58check-encode Convert from hex to base58check
decode-addr Decode a address from base58check form to internal RIPEMD representation
encode-addr Encode an address from internal RIPEMD representation to base58check form
FORMAT (WIF)
secret-to-wif Convert a secret exponent value to Wallet Import Format
wif-to-secret Convert a Wallet Import Format to secret exponent value.
HASHES
ripemd-hash RIPEMD hash data from STDIN.
sha256 Perform SHA256 hash of data.
MISC
qrcode Generate Bitcoin QR codes offline.
SATOSHI MATH
btc Convert Satoshis into Bitcoins.
satoshi Convert Bitcoins into Satoshis.
We can re-format the public_key as an address using the addr command. We pass the
public_key into standard input:
$ sx addr < public_key
17re1S4Q8ZHyCP8Kw7xQad1Lr6XUzWUnkG
The keys generated above are so called type-0 non-deterministic keys. That means that
each one is generated from a random number generator. The sx tools also support type-2
deterministic keys, where a master key is created and then extended to produce a
chain or tree of subkeys.
First, we generate a seed that will be used as the basis to derive a chain of keys, com
patible with the Electrum wallet and other similar implementations. We use the new
seed command to produce a seed value:
$ sx newseed > seed
$ cat seed
eb68ee9f3df6bd4441a9feadec179ff1
The seed value can also be exported as a word mnemonic that is human readable and
easier to store and type than a hexadecimal string using the mnemonic command:
$ sx mnemonic < seed > words
$ cat words
adore repeat vision worst especially veil inch woman cast recall dwell appreciate
The mnemonic words can be used to reproduce the seed using the mnemonic command
again:
$ sx mnemonic < words
eb68ee9f3df6bd4441a9feadec179ff1
With the seed, we can now generate a sequence of private and public keys, a key chain.
We use the genpriv command to generate a sequence of private keys from a seed and
the addr command to generate the corresponding public key.
$ sx genpriv 0 < seed
5JzY2cPZGViPGgXZ4Syb9Y4eUGjJpVt6sR8noxrpEcqgyj7LK7i
$ sx genpriv 0 < seed | sx addr
1esVQV2vR9JZPhFeRaeWkAhzmWq7Fi7t7
input : create
network : Bitcoin
wallet key : xprv9s21ZrQH143K3LU5ctPZTBnb9kTjA5Su9DcWHvXJemiJBsY7VqXUG7hipgdWaU\
m2nhnzdvxJf5KJo9vjP2nABX65c5sFsWsV8oXcbpehtJi
public version : xpub661MyMwAqRbcFpYYiuvZpKjKhnJDZYAkWSY76JvvD7FH4fsG3Nqiov2CfxzxY8\
DGcpfT56AMFeo8M8KPkFMfLUtvwjwb6WPv8rY65L2q8Hz
tree depth : 0
fingerprint : 9d9c6092
parent f'print : 00000000
child index : 0
chain code : 80574fb260edaa4905bc86c9a47d30c697c50047ed466c0d4a5167f6821e8f3c
private key : yes
247
secret exponent : 112471538590155650688604752840386134637231974546906847202389294096567806844862
hex : f8a8a28b28a916e1043cc0aca52033a18a13cab1638d544006469bc171fddfbe
wif : L5Z54xi6qJusQT42JHA44mfPVZGjyb4XBRWfxAzUWwRiGx1kV4sP
uncompressed : 5KhoEavGNNH4GHKoy2Ptu4KfdNp4r56L5B5un8FP6RZnbsz5Nmb
public pair x : 76460638240546478364843397478278468101877117767873462127021560368290114016034
public pair y : 59807879657469774102040120298272207730921291736633247737077406753676825777701
x as hex : a90b3008792432060fa04365941e09a8e4adf928bdbdb9dad41131274e379322
y as hex : 843a0f6ed9c0eb1962c74533795406914fe3f1957c5238951f4fe245a4fcd625
y parity : odd
key pair as sec : 03a90b3008792432060fa04365941e09a8e4adf928bdbdb9dad41131274e379322
uncompressed : 04a90b3008792432060fa04365941e09a8e4adf928bdbdb9dad41131274e379322\
843a0f6ed9c0eb1962c74533795406914fe3f1957c5238951f4fe245a4fcd625
hash160 : 9d9c609247174ae323acfc96c852753fe3c8819d
uncompressed : 8870d869800c9b91ce1eb460f4c60540f87c15d7
Bitcoin address : 1FNNRQ5fSv1wBi5gyfVBs2rkNheMGt86sp
uncompressed : 1DSS5isnH4FsVaLVjeVXewVSpfqktdiQAM
Create a BIP32 key from a passphrase:
THE PASSPHRASE IN THIS EXAMPLE IS WAY TOO EASY TO GUESS.
$ ku P:foo
input : P:foo
network : Bitcoin
wallet key : xprv9s21ZrQH143K31AgNK5pyVvW23gHnkBq2wh5aEk6g1s496M8ZMjxncCKZKgb5j\
ZoY5eSJMJ2Vbyvi2hbmQnCuHBujZ2WXGTux1X2k9Krdtq
public version : xpub661MyMwAqRbcFVF9ULcqLdsEa5WnCCugQAcgNd9iEMQ31tgH6u4DLQWoQayvtS\
VYFvXz2vPPpbXE1qpjoUFidhjFj82pVShWu9curWmb2zy
tree depth : 0
fingerprint : 5d353a2e
parent f'print : 00000000
child index : 0
chain code : 5eeb1023fd6dd1ae52a005ce0e73420821e1d90e08be980a85e9111fd7646bbc
private key : yes
secret exponent : 65825730547097305716057160437970790220123864299761908948746835886007793998275
hex : 91880b0e3017ba586b735fe7d04f1790f3c46b818a2151fb2def5f14dd2fd9c3
wif : L26c3H6jEPVSqAr1usXUp9qtQJw6NHgApq6Ls4ncyqtsvcq2MwKH
uncompressed : 5JvNzA5vXDoKYJdw8SwwLHxUxaWvn9mDea6k1vRPCX7KLUVWa7W
public pair x : 81821982719381104061777349269130419024493616650993589394553404347774393168191
public pair y : 58994218069605424278320703250689780154785099509277691723126325051200459038290
x as hex : b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f
y as hex : 826d8b4d3010aea16ff4c1c1d3ae68541d9a04df54a2c48cc241c2983544de52
y parity : even
key pair as sec : 02b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f
uncompressed : 04b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f\
826d8b4d3010aea16ff4c1c1d3ae68541d9a04df54a2c48cc241c2983544de52
hash160 : 5d353a2ecdb262477172852d57a3f11de0c19286
uncompressed : e5bd3a7e6cb62b4c820e51200fb1c148d79e67da
Bitcoin address : 19Vqc8uLTfUonmxUEZac7fz1M5c5ZZbAii
uncompressed : 1MwkRkogzBRMehBntgcq2aJhXCXStJTXHT
Get info as JSON:
input : 1
network : Bitcoin
secret exponent : 1
hex : 1
wif : KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn
uncompressed : 5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf
public pair x : 55066263022277343669578718895168534326250603453777594175500187360389116729240
public pair y : 32670510020758816978083085130507043184471273380659243275938904335757337482424
x as hex : 79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
y as hex : 483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
y parity : even
key pair as sec : 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
uncompressed : 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\
483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
hash160 : 751e76e8199196d454941c45d1b3a323f1433bd6
uncompressed : 91b24bf9f5288532960ac687abb035127b1d28a5
Bitcoin address : 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
uncompressed : 1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm
input : 1
network : Litecoin
secret exponent : 1
hex : 1
wif : T33ydQRKp4FCW5LCLLUB7deioUMoveiwekdwUwyfRDeGZm76aUjV
uncompressed : 6u823ozcyt2rjPH8Z2ErsSXJB5PPQwK7VVTwwN4mxLBFrao69XQ
public pair x : 55066263022277343669578718895168534326250603453777594175500187360389116729240
public pair y : 32670510020758816978083085130507043184471273380659243275938904335757337482424
x as hex : 79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
y as hex : 483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
y parity : even
key pair as sec : 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
uncompressed : 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\
483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
hash160 : 751e76e8199196d454941c45d1b3a323f1433bd6
uncompressed : 91b24bf9f5288532960ac687abb035127b1d28a5
Litecoin address : LVuDpNCSSj6pQ7t9Pv6d6sUkLKoqDEVUnJ
uncompressed : LYWKqJhtPeGyBAw7WC8R3F7ovxtzAiubdM
Dogecoin WIF:
$ ku -nD -W 1
QNcdLVw8fHkixm6NNyN6nVwxKek4u7qrioRbQmjxac5TVoTtZuot
From public pair (on Testnet):
$ ku -nT 55066263022277343669578718895168534326250603453777594175500187360389116729240,even
input : 550662630222773436695787188951685343262506034537775941755001873603\
89116729240,even
network : Bitcoin testnet
public pair x : 550662630222773436695787188951685343262506034537775941755001873603891167
public pair y : 326705100207588169780830851305070431844712733806592432759389043357573374
x as hex : 79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
y as hex : 483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
y parity : even
key pair as sec : 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
uncompressed : 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\
483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
hash160 : 751e76e8199196d454941c45d1b3a323f1433bd6
uncompressed : 91b24bf9f5288532960ac687abb035127b1d28a5
Bitcoin testnet address : mrCDrCybB6J1vRfbwM5hemdJz73FwDBC8r
uncompressed : mtoKs9V381UAhUia3d7Vb9GNak8Qvmcsme
From hash160:
$ ku 751e76e8199196d454941c45d1b3a323f1433bd6
input : 751e76e8199196d454941c45d1b3a323f1433bd6
network : Bitcoin
input : 751e76e8199196d454941c45d1b3a323f1433bd6
network : Dogecoin
hash160 : 751e76e8199196d454941c45d1b3a323f1433bd6
Dogecoin address : DFpN6QqFfUm3gKNaxN6tNcab1FArL9cZLE
010000000141045e0ab2b0b82cdefaf9e9a8ca9ec9df17673d6a74e274d0c73ae77d3f131e000000004a493046022100a7
255
Symbol Value (hex) Description
OP_RETURN 0x6a Halt and invalidate transaction
256 | Appendix C: Appendix: Transaction Script Language Operators, Constants and Symbols
Symbol Value (hex) Description
OP_OR 0x85 Disabled (Boolean OR of two top items)
OP_XOR 0x86 Disabled (Boolean XOR of two top items)
OP_EQUAL 0x87 Push TRUE (1) if top two items are exactly equal, push FALSE (0) otherwise
OP_EQUALVERIFY 0x88 Same as OP_EQUAL, but run OP_VERIFY after to halt if not TRUE
OP_RESERVED1 0x89 Halt - Invalid transaction unless found in an unexecuted OP_IF clause
OP_RESERVED2 0x8a Halt - Invalid transaction unless found in an unexecuted OP_IF clause
258 | Appendix C: Appendix: Transaction Script Language Operators, Constants and Symbols
APPENDIX D
Appendix - Bitcoin Improvement Proposals
A Standards Track BIP describes any change that affects most or all Bitcoin imple
mentations, such as a change to the network protocol, a change in block or trans
action validity rules, or any change or addition that affects the interoperability of
applications using Bitcoin.
An Informational BIP describes a Bitcoin design issue, or provides general guide
lines or information to the Bitcoin community, but does not propose a new feature.
Informational BIPs do not necessarily represent a Bitcoin community consensus
or recommendation, so users and implementors are free to ignore Informational
BIPs or follow their advice.
A Process BIP describes a process surrounding Bitcoin, or proposes a change to (or
an event in) a process. Process BIPs are like Standards Track BIPs but apply to areas
other than the Bitcoin protocol itself. They may propose an implementation, but
not to Bitcoins codebase; they often require community consensus; unlike Infor
mational BIPs, they are more than recommendations, and users are typically not
free to ignore them. Examples include procedures, guidelines, changes to the
decision-making process, and changes to the tools or environment used in Bitcoin
development. Any meta-BIP is also considered a Process BIP.
259
BIP# Link Title Owner Type Status
1 https://github.com/bitcoin/bips/blob/ BIP Purpose and Guidelines Amir Taaki Standard Active
master/bip-0001.mediawiki
10 https://github.com/bitcoin/bips/blob/ Multi-Sig Transaction Alan Reiner Informational Draft
master/bip-0010.mediawiki Distribution
11 https://github.com/bitcoin/bips/blob/ M-of-N Standard Transactions Gavin Standard Accepted
master/bip-0011.mediawiki Andresen
12 https://github.com/bitcoin/bips/blob/ OP_EVAL Gavin Standard Withdrawn
master/bip-0012.mediawiki Andresen
13 https://github.com/bitcoin/bips/blob/ Address Format for pay-to- Gavin Standard Final
master/bip-0013.mediawiki script-hash Andresen
14 https://github.com/bitcoin/bips/blob/ Protocol Version and User Amir Taaki, Standard Accepted
master/bip-0014.mediawiki Agent Patrick
Strateman
15 https://github.com/bitcoin/bips/blob/ Aliases Amir Taaki Standard Withdrawn
master/bip-0015.mediawiki
16 https://github.com/bitcoin/bips/blob/ Pay To Script Hash Gavin Standard Accepted
master/bip-0016.mediawiki Andresen
17 https://github.com/bitcoin/bips/blob/ OP_CHECKHASHVERIFY (CHV) Luke Dashjr Withdrawn Draft
master/bip-0017.mediawiki
18 https://github.com/bitcoin/bips/blob/ hashScriptCheck Luke Dashjr Standard Draft
master/bip-0018.mediawiki
19 https://github.com/bitcoin/bips/blob/ M-of-N Standard Transactions Luke Dashjr Standard Draft
master/bip-0019.mediawiki (Low SigOp)
20 https://github.com/bitcoin/bips/blob/ URI Scheme Luke Dashjr Standard Replaced
master/bip-0020.mediawiki
21 https://github.com/bitcoin/bips/blob/ URI Scheme Nils Standard Accepted
master/bip-0021.mediawiki Schneider,
Matt Corallo
22 https://github.com/bitcoin/bips/blob/ getblocktemplate - Luke Dashjr Standard Accepted
master/bip-0022.mediawiki Fundamentals
23 https://github.com/bitcoin/bips/blob/ getblocktemplate - Pooled Luke Dashjr Standard Accepted
master/bip-0023.mediawiki Mining
30 https://github.com/bitcoin/bips/blob/ Duplicate transactions Pieter Wuille Standard Accepted
master/bip-0030.mediawiki
31 https://github.com/bitcoin/bips/blob/ Pong message Mike Hearn Standard Accepted
master/bip-0031.mediawiki
32 https://github.com/bitcoin/bips/blob/ Hierarchical Deterministic Pieter Wuille Informational Accepted
master/bip-0032.mediawiki Wallets
33 https://github.com/bitcoin/bips/blob/ Stratized Nodes Amir Taaki Standard Draft
master/bip-0033.mediawiki
Colophon
The animal on the cover of FILL IN TITLE is FILL IN DESCRIPTION.
Many of the animals on OReilly covers are endangered; all of them are important to
the world. To learn more about how you can help, go to animals.oreilly.com.
The cover image is from FILL IN CREDITS. The cover fonts are URW Typewriter and
Guardian Sans. The text font is Adobe Minion Pro; the heading font is Adobe Myriad
Condensed; and the code font is Dalton Maags Ubuntu Mono.