1
0
mirror of https://github.com/bitcoinbook/bitcoinbook synced 2024-11-18 06:08:18 +00:00

Merge branch 'develop'

Conflicts:
	ch05.asciidoc
This commit is contained in:
Andreas M. Antonopoulos 2014-07-06 15:26:02 -04:00
commit b43e48d871
17 changed files with 1210 additions and 4 deletions

View File

@ -88,7 +88,7 @@ The transaction contains proof of ownership for each amount of bitcoin (inputs)
[TIP]
====
_Transactions_ move value *from* _transaction inputs_ *to* _transaction outputs_. An input is where the coin value is coming from, usually a previous transaction's output. A transaction output assigns a new owner to the value by associating it with a key. The destination key is called an _encumberance_. It imposes a requirement for a signature for the funds to be redeemed in future transactions. Outputs from one transaction can be used as inputs in a new transaction, thus creating a chain of ownership as the value is moved from address to address.
_Transactions_ move value *from* _transaction inputs_ *to* _transaction outputs_. An input is where the coin value is coming from, usually a previous transaction's output. A transaction output assigns a new owner to the value by associating it with a key. The destination key is called an _encumbrance_. It imposes a requirement for a signature for the funds to be redeemed in future transactions. Outputs from one transaction can be used as inputs in a new transaction, thus creating a chain of ownership as the value is moved from address to address.
====
@ -164,7 +164,7 @@ As you can see, Alice's wallet contains enough bitcoins in a single unspent outp
==== Creating the outputs
A transaction output is created in the form of a script that creates an encumberance on the value and can only be redeemed by the introduction of a solution to the script. In simpler terms, Alice's transaction output will contain a script that says something like "This output is payable to whoever can present a signature from the key corresponding to Bob's public address". Since only Bob has the wallet with the keys corresponding to that address, only Bob's wallet can present such a signature to redeem this output. Alice will therefore "encumber" the output value with a demand for a signature from Bob.
A transaction output is created in the form of a script that creates an encumbrance on the value and can only be redeemed by the introduction of a solution to the script. In simpler terms, Alice's transaction output will contain a script that says something like "This output is payable to whoever can present a signature from the key corresponding to Bob's public address". Since only Bob has the wallet with the keys corresponding to that address, only Bob's wallet can present such a signature to redeem this output. Alice will therefore "encumber" the output value with a demand for a signature from Bob.
This transaction will also include a second output, because Alice's funds are in the form of a 0.10 BTC output, too much money for the 0.015 BTC cup of coffee. Alice will need 0.085 BTC in change. Alice's change payment is created _by Alice's wallet_ in the very same transaction as the payment to Bob. Essentially, Alice's wallet breaks her funds into two payments: one to Bob, and one back to herself. She can then use the change output in a subsequent transaction, thus spending it later.

View File

@ -867,7 +867,7 @@ $ bitcoind decoderawtransaction 0100000001e34ac1e2baac09c366fce1c2245536bda8f7db
That looks correct! Our new transaction "consumes" the unspent output from our confirmed transaction and then spends it in two outputs, one for 25 millibits to our new address and one for 24.5 millibits as change back to the original address. The difference of 0.5 millibits represents the transaction fee and will be credited to the miner who finds the block that includes our transaction.
As you may notice, the transaction contains an empty +scriptSig+ because we haven't signed it yet. Without a signature, this transaction is meaningless, we haven't yet proven that we *own* the address from which the unspent output is sourced. By signing, we remove the encumberance on the output and prove that we own this output and can spend it. We use the +signrawtransaction+ command to sign the transaction. It takes the raw transaction hex string as the parameter.
As you may notice, the transaction contains an empty +scriptSig+ because we haven't signed it yet. Without a signature, this transaction is meaningless, we haven't yet proven that we *own* the address from which the unspent output is sourced. By signing, we remove the encumbrance on the output and prove that we own this output and can spend it. We use the +signrawtransaction+ command to sign the transaction. It takes the raw transaction hex string as the parameter.
[TIP]
====
@ -933,7 +933,7 @@ $ bitcoind decoderawtransaction 0100000001e34ac1e2baac09c366fce1c2245536bda8f7db
}
----
Now, the inputs used in the transaction contain a +scriptSig+, which is a digital signature proving ownership of address +1hvz...+ and removing the encumberance on the output so that it can be spent. The signature makes this transaction verifiable by any node in the bitcoin network.
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.
Now it's time to submit the newly created transaction to the network. We do that with the command +sendrawtransaction+ which takes the raw hex string produced by +signrawtransaction+. This is the same string we just decoded above:

524
ch06.asciidoc Normal file
View File

@ -0,0 +1,524 @@
[[ch6]]
== Chapter 6 - The Blockchain & Mining
*DRAFT - DO NOT SUBMIT ISSUES OR PULL REQUESTS YET PLEASE - CONSTANT CHANGES HAPPENING*
=== Introduction
((("blockchain")))
Bitcoin's blockchain is 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 independently 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 Nakamoto's main invention is the decentralized mechanism for emergent consensus. All the properties of bitcoin, including currency, transactions, payments and the security model that does not depend central authority or trust derive from this invention.
Bitcoin's consensus emerges from the interplay of three processes that occur independently on nodes across the network:
* Independent verification of each transaction, by every full node, based on a comprehensive list of criteria
* Independent aggregation of those transactions into new blocks by mining nodes, coupled with demonstrated computation through a Proof-of-Work algorithm
* Independent assembly of the new blocks by every full node into a chain and selection of the chain with the most cumulative computation demonstrated through Proof-of-Work
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 assemble its own copy of the authoritative, trusted, public, global ledger.
Each of these processes also aggregates smaller bitcoin units into larger data structures. First, unspent transaction outputs (UTXO) are aggregated into transactions. Next, many transactions are aggregated into a block. Finally, blocks are added to a chain of blocks, the blockchain. In the previous chapter we looked at transactions as a data structure. In this chapter we will also look at the larger data structures: blocks and the blockchain.
=== Independently Verifying Transactions
In the previous chapter we saw how wallet software creates transactions by collecting UTXO, providing the appropriate unlocking scripts and then constructing new outputs assigned to a new owner. The resulting transaction is then sent to the neighboring nodes in the bitcoin network so that it may be propagated across the entire bitcoin network.
Every bitcoin node that receives a transaction will first verify the transaction before forwarding it to its neighbors. This ensures that only valid transactions are propagated across the network, while invalid transactions are discarded at the first node that encounters them.
Each node verifies every transaction against a long checklist of criteria:
* Check the syntactic correctness of the transaction's data structure
* Make sure neither lists of inputs or outputs are empty
* The transaction size in bytes is less than MAX_BLOCK_SIZE
* Each output value, as well as the total, must be within the allowed range of values (less than 21m coins, more than 0)
* Check none of the inputs have hash=0, N=-1 (coinbase transactions should not be relayed)
* Check that nLockTime is less than or equal to INT_MAX
* Check that the transaction size in bytes is greater than or equal to 100
* Check the number of signature operations contained in the transaction is less than the signature operation limit
* Reject "nonstandard" transactions: unlocking script (scriptSig) doing anything other than pushing numbers on the stack, or the locking script (scriptPubkey) not matching isStandard forms
* Check for a matching transaction in the pool, or in a block in the main branch, if so reject this transaction
* For each input, if the referenced output exists in any other transaction in the pool, reject this transaction.
* For each input, look in the main branch and the transaction pool to find the referenced output transaction. If the output transaction is missing for any input, this will be an orphan transaction. Add to the orphan transactions, if a matching transaction is not already in the pool.
* For each input, if the referenced output transaction is a coinbase output, it must have at least COINBASE_MATURITY (100) confirmations; else reject this transaction
* For each input, if the referenced output does not exist (e.g. never existed or has already been spent), reject this transaction
* Using the referenced output transactions to get input values, check that each input value, as well as the sum, are in the allowed range of values (less than 21m coins, more than 0)
* Reject if the sum of input values < sum of output values
* Reject if transaction fee would be too low to get into an empty block
* Verify the unlocking scripts for each input against the corresponding output locking scripts
These conditions can be seen in detail in the functions AcceptToMemoryPool, CheckTransaction and CheckInputs in the bitcoin reference client. Note that the conditions change over time, to address new types of Denial-of-Service attacks or sometimes to relax the rules so as to include more types of transactions.
By independently verifying each transaction as it is received and before propagating it, every node builds a pool of valid new transactions (the transaction pool), roughly in the same order.
[[transaction_pools]]
== Transaction Pools
Almost every node on the bitcoin network maintains a temporary list of unconfirmed transactions called the memory pool or transaction pool. Once a transaction is verified using the detailed checklist introduced in the section above, it is added to the 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. Every node also maintains a separate pool of orphaned transactions as detailed in <<orphan_transactions>>. If a transactions inputs refer to a transaction that is not yet known, a missing parent, then it will be stored temporarily in the orphan pool until the parent transaction arrives. Both the transaction pool and orphan pool 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.
As transactions are received and verified using the criteria in the previous section, they are added to the transaction pool and relayed to the neighboring nodes to propagate on the network.
When a transaction is added to the transaction pool, the orphan pool is checked for any orphans that reference this transaction's outputs (its children). Any orphans found are pulled from the orphan pool and validated using the above checklist. If valid, they are also 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 reconstruction of an entire chain of interdependent transactions by re-uniting the orphans with their parents all the way down the chain.
Most nodes also create a UTXO pool which is the set of all unspent outputs on the blockchain, this may be housed in local memory or as an indexed database table on persistent storage. 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. Whereas the transaction and orphan pools represent a nodes local perspective and may vary significantly from node to node depending upon when the node was started or restarted, the UTXO pool represents the emergent consensus of the network and therefore will vary little between nodes. Furthermore the transaction and orphan pools only contain unconfirmed transactions, while the UTXO pool only contains confirmed outputs.
=== Aggregating Transactions into Blocks
Some of the nodes on the bitcoin network are specialized nodes called _miners_. A miner will collect, validate and relay new transactions just like any other node. Unlike other nodes, a miner will then aggregate these transactions into a _block_. The block of transactions constructed by a miner is a candidate block and becomes valid only if the miner succeeds in winning the mining competition. Each miner competes by trying billions of possible solutions to an equation based on a cryptographic hash. If they find a solution, they broadcast the candidate block for everyone to record on the blockchain. The competition difficulty is calibrated to ensure that a new block solution is found by someone every 10 minutes on average. We will look at the mining process itself in more detail in <<mining>>. For now, let's look at how miners aggregate transactions into blocks.
In Chapter 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. Jing started mining for bitcoin in 2010, when mining was not as competitive as it is today. At that time, Jing could mine bitcoin using a desktop computer. Today, he uses a much more powerful mining system based on Application Specific Integrated Circuits (ASICs), which are specialized silicon chips designed exclusively for one application - bitcoin mining. Over time, the way Jing participates in the mining process has changed slightly, but the fundamentals remain the same. We will start by looking at how Jing mined in 2010, when things were simpler and then look at how he mines today, as bitcoin mining has become a more complex and competitive activity.
In 2010, Jing mined on a desktop computer. At the time, he would run a full bitcoin node, connected to the bitcoin network. A full bitcoin node keeps a full copy of the blockchain, the list of all transactions since the first ever transaction in 2009. Jing's bitcoin node would receive transactions propagated by other nodes, just like any other node on the bitcoin network. After validating those transactions, the bitcoin software would add them to the _memory pool_, or _transaction pool_, where transactions would await until they could be included (mined) into a block.
Jing's bitcoin node is also listening for new blocks, propagated on the bitcoin network. As soon a Jing's bitcoin node receives a valid new block, it immediately starts the next round of competition. Receiving a new block signifies that someone else has won the previous round, meaning that Jing's system did not win that round and should abandon its current efforts and shift its resources to try and win the next round. During the previous 10 minutes, while Jing's node was searching for a solution, it was also collecting transactions. By now it has collected a few hundred transactions in the memory pool. After removing any transactions that appear in the new block recently received, Jing's memory pool is left containing unconfirmed transactions that are waiting to be recorded in a new block.
Jing's node immediately constructs a new candidate block, to participate in the competition.
=== 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, followed by a long list of transactions that make up the bulk of it's size.
[[block_structure]]
.The structure of a block
[options="header"]
|=======
|Size| Field | Description
| 4 bytes | Magic Number | A constant (0xD9B4BEF9) used to easily recognize bitcoin blocks
| 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
|=======
Jing's mining node creates a candidate block by building an empty data structure and then filling it with transactions and the appropriate metadata. We'll ignore the header for now, as it is the last thing filled in by a node and concentrate instead on the transactions and how they are added to the block. Jing's node uses a selection algorithm to pick transactions from the memory pool (and the orphan pool if the parent has arrived) and adds them after the block header. The selection algorithm is detailed in the next section.
=== Adding Transactions to a Candidate Block
To construct the candidate block Jing's bitcoin node selects transactions from the memory pool, by applying a priority metric to each transaction and adding the highest priority transactions first. Transactions are prioritized based on the "age" of the UTXO that is being spent in their inputs, allowing for old and high-value inputs to be prioritized over newer and smaller inputs. Prioritized transactions can be sent without any fees, if there is enough space in the block.
The priority of a transaction is calculated as the sum of the value and age of the inputs divided by the total size of the transaction:
----
Priority = Sum (Value of input * Input Age) / Transaction Size
----
In the equation above, the value of an input is measured in the base unit, satoshis (1/100m of a bitcoin). The age of a UTXO is the number of blocks that have elapsed since the UTXO was recorded on the blockchain, measuring how many blocks "deep" into the blockchain it is. The size of the transaction is measured in bytes.
For a transaction to be considered "high priority" its priority must be greater than 57,600,000, which corresponds to one bitcoin (100m satoshis), aged one day (144 blocks) in a transaction of 250 bytes total size.
----
High Priority = 100,000,000 satoshis * 144 blocks / 250 bytes = 57,600,000
----
The first 50 kilobytes of transaction space in a block are set aside for high priority transactions. Jing's node will fill the first 50 kilobytes, prioritizing the highest priority transactions first, regardless of fee. This allows high-priority transactions to be processed even if they carry zero fees.
Jing's mining node then fills the rest of the block up to the maximum block size (MAX_BLOCK_SIZE in the code), with transactions that carry at least the minimum fee, prioritizing those with the highest fee per kilobyte of transaction.
If there is any space remaining in the block, Jing's mining node may choose to fill it with no-fee transactions. Some miners choose to mine transactions without fees on a best-effort basis. Other miners may choose to ignore transactions without fees.
Any transactions left in the memory pool after the block is filled will remain in the pool for inclusion in the next block. As transactions remain in the memory pool, their inputs "age", as the UTXO they spend get deeper into the blockchain with new blocks added on top. Since a transactions priority depends on the age of its inputs, transactions remaining in the pool will age and therefore increase in priority. Eventually a transaction without fees may reach a high enough priority to be included in the block for free.
Bitcoin transactions do not have an expiration time-out. A transaction that is valid now will be valid in perpetuity. However, if a transaction is only propagated across the network once it will persist only as long as it is held in a mining node memory pool. When a mining node is restarted, its memory pool is wiped clear, as it is a transient non-persistent form of storage. While a valid transaction may have been propagated across the network, if it is not executed it may eventually not reside in the memory pool of any miner. Wallet software is expected to retransmit such transactions or reconstruct them with higher fees if they are not successfully executed within a reasonable amount of time.
=== 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 <<blockchain>>. The second set of metadata, namely the difficulty, timestamp and nonce, relate to the mining competition, as detailed in <<mining>>. The third piece of metadata is the Merkle Tree root, a data structure used to efficiently summarize all the transactions in the block. Merkle Trees are discussed in the next section.
Jing's node will next assemble the metadata and fill in the candidate block's header.
[[block_structure]]
.The structure of the block header
[options="header"]
|=======
|Size| Field | Description
| 4 bytes | Version | A version number to track software/protocol upgrades
| 32 bytes | Previous Block Hash | A reference to the hash of the previous (parent) block in the chain
| 32 bytes | Merkle Root | A hash of the root of the Merkle-Tree of this block's transactions
| 4 bytes | Timestamp | The approximate creation time of this block (seconds from Unix Epoch)
| 4 bytes | Difficulty Target | The proof-of-work algorithm difficulty target for this block
| 4 bytes | Nonce | A counter used for the proof-of-work algorithm
|=======
=== Merkle Trees
A _Merkle Tree_, also known as a _Binary Hash Tree_ is a data structure created by Ralph Merkle used for efficiently summarizing and verifying the integrity of large sets of data. Merkle Trees are binary trees containing cryptographic hashes. When N data elements are hashed and summarized in a Merkle Tree, you can check to see if any one data element is included in the tree with at most +2*log~2~(N)+ calculations, making this a very efficient data structure. The term "tree" is used in computer science to describe a branching data structure, but trees are usually displayed upside down with the "root" at the top and the "leaves" at the bottom of a diagram, as you will see in the examples that follow.
Merkle trees are used in bitcoin to summarize all the transactions in a block, producing an overall digital fingerprint of the entire set of transactions, which can be used to prove that a transaction is included in the set. A merkle tree is constructed by recursively hashing pairs of nodes until there is only one hash, called the _root_, or _merkle root_. The cryptographic hash algorithm used in bitcoin's merkle trees is SHA256 applied twice, also known as double-SHA256.
The merkle tree is constructed bottom-up. In the example below, we start with four transactions A, B, C and D, which form the _leaves_ of the Merkle Tree, shown in the diagram at the bottom. The transactions are not stored in the merkle tree, rather their data is hashed and the resulting hash is stored in each leaf node as H~A~, H~B~, H~C~ and H~D~:
+H~A~ = SHA256(SHA256(Transaction A))+
Consecutive pairs of leaf nodes are then summarized in a parent node, by concatenating the two hashes and hashing them together. For example, to construct the parent node H~AB~, the two 32-byte hashes of the children are concatenated to create a 64-byte string. That string is then double-hashed to produce the parent node's hash:
+H~AB~ = SHA256(SHA256(H~A~ + H~B~))+
The process continues until there is only one node at the top, the node known as the Merkle Root. That 32-byte hash is stored in the block header and summarizes all the data in all four transactions.
[[simple_merkle]]
.Calculating the nodes in a Merkle Tree
image::images/MerkleTree.png["merkle_tree"]
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 is 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:
[[merkle_tree_odd]]
.An even number of data elements, by duplicating one data element
image::images/MerkleTreeOdd.png["merkle_tree_odd"]
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 same way producing just 32-bytes of data from a single merkle root. In the diagram below, you will see a tree built from 16 transactions:
[[merkle_tree_large]]
.A Merkle Tree summarizing many data elements
image::images/MerkleTreeLarge.png["merkle_tree_large"]
To prove that a specific transaction is included in a block, a node need only produce +log~2~(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 H~L~, H~IJ~, H~MNOP~ and H~ABCDEFGH~. With those four hashes provided as an authentication path, any node can prove that H~K~ is included in the merkle root by computing four additional pair-wise hashes H~KL~, H~IJKL~ and H~IJKLMNOP~ that lead to the merkle root.
[[merkle_tree_path]]
.A Merkle Path used to prove inclusion of a data element
image::images/MerkleTreePathToK.png["merkle_tree_path"]
The efficiency of merkle trees becomes obvious as the scale increases. For example, proving that a transaction is part of a block requires:
[[block_structure]]
.Merkle Tree Efficiency
[options="header"]
|=======
|Number of Transactions| Path Size (Hashes) | Path Size (Bytes)
| 16 transactions | 4 hashes | 128 bytes
| 512 transactions | 9 hashes | 288 bytes
| 2048 transactions | 11 hashes | 352 bytes
| 65,535 transactions | 16 hashes | 512 bytes
|=======
[[blockchain]]
=== The Blockchain
Bitcoin's core innovation is the _blockchain_, a distributed, timestamped ledger. The ledger consists of a cryptographically verified chain of _blocks_ in historical order, each of which contains transactions, new coins and a signature (hash) of the previous block. Each full bitcoin node in the network keeps a complete local replica of the blockchain, and independently verify all transactions and balances from that replica.
In this chapter we will look at the structure of the blockchain and the blocks within it. We will examine various mechanisms for querying the blockchain database to retrieve information about blocks and transactions. Finally, we will see how new blocks are added to the blockchain through the mechanism of distributed consensus based on a Proof-of-Work algorithm, known as "mining".
The blockchain data structure is an ordered 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 Google's LevelDB database.
The blockchain is made of blocks, which are generated {not are generated - maybe are usually computed / created / produced / found / mined} every ten minutes on average and hold several hundred transactions that occurred during the previous ten minutes. {is this true? is it always those that occurred during the previous 10 min?} Each block is identified by a hash, generated using the SHA256 cryptographic hash algorithm on the header of the block. {who generates this hash?} Each block also {references the previous block's hash - thereby linking the two together} contains a link to the previous block in the chain, by reference to the previous block's hash. Since a block contains a cryptographic hash of the previous block as a reference, the hash proves that the previous block was known when the current block was created. The hash of the previous block is also part of the data that creates the hash of the current block, making the ancestry of each block an immutable part of its identity. The chain of hashes guarantees that a block cannot be modified retrospectively without forcing the re-computation of all following blocks, because a retrospective change in any block would change the hash, thereby changing the reference in the next block whose hash also changes, and so on. As new blocks are added to the chain, they strengthen the immutability of the ledger by effectively incorporating all previous blocks by reference in their cryptographic hash.
Since each block can only reference one previous block, every chain of blocks can be traced back to the first block every created, the _genesis block_.
=== The Genesis Block
The first block in the chain is called the _genesis block_ and was created in 2009. It is the "common ancestor" of all the blocks in the blockchain, meaning that if you start at any block and follow the chain backwards in time you will eventually arrive at the _genesis block_.
The genesis block has the identifier hash +000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f+. You can search for that block hash in any block explorer website, such as blockchain.info, and you will find a page describing the contents of this block, with a URL containing that hash:
https://blockchain.info/block/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
https://blockexplorer.com/block/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
Using the Bitcoin Core reference client on the command-line:
----
$ bitcoind getblock 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
{
"hash" : "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
"confirmations" : 308321,
"size" : 285,
"height" : 0,
"version" : 1,
"merkleroot" : "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"tx" : [
"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
],
"time" : 1231006505,
"nonce" : 2083236893,
"bits" : "1d00ffff",
"difficulty" : 1.00000000,
"nextblockhash" : "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
}
----
=== Linking Blocks in a Chain
[[chain_of_blocks]]
.Blocks linked in a chain, by reference to the previous block header hash
image::images/ChainOfBlocks.png["chain_of_blocks"]
[[mining]]
=== Proof-of-Work (Mining) and Consensus
((("Mining", "Proof of Work", "SHA256", "hashing power", "difficulty", "nonce")))
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 act as a decentralized clearinghouse, validating new transactions and recording them on the global ledger. A new block, containing transactions which 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 bitcoin's security model.
Bitcoin's security is underpinned by computation. New blocks are added to the blockchain through a consensus mechanism called the _Proof-of-Work_ (PoW) that requires a predictable computational effort, one that takes approximately 10 minutes to solve on average. Specialized bitcoin nodes called _miners_ validate transactions and collect them into blocks, then attempt to find the solution that satisfies the Proof-of-Work algorithm. The first miner to find such a solution, propagates the newly created block across the network. All other nodes on the network verify that the new block contains valid transactions and satisfies the Proof-of-Work algorithm, then they add it to the blockchain, thereby extending it by one block. The miners add a special coin generation transaction into the blocks they build, which creates new bitcoin from nothing and is payable to the miner's own bitcoin address. Once the block is accepted as valid by the entire network, that transaction is also recorded on the blockchain, thereby rewarding the miner for the computational effort it took to satisfy the Proof-of-Work. This de-centralized consensus mechanism, based on a global competition and requiring computation to create new blocks, is the basis for the security of the bitcoin transaction ledger and also for the issuance of new bitcoin. {move the last sentence to the beginning of the paragraph - to explain more about security} The equilibrium between the incentive of bitcoin reward and the immense computing effort required to win it force the participants to behave honestly, without the need for a centralized clearinghouse or currency issuer. The bitcoin consensus mechanism is a dynamic, self-regulating and completely decentralized security model that operates at very large scale.
The process of new coin generation is called mining, because the reward is designed to simulate diminishing returns, just like mining for precious metals. Bitcoin's money supply is created through mining, just like 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 2140 when all 21 million bitcoin have been issued.
Bitcoin miners also earn fees from transactions. Every transaction may include a transaction fee, in the form of a surplus of bitcoin between the transaction's inputs and outputs. The bitcoin miner gets to "keep the change" on the transactions.
Today the fees represent 1% or less of a bitcoin miner's income, the vast majority coming from the newly minted bitcoins. However, as the reward decreases over time and the number of transactions per block increases, a greater proportion of bitcoin mining earnings will come from fees. After 2140 all bitcoin miner earnings will be in the form of transaction fees.
[[figure_sha256_logical]]
.The Secure Hash Algorithm (SHA-256)
image::images/sha256-logical.png["SHA256"]
With SHA-256, the output is always 256 bits long, regardless of the size of the input. In the example below, we will use the Python interpreter to calculate the SHA256 hash of the phrase "I am Satoshi Nakamoto".
[[sha256_example1]]
.SHA256 Example
----
$ *python*
Python 2.7.1
>>> import hashlib
>>> print hashlib.sha256("I am Satoshi Nakamoto").hexdigest()
5d7c7ba21cbbcd75d14800b100252d5b428e5b1213d27c385bc141ca6b47989e
----
The example shows that if we calculate the hash of the phrase +"I am Satoshi Nakamoto"+, 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 vary the phrase, we will expect to see completely different hashes. Let's try that by adding a number to the end of our phrase, using this simple Python script
[[sha256_example_generator]]
.SHA256 A script for generating many hashes by iterating on a nonce
====
[source, python]
----
include::code/hash_example.py[]
----
====
Running this will produce the hashes of several phrases, made different by adding a unique number, called a _nonce_ at the end of the text. By incrementing the nonce, we can get different hashes.
((("nonce")))
[[sha256_example_generator_output]]
.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.
To make a challenge out of this algorithm, let's set an arbitrary target: find a phrase starting with "I am Satoshi Nakamoto" which produces a hash that starts with a zero. In numerical terms, that means finding a hash value that is less than +0x1000000000000000000000000000000000000000000000000000000000000000+. Fortunately, this isn't 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 only took 13 attempts to find it.
==== Proof-of-Work Algorithm
Bitcoin's proof-of-work is very similar to the problem above. First, a miner will generate a new block, containing:
((("block")))
* Transactions waiting to be included in a block
* The hash from the previous block
* A _nonce_
The only part a miner can modify is the nonce. Now, the miner will calculate the hash of this block's header and see if it is smaller than the current _target difficulty_. The miner will likely have to try many nonces before finding one that results in a low enough hash.
A very simplified proof-of-work algorithm is implemented in Python here:
((("proof of work")))
[[pow_example1]]
.Simplified Proof-Of-Work Implementation
====
[source, python]
----
include::code/proof-of-work-example.py[]
----
====
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:
[[pow_example_outputs]]
.Running the proof-of-work example for various difficulties
----
$ *python proof-of-work-example.py*
Difficulty: 1 (0 bits)
[...]
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
[...]
Difficulty: 4194304 (22 bits)
Starting search...
Success with nonce 1759164
Hash is 0000008bb8f0e731f0496b8e530da984e85fb3cd2bd81882fe8ba3610b6cefc3
Elapsed Time: 13.3201 seconds
Hashing Power: 132068 hashes per second
Difficulty: 8388608 (23 bits)
Starting search...
Success with nonce 14214729
Hash is 000001408cf12dbd20fcba6372a223e098d58786c6ff93488a9f74f5df4df0a3
Elapsed Time: 110.1507 seconds
Hashing Power: 129048 hashes per second
Difficulty: 16777216 (24 bits)
Starting search...
Success with nonce 24586379
Hash is 0000002c3d6b370fccd699708d1b7cb4a94388595171366b944d68b2acce8b95
Elapsed Time: 195.2991 seconds
Hashing Power: 125890 hashes per second
[...]
Difficulty: 67108864 (26 bits)
Starting search...
Success with nonce 84561291
Hash is 0000001f0ea21e676b6dde5ad429b9d131a9f2b000802ab2f169cbca22b1e21a
Elapsed Time: 665.0949 seconds
Hashing Power: 127141 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 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 500 TH/sec of processing power to bear, which will be able to find a block in about 10 minutes on average.
==== Difficulty Target and Re-Targetting
Bitcoin is tuned to generate blocks approximately every 10 minutes. This is achieved by automatically adjusting the target difficulty to account for increases and decreases in the available computing power on the network. This process occurs automatically and on every full node independently. Each node recalculates the expected difficulty every 2106 blocks, based on the time it took to hash the previous 2106 blocks. In simple terms: If the network is finding blocks faster than every 10 minutes, the difficulty increases. If block discovery is slower than expected, the difficulty will decrease.
{miners that are on mining pools get the difficulty (do not calculate difficulty independently) they are given the difficulty from the mining pool so they don't have to calculate the difficulty themselves and they are actually given a lower difficulty target. There are essentially two classifications of miners today - pool miners and solo miners. Solo miners run a full node and compete on their own. Whereas pool miners collaborate with one another and compete against the network as a team, while sharing the reward. The reason miners join pools - solo miners need an enormous amount of hashing power in order to have even the slimmest chance of finding a solution to a block which will make their earnings erratic. By participating in a pool, miners get smaller shares but a more regular share of rewards, reducing uncertainty. Solo mining is becoming obsolete, as the difficulty increases the likelihood of a solo miner finding a solution is more like winning the lottery.}
{ASIC miners do not run full nodes. Full nodes independently calculate the difficulty using the same equation on the same block, arriving at the same result for the new difficulty. Retargeting the difficulty at block heights that are multiples of 2106 from the genesis block. The equation for retargeting difficulty measures the time it took to find the last 2106 blocks, compares that to the expected time of 21,060 minutes (based upon a desired 10 minute block time), the difference is calculated as a percentage and a corresponding percentage adjustment is made to the difficulty. To avoid extreme volatility in the difficulty, the retargeting adjustment cannot exceed {X%} per retargeting. The difficulty will only be retargeted up or down by maximum of {X%} per cycle. If the required difficulty adjustment is greater than the maximum it will be reflected in the next retargeting adjustment as the imbalance will persist through the next 2106 blocks. Large discrepancies between hashing power and difficulty may take several cycles to even out. This leads to a potential problem which has been observed in alt coins, where very large changes in difficulty can cause hashing power to collapse leading to excessively long block times. If the aggregate network hashing power collapses due to the departure of many miners simultaneously, the remaining hashing power may be insufficient to meet the difficulty target leading to excessively long block intervals. Since retargeting is not a function of time but rather block number, a large hashing deficit can mean the next cycle is very far in the future. Usually this is caused for two reasons - scenario one - entry for a brief period of a lot of hashing which temporarily increases the difficulty, followed by the departure of that hashing, resulting in a collapse of block solutions. Essentially a hashing pump and dump. Usually a deliberate attack. This is not a concern in bitcoin because new hashing power introduced into the network will not effect the average enough to cause a major change in difficulty. The other scenario in which hashing power can collapse is a crash in bitcoin price, making mining unprofitable. (If the miner cannot pay their electricity bill, the miner will leave the network.) This is a weakness of the protocol, as an insurmountable hashing deficit could occur with a precipitous collapse in price and corresponding reduction in available hashing power. The network would be unable to recover because ... }
[TIP]
====
The difficulty of finding a bitcoin block is approximately '10 minutes of processing' for the entire network, based on the time it took to find the previous 2106 blocks, adjusted every 2106 blocks.
====
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 in hashing power from today's level. The increase in hashing power represents market forces as new miners enter the market to compete for the reward. As long as enough hashing power is under the control of miners acting honestly in pursuit of the reward, it is enough to prevent "takeover" attacks and therefore it is enough to secure bitcoin.
The target difficulty is closely related to the cost of electricity and the exchange rate of bitcoin vis-a-vis the currency used to pay for electricity. High performance mining systems are about as efficient as possible with the current generation of silicon fabrication, converting electricity into hashing computation at the highest rate possible. The primary influence on the mining market is the price of one kilowatt-hour in bitcoin, as that determines the profitability of mining and therefore the incentives to enter or exit the mining market.
==== Mining New Bitcoins
Bitcoins are "minted" during the creation of each block at a fixed and diminishing rate. Each block, generated on average every 10 minutes, contains a _reward_ that consists of entirely new bitcoins. The reward was 50BTC for the first four years of operation of the network. Every four years the reward is decreased by 50%, resulting in a diminishing rate of issuance over time. In 2012, the reward was decreased to 25BTC and it will decrease again to 12.5BTC in 2016. By approximately 2140, the last fragments of a bitcoin will be mined, for a total of 21 million bitcoins. {Clarify coinbase transaction as first - includes the reward and transactions. Discuss how the coinbase transaction will change in 2140}
The finite and diminishing issuance creates a fixed monetary supply that resists inflation. Unlike a fiat currency which can be printed in infinite numbers by a central bank, bitcoin can never be inflated by printing.
===== Monetary supply
Bitcoin's monetary supply is defined as the number of coins in circulation (minted). Like any other currency, this measure of monetary supply is called M0, which represents the narrowest measure of the money supply. Just like any other currency, bitcoin can also have a _fractional reserve banking_ which means that an organization can trade bitcoins "off blockchain" which are not part of the M0 monetary measure, but of the broader monetary supply measures M1-M3. {have you explained M1-M3?}{also, i think you should explain fractional reserve banking a bit here}
While the total bitcoins in circulation will not exceed 21m, that monetary base can support a much broader economy through fractional reserve banking and expansion of the available credit.
===== 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 your 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, the incentives for regular people are to hoard the money and not spend it, hoping that prices will fall. Such a phenomenon unfolded during Japan's "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, we associate deflation 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 to print money. Deflation in bitcoin is not caused by a collapse in demand, but by predictably constrained supply.
In practice, it has become evident that the hoarding instinct caused by a deflationary currency can be overcome by discounting from vendors, until the discount overcomes the hoarding instinct of the buyer. Since the seller is also motivated to hoard, the discount becomes the equilibrium price at which the two hoarding instincts are matched. With discounts of 30% on the bitcoin price, most bitcoin retailers are not experiencing difficulty overcoming the hoarding instinct and generating revenue. It remains to be seen whether the deflationary aspect of the currency is really a problem when it is not driven by rapid economic retraction.
==== Blockchain Forks
{Discuss chain selection: As new blocks are found they are added to the chain. Each full node constructs a chain and calculates the cumulative difficulty of that chain. As blocks are constructed and propagated across the network,}
{create a graphic showing propagating transaction}
{Because the blockchain is a decentralized data structure, different copies of it are not always consistent. Blocks may arrive at different nodes at different times, causing them to have a different perspective o ft the blockchain. To resolve this, each node always selects and attempts to extend the chain of blocks that represents the most Proof-of-Work, also known as the longest chain or greatest cumulative difficulty chain, by adding the difficulty recorded in each block for a chain a node can calculate the total amount of PoW that has been expended to create that chain. As long as all nodes select the longest, i.e. the longest cumulative difficulty chain, the global bitcoin network eventually converges to a consistent state. Forks occur as temporary inconsistencies between versions of the blockchain, which are resolved by the eventual reconvergence.}
{Bitcoin's _consensus mechanism_, which creates the is comprised of the independent validation of transactions by every node, the cumulative work of the miners, and the network convergence upon the greatest difficulty chain. The interplay of these three processes manifests the emergent property of consensus that allows for a global decentralized public ledger without a central authority. which creates one global public ledger, emerges as a property of (1) the selection of the greatest difficulty chain. This chapter is about the emergent property of consensus. This consensus is created by the interplay of three processes - (1) ,2,3. The emergent property of network-wide consensus is what establishes a trusted decentralized global public ledger. Satohsi's invention was not proof of work, elliptic curve cryptography. Satoshi's invention was how the interplay of these processes creates emergent consensus in a decentralized network without the need for a centralized trusted authority.}
A "fork" occurs whenever there are two candidate blocks competing to form the longest blockchain. This occurs under normal conditions whenever two miners solve the Proof-of-Work algorithm within a short period of time from each other. As both miners discover a solution for their respective candidate blocks, they immediately broadcast their own "winning" block to their immediate neighbors who begin propagating the block across the network. Each node that receives a valid block will incorporate it into their blockchain, extending the blockchain by one block. If that node later sees another candidate block extending the same parent, they ignore the second candidate. As a result, some nodes will "see" one candidate block first, while other nodes will see the other candidate block and two competing versions of the blockchain will emerge.
{create a graphic with the globe, two miners each - bitcoin topology map}
Let's assume for example that a miner in Canada finds a proof-of-work solution for block "A" that extends the blockchain from height 315000 to height 315001, building on top of parent block "P". Almost simultaneously, an Australian miner who was also extending block "P", finds a solution for block "B", their candidate block. Now, there are two possible candidates for block height 315001, one we call "A", originating in Canada and one we call "B", originating in Australia. Both blocks are valid, both blocks contain a valid solution to the proof of work, both blocks extend the same parent. Both blocks likely contain most of the same transactions, with only perhaps a few differences in the order of transactions. From that moment, the bitcoin network nodes closest (topologically, not geographically) to the Canadian node will hear about block "A" first and will create a new greatest-cumulative-difficulty blockchain with height 315001 and "A" as the last block in the chain (e.g. P-A), ignoring the candidate block "B" that arrives a bit later. Meanwhile, nodes closer to the Australian node will take that block as the winner and extend the blockchain to height 315001 with "B" as the last block (e.g. P-B), ignoring "A" when it arrives a few seconds later. Any miners that saw "A" first will immediately build candidate blocks that reference "A" as the parent and start trying to solve the PoW for these candidate blocks. The miners that accepted "B" instead, will start extending that chain.
----
Block "A" extends the chain: P-A
Block "B" also extends the chain: P-B
----
Forks are almost always resolved within one block. As part of the network's hashing power is dedicated to building on top of "A" as the parent, another part of the hashing power is focused on building on top of "B". 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. Let's say for example that the miners building on top of "B" find a new block "X" that extends the chain to height 315002 (e.g. P-B-X). They immediately propagate this new block and the entire network sees it as a valid solution. All nodes that had chosen "B" as the winner in the previous round will simply extend the chain one more block. The nodes that chose "A" as the winner, however, will now see a block extending an even longer chain (greater-cumulative difficulty), that does not include "A" in it. Any miners working on extending the chain P-A will now stop that work because their candidate block is an "orphan", as its parent "A" is no longer on the longest chain. The block "A" is removed from the blockchain by any nodes that had accepted it and any transactions within it are queued up again for processing in the next block. The entire network re-converges on a single blockchain P-B-X, with "X" as the last block in the chain. All miners immediately start working on candidate blocks that reference "X" as their parent to extend the P-B-X 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.
----
Block "X" extends the chain: P-B-X
Old chain is now "shorter": P-A
----
[TIP]
====
As of version 0.9, Bitcoin Core's +alertnotify+ option will send alerts whenever a 6-block or longer fork occurs
====
[[chainforks]]
.A blockchain showing two instances of forking
image::images/BlockChainWithForks.png["chainforks"]
==== Highest Difficulty Chain Selection
==== Competition and Coinbase
==== Mining Pools
===== Managed Pools
===== P2Pool
==== Mining Economics
==== Consensus Attacks
===== 51% Attack
===== Selfish Mining Attack
==== Normal Forks
==== Soft Forks
==== Hard Forks
==== Unusual Forks

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
images/ChainOfBlocks.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
images/ForkedChain1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
images/ForkedChain2a.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

BIN
images/ForkedChain2b.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

BIN
images/ForkedChain3b.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

BIN
images/GlobalFork.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

BIN
images/GlobalFork2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

BIN
images/MerkleTree.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
images/MerkleTreeLarge.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
images/MerkleTreeOdd.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
images/MerkleTreePathToK.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

682
pycoin.asciidoc Normal file
View File

@ -0,0 +1,682 @@
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. As of June, 2014, the latest released version is 0.42, and all examples here are based on that version; be warned that it is still under active development, so later versions may have differences in API or command-line tools.
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:
$ 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
Installing collected packages: pycoin
Running setup.py install for pycoin
Installing tx script to /tmp/pycoin/bin
Installing cache_tx script to /tmp/pycoin/bin
Installing bu script to /tmp/pycoin/bin
Installing fetch_unspent script to /tmp/pycoin/bin
Installing block script to /tmp/pycoin/bin
Installing spend script to /tmp/pycoin/bin
Installing ku script to /tmp/pycoin/bin
Installing genwallet script to /tmp/pycoin/bin
Successfully installed pycoin
Cleaning up...
$
KU and TX
=========
KU
--
The command-line utility ```ku``` ("key utility") is Swiss Army knife for manipulating keys. It supports BIP32 keys, WIF, and address (bitcoin and alt coins). Here are some examples.
Create a BIP32 Key using the default entropy sources of GPG and /dev/random:
$ ku create
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
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:
$ ku P:foo -P -j
{
"y_parity": "even",
"public_pair_y_hex": "826d8b4d3010aea16ff4c1c1d3ae68541d9a04df54a2c48cc241c2983544de52",
"private_key": "no",
"parent_fingerprint": "00000000",
"tree_depth": "0",
"network": "Bitcoin",
"btc_address_uncompressed": "1MwkRkogzBRMehBntgcq2aJhXCXStJTXHT",
"key_pair_as_sec_uncompressed": "04b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f826d8b4d3010aea16ff4c1c1d3ae68541d9a04df54a2c48cc241c2983544de52",
"public_pair_x_hex": "b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f",
"wallet_key": "xpub661MyMwAqRbcFVF9ULcqLdsEa5WnCCugQAcgNd9iEMQ31tgH6u4DLQWoQayvtSVYFvXz2vPPpbXE1qpjoUFidhjFj82pVShWu9curWmb2zy",
"chain_code": "5eeb1023fd6dd1ae52a005ce0e73420821e1d90e08be980a85e9111fd7646bbc",
"child_index": "0",
"hash160_uncompressed": "e5bd3a7e6cb62b4c820e51200fb1c148d79e67da",
"btc_address": "19Vqc8uLTfUonmxUEZac7fz1M5c5ZZbAii",
"fingerprint": "5d353a2e",
"hash160": "5d353a2ecdb262477172852d57a3f11de0c19286",
"input": "P:foo",
"public_pair_x": "81821982719381104061777349269130419024493616650993589394553404347774393168191",
"public_pair_y": "58994218069605424278320703250689780154785099509277691723126325051200459038290",
"key_pair_as_sec": "02b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f"
}
Public BIP32 Key:
$ ku -w -P P:foo
xpub661MyMwAqRbcFVF9ULcqLdsEa5WnCCugQAcgNd9iEMQ31tgH6u4DLQWoQayvtSVYFvXz2vPPpbXE1qpjoUFidhjFj82pVShWu9curWmb2zy
Generate a subkey:
$ ku -w -s3/2 P:foo
xprv9wTErTSkjVyJa1v4cUTFMFkWMe5eu8ErbQcs9xajnsUzCBT7ykHAwdrxvG3g3f6BFk7ms5hHBvmbdutNmyg6iogWKxx6mefEw4M8EroLgKj
Hardened subkey:
$ ku -w -s3/2H P:foo
xprv9wTErTSu5AWGkDeUPmqBcbZWX1xq85ZNX9iQRQW9DXwygFp7iRGJo79dsVctcsCHsnZ3XU3DhsuaGZbDh8iDkBN45k67UKsJUXM1JfRCdn1
WIF:
$ ku -W P:foo
L26c3H6jEPVSqAr1usXUp9qtQJw6NHgApq6Ls4ncyqtsvcq2MwKH
Address:
$ ku -a P:foo
19Vqc8uLTfUonmxUEZac7fz1M5c5ZZbAii
Generate a bunch of subkeys:
$ ku P:foo -s 0/0-5 -w
xprv9xWkBDfyBXmZjBG9EiXBpy67KK72fphUp9utJokEBFtjsjiuKUUDF5V3TU8U8cDzytqYnSekc8bYuJS8G3bhXxKWB89Ggn2dzLcoJsuEdRK
xprv9xWkBDfyBXmZnzKf3bAGifK593gT7WJZPnYAmvc77gUQVej5QHckc5Adtwxa28ACmANi9XhCrRvtFqQcUxt8rUgFz3souMiDdWxJDZnQxzx
xprv9xWkBDfyBXmZqdXA8y4SWqfBdy71gSW9sjx9JpCiJEiBwSMQyRxan6srXUPBtj3PTxQFkZJAiwoUpmvtrxKZu4zfsnr3pqyy2vthpkwuoVq
xprv9xWkBDfyBXmZsA85GyWj9uYPyoQv826YAadKWMaaEosNrFBKgj2TqWuiWY3zuqxYGpHfv9cnGj5P7e8EskpzKL1Y8Gk9aX6QbryA5raK73p
xprv9xWkBDfyBXmZv2q3N66hhZ8DAcEnQDnXML1J62krJAcf7Xb1HJwuW2VMJQrCofY2jtFXdiEY8UsRNJfqK6DAdyZXoMvtaLHyWQx3FS4A9zw
xprv9xWkBDfyBXmZw4jEYXUHYc9fT25k9irP87n2RqfJ5bqbjKdT84Mm7Wtc2xmzFuKg7iYf7XFHKkSsaYKWKJbR54bnyAD9GzjUYbAYTtN4ruo
Generate the corresponding addresses:
$ ku P:foo -s 0/0-5 -a
1MrjE78H1R1rqdFrmkjdHnPUdLCJALbv3x
1AnYyVEcuqeoVzH96zj1eYKwoWfwte2pxu
1GXr1kZfxE1FcK6ZRD5sqqqs5YfvuzA1Lb
116AXZc4bDVQrqmcinzu4aaPdrYqvuiBEK
1Cz2rTLjRM6pMnxPNrRKp9ZSvRtj5dDUML
1WstdwPnU6HEUPme1DQayN9nm6j7nDVEM
Generate the corresponding WIFS:
$ ku P:foo -s 0/0-5 -W
L5a4iE5k9gcJKGqX3FWmxzBYQc29PvZ6pgBaePLVqT5YByEnBomx
Kyjgne6GZwPGB6G6kJEhoPbmyjMP7D5d3zRbHVjwcq4iQXD9QqKQ
L4B3ygQxK6zH2NQGxLDee2H9v4Lvwg14cLJW7QwWPzCtKHdWMaQz
L2L2PZdorybUqkPjrmhem4Ax5EJvP7ijmxbNoQKnmTDMrqemY8UF
L2oD6vA4TUyqPF8QG4vhUFSgwCyuuvFZ3v8SKHYFDwkbM765Nrfd
KzChTbc3kZFxUSJ3Kt54cxsogeFAD9CCM4zGB22si8nfKcThQn8C
Check that it works by choosing a BIP32 string (the one corresponding to subkey 0/3):
$ ku -W xprv9xWkBDfyBXmZsA85GyWj9uYPyoQv826YAadKWMaaEosNrFBKgj2TqWuiWY3zuqxYGpHfv9cnGj5P7e8EskpzKL1Y8Gk9aX6QbryA5raK73p
L2L2PZdorybUqkPjrmhem4Ax5EJvP7ijmxbNoQKnmTDMrqemY8UF
$ ku -a xprv9xWkBDfyBXmZsA85GyWj9uYPyoQv826YAadKWMaaEosNrFBKgj2TqWuiWY3zuqxYGpHfv9cnGj5P7e8EskpzKL1Y8Gk9aX6QbryA5raK73p
116AXZc4bDVQrqmcinzu4aaPdrYqvuiBEK
Yep, looks familiar.
From secret exponent:
$ ku 1
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
Litecoin version:
$ ku -nL 1
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 : 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 testnet address : mrCDrCybB6J1vRfbwM5hemdJz73FwDBC8r
uncompressed : mtoKs9V381UAhUia3d7Vb9GNak8Qvmcsme
From hash160:
$ ku 751e76e8199196d454941c45d1b3a323f1433bd6
input : 751e76e8199196d454941c45d1b3a323f1433bd6
network : Bitcoin
hash160 : 751e76e8199196d454941c45d1b3a323f1433bd6
Bitcoin address : 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
As a Dogecoin address:
$ ku -nD 751e76e8199196d454941c45d1b3a323f1433bd6
input : 751e76e8199196d454941c45d1b3a323f1433bd6
network : Dogecoin
hash160 : 751e76e8199196d454941c45d1b3a323f1433bd6
Dogecoin address : DFpN6QqFfUm3gKNaxN6tNcab1FArL9cZLE
tx
--
The command-line utility ```tx``` will display transactions in human-readable form, fetch base transactions from pycoin's transaction cache or from web services (blockchain.info, blockr.io, biteasy.com are currently supported), merge transactions, add or delete inputs or outputs, and sign transactions.
Examples:
View the famous "pizza" transaction [PIZZA]:
$ tx 49d2adb6e476fa46d8357babf78b1b501fd39e177ac7833124b3f67b17c40c2a
warning: consider setting environment variable PYCOIN_CACHE_DIR=~/.pycoin_cache to cache transactions fetched via web services
warning: no service providers found for get_tx; consider setting environment variable PYCOIN_SERVICE_PROVIDERS=BLOCKR_IO:BLOCKCHAIN_INFO:BITEASY:BLOCKEXPLORER
usage: tx [-h] [-t TRANSACTION_VERSION] [-l LOCK_TIME] [-n NETWORK] [-a]
[-i address] [-f path-to-private-keys] [-g GPG_ARGUMENT]
[--remove-tx-in tx_in_index_to_delete]
[--remove-tx-out tx_out_index_to_delete] [-F transaction-fee] [-u]
[-b BITCOIND_URL] [-o path-to-output-file]
argument [argument ...]
tx: error: can't find Tx with id 49d2adb6e476fa46d8357babf78b1b501fd39e177ac7833124b3f67b17c40c2a
Oops! We don't have web services set up. Let's do that now.
$ PYCOIN_CACHE_DIR=~/.pycoin_cache
$ PYCOIN_SERVICE_PROVIDERS=BLOCKR_IO:BLOCKCHAIN_INFO:BITEASY:BLOCKEXPLORER
$ export PYCOIN_CACHE_DIR PYCOIN_SERVICE_PROVIDERS
It's not done automatically so a command-line tool won't leak potentially private information about what transactions you're interested in to a third party web site. If you don't care, you could put these lines into your .profile.
Let's try again:
$ tx 49d2adb6e476fa46d8357babf78b1b501fd39e177ac7833124b3f67b17c40c2a
Version: 1 tx hash 49d2adb6e476fa46d8357babf78b1b501fd39e177ac7833124b3f67b17c40c2a 159 bytes
TxIn count: 1; TxOut count: 1
Lock time: 0 (valid anytime)
Input:
0: (unknown) from 1e133f7de73ac7d074e2746a3d6717dfc99ecaa8e9f9fade2cb8b0b20a5e0441:0
Output:
0: 1CZDM6oTttND6WPdt3D6bydo7DYKzd9Qik receives 10000000.00000 mBTC
Total output 10000000.00000 mBTC
including unspents in hex dump since transaction not fully signed
010000000141045e0ab2b0b82cdefaf9e9a8ca9ec9df17673d6a74e274d0c73ae77d3f131e000000004a493046022100a7f26eda874931999c90f87f01ff1ffc76bcd058fe16137e0e63fdb6a35c2d78022100a61e9199238eb73f07c8f209504c84b80f03e30ed8169edd44f80ed17ddf451901ffffffff010010a5d4e80000001976a9147ec1003336542cae8bded8909cdd6b5e48ba0ab688ac00000000
** can't validate transaction as source transactions missing
The final line appears because to validate the transactions' signatures, you technically need to the source transactions. So let's add ```-a``` to augment the transactions with source information.
$ tx -a 49d2adb6e476fa46d8357babf78b1b501fd39e177ac7833124b3f67b17c40c2a
warning: transaction fees recommendations casually calculated and estimates may be incorrect
warning: transaction fee lower than (casually calculated) expected value of 0.1 mBTC, transaction might not propogate
Version: 1 tx hash 49d2adb6e476fa46d8357babf78b1b501fd39e177ac7833124b3f67b17c40c2a 159 bytes
TxIn count: 1; TxOut count: 1
Lock time: 0 (valid anytime)
Input:
0: 17WFx2GQZUmh6Up2NDNCEDk3deYomdNCfk from 1e133f7de73ac7d074e2746a3d6717dfc99ecaa8e9f9fade2cb8b0b20a5e0441:0 10000000.00000 mBTC sig ok
Output:
0: 1CZDM6oTttND6WPdt3D6bydo7DYKzd9Qik receives 10000000.00000 mBTC
Total input 10000000.00000 mBTC
Total output 10000000.00000 mBTC
Total fees 0.00000 mBTC
010000000141045e0ab2b0b82cdefaf9e9a8ca9ec9df17673d6a74e274d0c73ae77d3f131e000000004a493046022100a7f26eda874931999c90f87f01ff1ffc76bcd058fe16137e0e63fdb6a35c2d78022100a61e9199238eb73f07c8f209504c84b80f03e30ed8169edd44f80ed17ddf451901ffffffff010010a5d4e80000001976a9147ec1003336542cae8bded8909cdd6b5e48ba0ab688ac00000000
all incoming transaction values validated
We can see the transactions have been cached.
$ ls ~/.pycoin_cache/txs/
1e133f7de73ac7d074e2746a3d6717dfc99ecaa8e9f9fade2cb8b0b20a5e0441_tx.bin
49d2adb6e476fa46d8357babf78b1b501fd39e177ac7833124b3f67b17c40c2a_tx.bin
Now, let's create a new transaction with some Satoshi coinbase coins. In block #1, we see a coinbase transaction to 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX. Let's use fetch_unspent to find all coins in this address.
$ fetch_unspent 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX
a3a6f902a51a2cbebede144e48a88c05e608c2cce28024041a5b9874013a1e2a/0/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/333000
cea36d008badf5c7866894b191d3239de9582d89b6b452b596f1f1b76347f8cb/31/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/10000
065ef6b1463f552f675622a5d1fd2c08d6324b4402049f68e767a719e2049e8d/86/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/10000
a66dddd42f9f2491d3c336ce5527d45cc5c2163aaed3158f81dc054447f447a2/0/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/10000
ffd901679de65d4398de90cefe68d2c3ef073c41f7e8dbec2fb5cd75fe71dfe7/0/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/100
d658ab87cc053b8dbcfd4aa2717fd23cc3edfe90ec75351fadd6a0f7993b461d/5/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/911
36ebe0ca3237002acb12e1474a3859bde0ac84b419ec4ae373e63363ebef731c/1/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/100000
fd87f9adebb17f4ebb1673da76ff48ad29e64b7afa02fda0f2c14e43d220fe24/0/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/1
dfdf0b375a987f17056e5e919ee6eadd87dad36c09c4016d4a03cea15e5c05e3/1/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/1337
cb2679bfd0a557b2dc0d8a6116822f3fcbe281ca3f3e18d3855aa7ea378fa373/0/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/1337
d6be34ccf6edddc3cf69842dce99fe503bf632ba2c2adb0f95c63f6706ae0c52/1/76a914119b098e2e980a229e139a9ed01a469e518e6f2688ac/2000000
0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098/0/410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac/5000000000
Wow, that yields a lot of options. The last one is the coinbase source from block #1. Let's write a transaction that sends these coins to my donation address.
$ tx 0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098/0/410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac/5000000000 1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T -o tx.bin
all incoming transaction values validated
$ ls -l tx.bin
-rw-r--r-- 1 kiss staff 161 Apr 27 18:23 tx.bin
Now, let's dump it.
$ tx tx.bin
warning: transaction fees recommendations casually calculated and estimates may be incorrect
Version: 1 tx hash 3d36aed60ecb311a55a6329f5c2af785f06e147fc35b7678eb798eca7f603c83 85 bytes
TxIn count: 1; TxOut count: 1
Lock time: 0 (valid anytime)
Input:
0: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from 0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098:0 50000.00000 mBTC BAD SIG
Output:
0: 1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T receives 49999.90000 mBTC
Total input 50000.00000 mBTC
Total output 49999.90000 mBTC
Total fees 0.10000 mBTC
including unspents in hex dump since transaction not fully signed
0100000001982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e0000000000ffffffff01f0ca052a010000001976a914cd5dc792f0abb0aa8ba4ca36c9fe5eda8e495ff988ac0000000000f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac
all incoming transaction values validated
We see a transaction that sends most of the 50 BTC to a new address. The signature is not correct though. If we had the private key, we could sign it like this:
$ tx tx.bin -f wifs.gpg -o signed_tx.bin
You need a passphrase to unlock the secret key for
user: "Richard Kiss <him@richardkiss.com>"
2048-bit ELG-E key, ID 681E71C8, created 1999-11-08 (main key ID DBD8AB6A)
gpg: encrypted with 2048-bit ELG-E key, ID 681E71C8, created 1999-11-08
"Richard Kiss <him@richardkiss.com>"
signing...
warning: 1 TxIn items still unsigned
all incoming transaction values validated
Yep, if the file passed to -f ends with ```.gpg```, then ```gpg -d``` is automatically invoked, and you can type your GPG passphrase. So ```tx``` plus ```gpg``` is actually a pretty reasonably secure solution! And if you keep your WIF.gpg file on an airgapped machine, this solves the problem of cold storage!
$ shasum tx.bin signed_tx.bin
3ba7db8417e0fe1aeb7b4a1cbf13880bf84f38bc tx.bin
3ba7db8417e0fe1aeb7b4a1cbf13880bf84f38bc signed_tx.bin
Unfortunately for me, this file didn't include the WIF to the outgoing transaction, so the transaction remains unsigned.
You can also use ```-i``` to fetch all unspents (via the web) for a given bitcoin address and split it up.
$ tx -F 85000 -i 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX 1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T 1KissEskteXTAXbh17qJYLtMes1B6kJxZj 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX/50
warning: transaction fees recommendations casually calculated and estimates may be incorrect
warning: transaction fee of 0.85 exceeds expected value of 0.1 mBTC
Version: 1 tx hash fb3551086baa047f4e8b55a28c275502b48c637c003b89dbececb3cab8897089 604 bytes
TxIn count: 12; TxOut count: 3
Lock time: 0 (valid anytime)
Inputs:
0: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from a3a6f902a51a2cbebede144e48a88c05e608c2cce28024041a5b9874013a1e2a:0 3.33000 mBTC BAD SIG
1: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from cea36d008badf5c7866894b191d3239de9582d89b6b452b596f1f1b76347f8cb:31 0.10000 mBTC BAD SIG
2: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from 065ef6b1463f552f675622a5d1fd2c08d6324b4402049f68e767a719e2049e8d:86 0.10000 mBTC BAD SIG
3: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from a66dddd42f9f2491d3c336ce5527d45cc5c2163aaed3158f81dc054447f447a2:0 0.10000 mBTC BAD SIG
4: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from ffd901679de65d4398de90cefe68d2c3ef073c41f7e8dbec2fb5cd75fe71dfe7:0 0.00100 mBTC BAD SIG
5: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from d658ab87cc053b8dbcfd4aa2717fd23cc3edfe90ec75351fadd6a0f7993b461d:5 0.00911 mBTC BAD SIG
6: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from 36ebe0ca3237002acb12e1474a3859bde0ac84b419ec4ae373e63363ebef731c:1 1.00000 mBTC BAD SIG
7: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from fd87f9adebb17f4ebb1673da76ff48ad29e64b7afa02fda0f2c14e43d220fe24:0 0.00001 mBTC BAD SIG
8: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from dfdf0b375a987f17056e5e919ee6eadd87dad36c09c4016d4a03cea15e5c05e3:1 0.01337 mBTC BAD SIG
9: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from cb2679bfd0a557b2dc0d8a6116822f3fcbe281ca3f3e18d3855aa7ea378fa373:0 0.01337 mBTC BAD SIG
10: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from d6be34ccf6edddc3cf69842dce99fe503bf632ba2c2adb0f95c63f6706ae0c52:1 20.00000 mBTC BAD SIG
11: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX from 0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098:0 50000.00000 mBTC BAD SIG
Outputs:
0: 1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T receives 25011.90818 mBTC
1: 1KissEskteXTAXbh17qJYLtMes1B6kJxZj receives 25011.90818 mBTC
2: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX receives 0.00050 mBTC
Total input 50024.66686 mBTC
Total output 50023.81686 mBTC
Total fees 0.85000 mBTC
including unspents in hex dump since transaction not fully signed
010000000c2a1e3a0174985b1a042480e2ccc208e6058ca8484e14debebe2c1aa502f9a6a30000000000ffffffffcbf84763b7f1f196b552b4b6892d58e99d23d391b1946886c7f5ad8b006da3ce1f00000000ffffffff8d9e04e219a767e7689f0402444b32d6082cfdd1a52256672f553f46b1f65e065600000000ffffffffa247f4474405dc818f15d3ae3a16c2c55cd42755ce36c3d391249f2fd4dd6da60000000000ffffffffe7df71fe75cdb52fecdbe8f7413c07efc3d268fece90de98435de69d6701d9ff0000000000ffffffff1d463b99f7a0d6ad1f3575ec90feedc33cd27f71a24afdbc8d3b05cc87ab58d60500000000ffffffff1c73efeb6333e673e34aec19b484ace0bd59384a47e112cb2a003732cae0eb360100000000ffffffff24fe20d2434ec1f2a0fd02fa7a4be629ad48ff76da7316bb4e7fb1ebadf987fd0000000000ffffffffe3055c5ea1ce034a6d01c4096cd3da87ddeae69e915e6e05177f985a370bdfdf0100000000ffffffff73a38f37eaa75a85d3183e3fca81e2cb3f2f8216618a0ddcb257a5d0bf7926cb0000000000ffffffff520cae06673fc6950fdb2a2cba32f63b50fe99ce2d8469cfc3ddedf6cc34bed60100000000ffffffff982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e0000000000ffffffff03a2241595000000001976a914cd5dc792f0abb0aa8ba4ca36c9fe5eda8e495ff988aca2241595000000001976a914cd5dc78d67a621ad4564aac6cc1f931b4d8be8d988ac32000000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac00000000c8140500000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac10270000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac10270000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac10270000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac64000000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac8f030000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688aca0860100000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac01000000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac39050000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac39050000000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac80841e00000000001976a914119b098e2e980a229e139a9ed01a469e518e6f2688ac00f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac
all incoming transaction values validated
Note that 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX was explicitly budgeted 50 satoshis. A custom fee of 85000 satoshis was paid, and the remainder was split between the other two addresses.
OK, let's try actually signing a transaction. Let's use the WIF for secret exponent 1.
$ ku -a -u 1
1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm
Investigation on blockchain.info show a transaction payable to this bitcoin address with id d61aa2a5f5bce59d2a57447134f7ce9ce9d29b5c471f4bf747c43bf82aa26c2a.
$ tx -u d61aa2a5f5bce59d2a57447134f7ce9ce9d29b5c471f4bf747c43bf82aa26c2a
d61aa2a5f5bce59d2a57447134f7ce9ce9d29b5c471f4bf747c43bf82aa26c2a/0/76a9149b92770a85b1252448ec69900e77f1371d6a620188ac/70594320
d61aa2a5f5bce59d2a57447134f7ce9ce9d29b5c471f4bf747c43bf82aa26c2a/1/76a91491b24bf9f5288532960ac687abb035127b1d28a588ac/12345678
** can't validate transaction as source transactions missing
The ```-u``` shows the unspents, which can be passed as inputs to tx.
$ tx d61aa2a5f5bce59d2a57447134f7ce9ce9d29b5c471f4bf747c43bf82aa26c2a/1/76a91491b24bf9f5288532960ac687abb035127b1d28a588ac/12345678 1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T -o tx.bin
all incoming transaction values validated
$ tx tx.bin
warning: transaction fees recommendations casually calculated and estimates may be incorrect
Version: 1 tx hash ab963a39df0e095bbd76840de90fe208e903d5d43e891ef245b217dbcd29a8a7 85 bytes
TxIn count: 1; TxOut count: 1
Lock time: 0 (valid anytime)
Input:
0: 1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm from d61aa2a5f5bce59d2a57447134f7ce9ce9d29b5c471f4bf747c43bf82aa26c2a:1 123.45678 mBTC BAD SIG
Output:
0: 1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T receives 123.35678 mBTC
Total input 123.45678 mBTC
Total output 123.35678 mBTC
Total fees 0.10000 mBTC
including unspents in hex dump since transaction not fully signed
01000000012a6ca22af83bc447f74b1f475c9bd2e99ccef7347144572a9de5bcf5a5a21ad60100000000ffffffff013e3abc00000000001976a914cd5dc792f0abb0aa8ba4ca36c9fe5eda8e495ff988ac000000004e61bc00000000001976a91491b24bf9f5288532960ac687abb035127b1d28a588ac
all incoming transaction values validated
Now, let's sign it.
$ tx tx.bin KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn -o signed_tx.hex
signing...
all incoming transaction values validated
$ cat signed_tx.hex
01000000012a6ca22af83bc447f74b1f475c9bd2e99ccef7347144572a9de5bcf5a5a21ad6010000008b48304502210084fd73b302520381dea1885efda58bc446653998864db7a2cd04906fc6d5536302206325303c8e50f84d25c95eff2849441382d4aafb2f678f636a6d164b721bf0f101410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ffffffff013e3abc00000000001976a914cd5dc792f0abb0aa8ba4ca36c9fe5eda8e495ff988ac00000000
$ tx -a signed_tx.hex
warning: transaction fees recommendations casually calculated and estimates may be incorrect
Version: 1 tx hash 0995cf6f55e1cf22f7c31f5ad52d111e897b0b9b7e37a1bb755a470324b4a2c4 224 bytes
TxIn count: 1; TxOut count: 1
Lock time: 0 (valid anytime)
Input:
0: 1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm from d61aa2a5f5bce59d2a57447134f7ce9ce9d29b5c471f4bf747c43bf82aa26c2a:1 123.45678 mBTC sig ok
Output:
0: 1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T receives 123.35678 mBTC
Total input 123.45678 mBTC
Total output 123.35678 mBTC
Total fees 0.10000 mBTC
01000000012a6ca22af83bc447f74b1f475c9bd2e99ccef7347144572a9de5bcf5a5a21ad6010000008b48304502210084fd73b302520381dea1885efda58bc446653998864db7a2cd04906fc6d5536302206325303c8e50f84d25c95eff2849441382d4aafb2f678f636a6d164b721bf0f101410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ffffffff013e3abc00000000001976a914cd5dc792f0abb0aa8ba4ca36c9fe5eda8e495ff988ac00000000
all incoming transaction values validated
Wow! It worked! (It wrote the output as hex because of the ".hex" suffix.)
So why not just broadcast this transaction and collect our winnings? Well, the coins have already been spent. Oh well.
Note that pycoin uses a deterministic algorithm to create the signatures, so if you try this at home, you will get the exact same transaction with the exact same 0995cf6f55e1cf22f7c31f5ad52d111e897b0b9b7e37a1bb755a470324b4a2c4 hash.
[PIZZA]: https://bitcointalk.org/index.php?topic=137.0
--------------
You can also use pycoin to create and validate keys programmatically.
>>> from pycoin.key import Key
>>> k = Key.from_text("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH")
>>> print(k.address())
1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
>>> print(k.hash160())
b'u\x1ev\xe8\x19\x91\x96\xd4T\x94\x1cE\xd1\xb3\xa3#\xf1C;\xd6'
>>> from pycoin.serialize import b2h
>>> print(b2h(k.hash160()))
751e76e8199196d454941c45d1b3a323f1433bd6
Compare to using ku:
$ ku 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
input : 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
network : Bitcoin mainnet
netcode : BTC
hash160 : 751e76e8199196d454941c45d1b3a323f1433bd6
Bitcoin mainnet address : 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
>>> from pycoin.key.validate import is_address_valid
>>> v = is_address_valid("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH")
>>> print(v)
'BTC'
# you can also specify certain networks, like Litecoin
>>> v = is_address_valid("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH", allowable_netcodes=["LTC"])
>>> print(v)
None
# not a valid LTC address
>>> v = is_address_valid("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH", allowable_types=["pay_to_script"])
>>> print(v)
None
# not a valid pay-to-script address (they start with a "3")
>>> v = is_address_valid("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH", allowable_types=["address"])
>>> print(v)
BTC
>>> from pycoin.key import Key
>>> k = Key(secret_exponent=1)
>>> print(k.address())
1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
>>> print(k.wif())
KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn
>>> print(k.as_text())
KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn
$ ku KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn
input : KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn
network : Bitcoin mainnet
netcode : BTC
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 mainnet address : 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
Bitcoin mainnet uncompressed : 1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm
Different networks have different representations of the same WIF.
$ ku -W 1
KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn
$ ku -W -n XTN 1
cMahea7zqjxrtgAbB7LSGbcQUr1uX1ojuat9jZodMN87JcbXMTcA
$ ku -W 1 -n DOGE
QNcdLVw8fHkixm6NNyN6nVwxKek4u7qrioRbQmjxac5TVoTtZuot
$ ku -W 1 -n LTC
T33ydQRKp4FCW5LCLLUB7deioUMoveiwekdwUwyfRDeGZm76aUjV
--------------
Fetch, parse a tx, stream a tx
$ tx 0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098 -o tx.out
all incoming transaction values validated
>>> from pycoin.tx import Tx
>>> tx = Tx.parse(open("tx.out", "rb"))
>>> print(tx)
Tx [0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098]
>>> print(tx.txs_in[0])
TxIn<COINBASE: 04ffff001d0104>
>>> print(tx.txs_out[0])
TxOut<5E+4 mbtc "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee OP_CHECKSIG">
>>> f1 = open("tx1.out", "wb")
>>> tx.stream(f1)
$ ls -l tx1.out
-rw-r--r-- 1 kiss staff 134 Jun 11 17:02 tx1.out
$ tx tx1.out
warning: transaction fees recommendations casually calculated and estimates may be incorrect
warning: transaction fee lower than (casually calculated) expected value of 0.1 mBTC, transaction might not propogate
Version: 1 tx hash 0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098 134 bytes
TxIn count: 1; TxOut count: 1
Lock time: 0 (valid anytime)
Input:
0: COINBASE 50000.00000 mBTC
Output:
0: 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX receives 50000.00000 mBTC
Total input 50000.00000 mBTC
Total output 50000.00000 mBTC
Total fees 0.00000 mBTC
01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000
all incoming transaction values validated
-----------
A simple script to grab and spend coins.
#!/usr/bin/env python
from pycoin.key import Key
from pycoin.key.validate import is_address_valid, is_wif_valid
from pycoin.services import spendables_for_address
from pycoin.tx.tx_utils import create_signed_tx
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")
tx = create_signed_tx(spendables, payables=[dst_address], wifs=[wif])
print("here is the signed output transaction")
print(tx.as_hex())