SlideShare a Scribd company logo
Bitcoin Developer Guide
Roger
Bitcoin
▚ Bitcoin is a worldwide cryptocurrency and digital payment system
invented by Satoshi Nakamoto.
▚ The system is peer-to-peer, and transactions take place between
users directly, without an intermediary.
▚ Transactions are verified by network nodes and recorded in a
public distributed ledger called a blockchain.
2
Blockchain
▚ The blockchain data structure is an ordered, back-linked list of
blocks of transactions.
▚ Every block must include one or more transactions.
▚ The first one of these transactions must be a coinbase transaction.
3
Blockchain
4
Merkle Tree
▚ A merkle tree, also known as a binary hash tree, is a data structure
used for efficiently summarizing and verifying the integrity of
large sets of data.
▚ 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.
5
Merkle Tree (cont.)
H~A~ = SHA256(SHA256(TxA))
H~AB~ = SHA256(SHA256(H~A~ + H~B~))
6
Merkle Tree (cont.)
7
Bitcoin overview
8
Account model
vs
UTXO (Unspent Transaction Outputs)
9
Account model
▚ A mined 50
▚ A pay 30 to B
▚ B pay 20 to C & A pay 10 to C
Account Balances
A 50
B 0
C 0
Account Balances
A 20
B 30
C 0
Account Balances
A 10
B 10
C 30 10
UTXO & Change
Example 11
Private Key
x
Public Key
x
Bitcoin Address
12
How to create a bitcoin address?
▚ Relationships among Private Key, Public Key and Address.
13
Step1. Generate Private Key
▚ The private key is, in essence, just a really big random number
(256-bits) which can easily be generated offline with a sufficient
source of randomness.
var privateKey =
'8F72F6B29E6E225A36B68DFE333C7CE5E55D83249D3D2CD6332671F
A445C4DD3';
14
Step2. Generate Public Key
▚ Bitcoin uses the Elliptic Curve Digital Signature Algorithm (ECDSA)
with the secp256k1 curve.
secp256k1 ===> y2 = (x3 + 7)
K (PublicKey) = k (PrivateKey) * G (base point)
G = 04 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9
59F2815B 16F81798 483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448
A6855419 9C47D08F FB10D4B8 (NIST)
15
P
2P = (P+P)
A
B
C = (A+B)
Elliptic Curve
▚ K (PublicKey) = k (PrivateKey) * G (base point)
16
Elliptic Curve
▚ K (PublicKey) = k (PrivateKey) * G (base point)
17
secp256k1 ===> y2 mod p = (x3 + 7) mod p,
p = 2256 - 232 - 29 - 28 - 27 - 26 - 24 - 1
K (PublicKey) = k (PrivateKey) * G (base point)
G = 04 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB
2DCE28D9 59F2815B 16F81798 483ADA77 26A3C465 5DA4FBFC
0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8 (NIST)
Step2. Generate Public Key (cont.)
Public Key x-axis:
06CCAE7536386DA2C5ADD428B099C7658814CA837F94FADE3
65D0EC6B1519385
Public Key y-axis:
FF83EC5F2C0C8F016A32134589F7B9E97ACBFEFD2EF12A91FA6
22B38A1449EEB
Public Key:
0406CCAE7536386DA2C5ADD428B099C7658814CA837F94FAD
E365D0EC6B1519385FF83EC5F2C0C8F016A32134589F7B9E97A
CBFEFD2EF12A91FA622B38A1449EEB
18
Step3. Public Key to Public Key Hash
▚ Publick key hash = RIPEMD-160( SHA256( Public Key ) ), called
HASH160.
Public Key:
0406CCAE7536386DA2C5ADD428B099C7658814CA83
7F94FADE365D0EC6B1519385FF83EC5F2C0C8F016A3
2134589F7B9E97ACBFEFD2EF12A91FA622B38A1449EE
B
Hash160:
0b14f003d63ab31aef5fedde2b504699547dd1f6
19
Step4. Public Key Hash to Bitcoin Address
20
Step4. Public Key Hash to Bitcoin Address
Hash160:
0b14f003d63ab31aef5fedde2b504699547dd1f6
SHA256(SHA256(Hash160)):
869ac57b83ccf75ca9da8895823562fffb611e3c29
7d9c2d4612aeeb32850078
New payload:
000b14f003d63ab31aef5fedde2b504699547dd1f
6869ac57b
Base58checkEncode:
1QCXRuoxWo5Bya9NxHaVBArBQYhatHJrU7
21
Keys summary
22Example
Wallet
23
Wallets
▚ Bitcoin wallets contain keys, not coins. Each user has a wallet
containing keys. Wallets are really keychains containing pairs of
private/public keys.
▚ Users sign transactions with the keys, thereby proving they own
the transaction outputs
24
Wallet Import Format (WIF)
25
Nondeterministic (Random) Wallets
▚ Wallets were simply
collections of randomly
generated private keys.
▚ This type of wallet is
nicknamed "Just a Bunch Of
Keys" (JBOK).
26
Deterministic (Seeded) Wallets
▚ Deterministic, or "seeded" wallets are wallets that contain private
keys that are all derived from a common seed, through the use of
a one-way hash function.
▚ The seed allows a user to easily backup and restore a wallet
without needing any other information.
27
Mnemonic Code Words
▚ Mnemonic codes are
English word sequences
that represent (encode) a
random number used as a
seed to derive a
deterministic wallet.
28
Hierarchical Deterministic Wallets
▚ Hierarchical deterministic
wallets contain keys derived
in a tree structure, such that
a parent key can derive a
sequence of children keys,
each of which can derive a
sequence of grandchildren
keys, and so on, to an
infinite depth.
29
HD Wallet - Create Master Key
▚ HD wallets are created from
a single root seed.
▚ Everything else in the HD
wallet is deterministically
derived from this root seed,
which makes it possible to
re-create the entire HD
wallet from that seed.
30
HD Wallet - Create Child Private Key
▚ HD wallets use a child key
derivation (CKD) function to
derive children keys from
parent keys.
▚ The CKD are based on a one-
way hash function that
combines:
� A parent private or public key.
� A seed called a chain code.
� An index number (32 bits).
31
point((parent_private + lefthand_hash) % G) == child_private
*********************************************************************
point(child_private) == child_public
parent_public + point(lefthand_hash) == child_public
HD Wallet - Extended Key
▚ The two essential ingredients are the key and chain code, and
combined these are called an extended key.
▚ An extended key consists of a private or public key and chain code,
therefore it can create children, generating its own branch in the
tree structure. Sharing an extended key gives access to the entire
branch.
32
Chain Code Private Key / Public Key Extended Private / Public Key
Base58 encode
HD Wallet - Extended Key (cont.)
▚ Extended Key Format.
� 4 bytes, version, mainnet public: 0x0488B21E, mainnet private:
0x0488ADE4, testnet public: 0x043587CF, testnet private: 0x04358394
� 1 byte, depth
� 4 bytes, fingerprint, the first 4 bytes of HASH160( Public Key )
� 4 bytes, child number, n-th child
� 32 bytes, chain code
Base58 encode 33
HD Wallet - Create Child Public Key
▚ An Extended public key can
be used to create very
secure public-key-only
deployments where a server
or application has a copy of
an extended public key and
no private keys whatsoever.
▚ Cannot spend any of the
money sent to those
addresses.
34
HD Wallet - Hardened key derivation
▚ The extended public key contains the chain code, if a child private
key leaked, it can be used with the chain code to derive all the
other child private keys.
35
HD Wallet - Hardened child key (cont.)
▚ Hardened derivation, which
"breaks" the relationship
between parent public key and
child chain code.
▚ The hardened derivation
function uses the parent
private key to derive the child
chain code, instead of the
parent public key.
36
Transaction
37
Bitcoin Transaction Message Format
38
Bitcoin Transaction Message Raw Data
/* input */
01 // number of inputs
e34ac1e2baac09c366fce1c2245536bda8f7db0f6685862aecf53ebd69f9a89c // tx id
00000000 // input index
00 // unlocking script length
ffffffff // sequence
/* input end */
/* output */
02 // number of outputs
a025260000000000 // amount
19 // locking script length
76a914d90d36e98f62968d2bc9bbd68107564a156a9bcf88ac // locking script
5062250000000000 // amount
19 // locking script length
76a91407bdb518fa2e6089fd810235cf1100c9c13d1fd288ac // locking script
/* output end */
00000000 // 4 bytes locktime
39
Transaction Script & Script Language
▚ Bitcoin's scripting language is called a stack-based language
because it uses a data structure called a stack.
▚ The scripting language executes the script by processing each
item from left to right.
40
Transaction Script & Script Language (cont.)
41
Script Construction (Lock + Unlock)
▚ Locking script is an encumbrance placed on an output, and it
specifies the conditions that must be met to spend the output in
the future.
▚ Unlocking script is a script that "solves" the conditions placed on
an output by a locking script and allows the output to be spent.
42
Bitcoin Script Construction
43
Standard Transactions
▚ pay-to-public-key-hash (P2PKH)
▚ pay-to-public-key (P2PK)
▚ multi-signature (limited to 15 keys) (MS)
▚ pay-to-script-hash (P2SH)
▚ data output (OP_RETURN) 44
pay-to-public-key-hash (P2PKH)
▚ The vast majority of transactions processed on the bitcoin
network are P2PKH transactions. These contain a locking script
that encumbers the output with a public key hash, more
commonly known as a bitcoin address.
45
pay-to-public-key-hash (P2PKH) (cont.)
46
▚ Locking script
▚ Unlocking script
▚ Combined
pay-to-public-key (P2PK)
<Public Key A> OP_CHECKSIG
<Signature from Private Key A>
<Signature from Private Key A><Public Key A> OP_CHECKSIG
47
multi-signature (MS)
▚ An M-of-N scheme, where N is the total number of keys and M is
the threshold of signatures required for validation.
▚ Locking script
▚ Unlocking script
▚ Combined (2-3 multi-signature)
M <Public Key 1> <Public Key 2> ... <Public Key N> N OP_CHECKMULTISIG
OP_0 <Signature B> <Signature C>
OP_0 <Signature B> <Signature C> 2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG
48
pay-to-script-hash (P2SH)
▚ Multi-sig would be about five times larger than a simple payment
transaction, because this script contains very long public keys.
■ Extra-large transaction would increase fees
■ UTXO set in RAM in full node
49
pay-to-script-hash (P2SH) (cont.)
MultiSig
2
0 4 C 1 6 B 8 6 9 8 A 9 A B F 8 4 2 5 0 A 7 C 3 E A 7 E E -
DEF9897D1C8C6ADF47F06CF73370D74DCCA01CDCA79DCC5C395D7EEC6984D83F1F50C900A
24DD47F569FD4193AF5DE762C58704A2192968D8655D6A935BEAF2CA23E3FB87A3495E7AF
308EDF08DAC3C1FCBFC2C75B4B0F4D0B1B70CD2423657738C0C2B1D5CE65C97D78D0E3422
4858008E8B49047E63248B75DB7379BE9CDA8CE5751D16485F431E46117B9D0C1837C9D57
37812F393DA7D4420D7E1A9162F0279CFC10F1E8E8F3020DECDBC3C0DD389D99779650421
D65CBD7149B255382ED7F78E946580657EE6FDA162A187543A9D85BAAA93A4AB3A8F044DA
-
DA618D087227440645ABE8A35DA8C5B73997AD343BE5C2AFD94A5043752580AFA1EC-
ED3C68D446BCAB69AC0A7DF50D56231BE0AABF1FDEEC78A6A45E394BA29A1EDF518C022DD
618DA774D207D137AAB59E0B000EB7ED238F4D800 5 OP_CHECKMULTISIG
P2SH
54c557e07dde5bb6cb791c7a540e0a4796f5e97
50
pay-to-script-hash (P2SH) (cont.)
Redeem
Script
20-bytes
20-bytes
P2SH Address
0x05
0x05
51
data-output (OP_RETURN)
▚ OP_RETURN allows developers to add 40 bytes of nonpayment
data to a transaction output.
▚ OP_RETURN outputs are recorded on the blockchain, but they are
not stored in the UTXO set and therefore do not bloat the UTXO
memory pool.
▚ Locking script
▚ No unlocking script
OP_RETURN <data>
52
data-output (OP_RETURN) (cont.)
53
CoinJoin
▚ Bitcoin anonymous weaknesses
� Fiat money exchange
� Transactions are open
� The summary of the transaction
will expose the owner of the other
address
◇ CoinJoin
� communication is not encrypted
Example
54
Bitcoin Network
55
Nodes Types and Roles
56
The extended bitcoin network
57
Network Discovery
▚ When a new node boots up,
it must discover other
bitcoin nodes on the
network in order to
participate.
58
Network Discovery (cont.)
▚ The new node will send an
addr to its neighbors. The
neighbors will, in turn, forward
the addr message to their
neighbors.
▚ The newly connected node can
send getaddr to the neighbors,
asking them to return a list of
IP addresses of other peers.
59
Exchange Inventory
▚ The longer blockchain peer will
identify the first 500 blocks to
share and transmit their hashes
using an inv(inventory)
message.
▚ The node missing these blocks
will then retrieve them, by
issuing a series of getdata
messages requesting the full
block data
60
Simplified Payment Verification Node (SPV)
▚ SPV nodes download only
the block headers and do
not download the
transactions included in
each block.
61
SPV + Bloom Filter
▚ A bloom filter is a probabilistic search filter, a way to describe a
desired pattern without specifying it exactly.
▚ Bloom filters offer an efficient way to express a search pattern
while protecting privacy.
▚ They are used by SPV nodes to ask their peers for transactions
matching a specific pattern, without revealing exactly which
addresses they are searching for.
62
SPV + Bloom Filter (cont.)
▚ An example of a simplistic bloom filter, with a 16-bit field and
three hash functions.
63
SPV + Bloom Filter (cont.)
64
SPV + Bloom Filter (cont.)
65
SPV + Bloom Filter (cont.)
66
SPV + Bloom Filter (cont.)
67
▚ Peers will send a merkleblock message that contains only block
headers for blocks matching the filter and a merkle path for each
matching transaction.
▚ Merkle path: HABCDEFGH + HIJ + HK + HK + HMNOP
SPV + Bloom Filter (cont.)
68
Mining and Consensus
69
Bitcoin Economics and Currency Creation
▚ Each block, generated on
average every 10 minutes,
contains entirely new bitcoins.
▚ Every 210,000 blocks (4 years),
the currency issuance rate is
decreased by 50%.
▚ In approximately 2140, almost
21 million bitcoins, will be
issued. 70
Independent Verification of Transactions
▚ Every bitcoin node that receives a transaction will first verify the
transaction, while invalid transactions are discarded at the first
node that encounters them.
▚ Each node verifies every transaction against a long checklist of
criteria:
■ The transaction's syntax and data structure must be correct.
■ Neither lists of inputs or outputs are empty.
■ …...
71
Transaction Age, Fees, and Priority
▚ To construct the candidate block, bitcoin node selects
transactions from the memory pool by applying a priority metric
to each transaction and adding the highest priority transactions
first.
▚ The first 50 KB of transaction space in a block are set aside for
high-priority transactions even if they carry zero fees.
Priority = Sum (Value of input * Input Age) / Transaction Size
High Priority > 100,000,000 satoshis * 144 blocks / 250 bytes = 57,600,000
72
Coinbase
▚ The first transaction added to the block is a special transaction,
called coinbase transaction. This transaction is constructed by
miner's node and is its reward for the mining effort.
▚ Coinbase do not have an unlocking script field. Instead, this field is
replaced by coinbase data, which must be between 2 and 100
bytes.
Total Fees = Sum(Inputs) - Sum(Outputs)
Coinbase
Example
AntPool
Coinbase 73
Mining - Constructing the Block Header
74
Mining - Target
▚ “Bits”first byte is a hexadecimal exponent, while the next part is
the coefficient.
■ Ex, Block: 277316, Bits: 0x1903a30c
75
Target = coefficient * 2^(8 * (exponent - 3))
Example
Mining - Difficulty Target and Retargeting
▚ To keep the block generation time at 10 minutes, the difficulty of
mining must be adjusted to account for these changes.
▚ Every 2016 blocks, all nodes retarget the proof-of-work difficulty.
■ If the network is finding blocks faster than every 10 minutes, the
difficulty increases.
■ If block discovery is slower than expected, the difficulty decreases.
76
New Difficulty = Old Difficulty * (Actual Time of Last 2016 Blocks / 20160 minutes)
Example
Blockchain Forks
▚ Because the blockchain is a decentralized data structure, different copies
of it are not always consistent.
▚ Blocks might arrive at different nodes at different times, causing the
nodes to have different perspectives of 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.
77
Blockchain Forks (cont.)
78
Blockchain Forks (cont.)
79
Blockchain Forks (cont.)
80
Blockchain Forks (cont.)
81
Blockchain Forks (cont.)
AntPool
475562, 477981
82
Mining Pools
▚ A mining pool is the pooling of resources by miners, who share their
processing power over a network.
▚ A "share" is awarded to members of the mining pool who present a valid
proof of work that their miner solved.
▚ Reward types
■ Pay Per Last N Shares (PPLNS)
■ Pay Per Share (PPS)
■ Full Pay Per Share (FPPS) 83
Consensus Attacks
▚ A miner or group of miners
can achieve a significant
share of the mining power,
they can attack the
consensus mechanism so as
to disrupt the security and
availability of the bitcoin
network.
� 51% Attack
� Double spending
A sent 100 BTC to B.
A sent 1 BTC to B.
84
Thanks!
x
Any questions?
85

More Related Content

PPTX
The 3rd generation blockchain
PPTX
bitcoin_presentation
PDF
Blockchain introduction
ODP
Blockchain technology in (life) sciences
PDF
Blockchain
PPTX
Best practices to build secure smart contracts
PDF
Boolberry reduces blockchain bloat
ODP
Intro to Blockchain - And, by the way, what the heck is proof-of-work?
The 3rd generation blockchain
bitcoin_presentation
Blockchain introduction
Blockchain technology in (life) sciences
Blockchain
Best practices to build secure smart contracts
Boolberry reduces blockchain bloat
Intro to Blockchain - And, by the way, what the heck is proof-of-work?

What's hot (20)

PDF
Bitcoins Math
PPTX
BitCoin Protocol
PDF
Bitcoin Blockchain - Under the Hood
PDF
RSK (Rootstock) - Smarter Bitcoin
PPTX
Blockchain Corporate Style
PPTX
Bitcoin Internal
PPTX
Bitcoin, Blockchain and the Crypto Contracts - Part 2
PDF
Economías criptográficas
PDF
Introduction to BigchainDB
PDF
Trent McConaghy- BigchainDB
PDF
Blockchain: life of a blockchain transaction
PPTX
Mining Opportunities of Block Chain and BitCoin
PDF
Blockchain - a basic overview
PDF
Bitcoin : A fierce Decentralized internet currency
PPTX
Blockchain data structures and fundamental
PDF
Build your first blockchain
PDF
Доклад Владимира Бичева на третьем митапе сообщества блокчейн-разработчиков С...
PDF
Blockchain intro at framework
PDF
Blockchain and bitcoin
PDF
Blockchain Programming
Bitcoins Math
BitCoin Protocol
Bitcoin Blockchain - Under the Hood
RSK (Rootstock) - Smarter Bitcoin
Blockchain Corporate Style
Bitcoin Internal
Bitcoin, Blockchain and the Crypto Contracts - Part 2
Economías criptográficas
Introduction to BigchainDB
Trent McConaghy- BigchainDB
Blockchain: life of a blockchain transaction
Mining Opportunities of Block Chain and BitCoin
Blockchain - a basic overview
Bitcoin : A fierce Decentralized internet currency
Blockchain data structures and fundamental
Build your first blockchain
Доклад Владимира Бичева на третьем митапе сообщества блокчейн-разработчиков С...
Blockchain intro at framework
Blockchain and bitcoin
Blockchain Programming
Ad

Similar to Bitcoin developer guide (20)

PPTX
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
PPTX
Bitcoin
PPTX
Bitcoin and it's security related to transaction.pptx
PPTX
Intro to blockchain
PPTX
Bitcoin I.pptx
PPTX
“Technical Intro to Blockhain” by Yurijs Pimenovs from Paybis at CryptoCurren...
PPTX
Cryptocurrencies for Everyone (Dmytro Pershyn Technology Stream)
PDF
Bitcoin Transaction Malleability
PDF
Tmc mastering bitcoins ppt
PDF
Introduction to Bitcoin for programmers
PDF
Bitcoin for programmers - part 1 version 2
PPTX
Blockchain and Bitcoin
PDF
Security Model of Blockchain
PPTX
Presentation topalidis giorgos
PPTX
Presentation_Topalidis_Giorgos
PPTX
J.burke HackMiami6
PPTX
Bitcoin cryptography
PDF
sfrontori-bitcoin-technical intro-meetup2014
PPTX
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)
PPTX
SMART Seminar Series: "Blockchain and its Applications". Presented by Prof Wi...
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
Bitcoin
Bitcoin and it's security related to transaction.pptx
Intro to blockchain
Bitcoin I.pptx
“Technical Intro to Blockhain” by Yurijs Pimenovs from Paybis at CryptoCurren...
Cryptocurrencies for Everyone (Dmytro Pershyn Technology Stream)
Bitcoin Transaction Malleability
Tmc mastering bitcoins ppt
Introduction to Bitcoin for programmers
Bitcoin for programmers - part 1 version 2
Blockchain and Bitcoin
Security Model of Blockchain
Presentation topalidis giorgos
Presentation_Topalidis_Giorgos
J.burke HackMiami6
Bitcoin cryptography
sfrontori-bitcoin-technical intro-meetup2014
Crypto Wallets: A Technical Perspective (Nakov at OpenFest 2018)
SMART Seminar Series: "Blockchain and its Applications". Presented by Prof Wi...
Ad

More from 承翰 蔡 (12)

PDF
Notes for AWS IoT
PPTX
Node-red Chatbot module
PPTX
PPTX
How to create ethereum token (A plan coin ico)
PPTX
Web of things introduction
PPTX
AWS IoT introduction
PPTX
IoT開發平台NodeMCU
PPTX
Node mcu x raspberrypi2 x mqtt
PPTX
Arduino mqtt client introduction
PPTX
Webduino introduction
PDF
MongoDB 3.0.0 vs 2.6.x vs 2.4.x Benchmark
PPTX
Kimono sharing
Notes for AWS IoT
Node-red Chatbot module
How to create ethereum token (A plan coin ico)
Web of things introduction
AWS IoT introduction
IoT開發平台NodeMCU
Node mcu x raspberrypi2 x mqtt
Arduino mqtt client introduction
Webduino introduction
MongoDB 3.0.0 vs 2.6.x vs 2.4.x Benchmark
Kimono sharing

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
KodekX | Application Modernization Development
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPT
Teaching material agriculture food technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Electronic commerce courselecture one. Pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
Big Data Technologies - Introduction.pptx
KodekX | Application Modernization Development
Chapter 3 Spatial Domain Image Processing.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Teaching material agriculture food technology
The AUB Centre for AI in Media Proposal.docx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Electronic commerce courselecture one. Pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectroscopy.pptx food analysis technology
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
“AI and Expert System Decision Support & Business Intelligence Systems”
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Per capita expenditure prediction using model stacking based on satellite ima...

Bitcoin developer guide

  • 2. Bitcoin ▚ Bitcoin is a worldwide cryptocurrency and digital payment system invented by Satoshi Nakamoto. ▚ The system is peer-to-peer, and transactions take place between users directly, without an intermediary. ▚ Transactions are verified by network nodes and recorded in a public distributed ledger called a blockchain. 2
  • 3. Blockchain ▚ The blockchain data structure is an ordered, back-linked list of blocks of transactions. ▚ Every block must include one or more transactions. ▚ The first one of these transactions must be a coinbase transaction. 3
  • 5. Merkle Tree ▚ A merkle tree, also known as a binary hash tree, is a data structure used for efficiently summarizing and verifying the integrity of large sets of data. ▚ 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. 5
  • 6. Merkle Tree (cont.) H~A~ = SHA256(SHA256(TxA)) H~AB~ = SHA256(SHA256(H~A~ + H~B~)) 6
  • 9. Account model vs UTXO (Unspent Transaction Outputs) 9
  • 10. Account model ▚ A mined 50 ▚ A pay 30 to B ▚ B pay 20 to C & A pay 10 to C Account Balances A 50 B 0 C 0 Account Balances A 20 B 30 C 0 Account Balances A 10 B 10 C 30 10
  • 13. How to create a bitcoin address? ▚ Relationships among Private Key, Public Key and Address. 13
  • 14. Step1. Generate Private Key ▚ The private key is, in essence, just a really big random number (256-bits) which can easily be generated offline with a sufficient source of randomness. var privateKey = '8F72F6B29E6E225A36B68DFE333C7CE5E55D83249D3D2CD6332671F A445C4DD3'; 14
  • 15. Step2. Generate Public Key ▚ Bitcoin uses the Elliptic Curve Digital Signature Algorithm (ECDSA) with the secp256k1 curve. secp256k1 ===> y2 = (x3 + 7) K (PublicKey) = k (PrivateKey) * G (base point) G = 04 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798 483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8 (NIST) 15 P 2P = (P+P) A B C = (A+B)
  • 16. Elliptic Curve ▚ K (PublicKey) = k (PrivateKey) * G (base point) 16
  • 17. Elliptic Curve ▚ K (PublicKey) = k (PrivateKey) * G (base point) 17 secp256k1 ===> y2 mod p = (x3 + 7) mod p, p = 2256 - 232 - 29 - 28 - 27 - 26 - 24 - 1 K (PublicKey) = k (PrivateKey) * G (base point) G = 04 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798 483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8 (NIST)
  • 18. Step2. Generate Public Key (cont.) Public Key x-axis: 06CCAE7536386DA2C5ADD428B099C7658814CA837F94FADE3 65D0EC6B1519385 Public Key y-axis: FF83EC5F2C0C8F016A32134589F7B9E97ACBFEFD2EF12A91FA6 22B38A1449EEB Public Key: 0406CCAE7536386DA2C5ADD428B099C7658814CA837F94FAD E365D0EC6B1519385FF83EC5F2C0C8F016A32134589F7B9E97A CBFEFD2EF12A91FA622B38A1449EEB 18
  • 19. Step3. Public Key to Public Key Hash ▚ Publick key hash = RIPEMD-160( SHA256( Public Key ) ), called HASH160. Public Key: 0406CCAE7536386DA2C5ADD428B099C7658814CA83 7F94FADE365D0EC6B1519385FF83EC5F2C0C8F016A3 2134589F7B9E97ACBFEFD2EF12A91FA622B38A1449EE B Hash160: 0b14f003d63ab31aef5fedde2b504699547dd1f6 19
  • 20. Step4. Public Key Hash to Bitcoin Address 20
  • 21. Step4. Public Key Hash to Bitcoin Address Hash160: 0b14f003d63ab31aef5fedde2b504699547dd1f6 SHA256(SHA256(Hash160)): 869ac57b83ccf75ca9da8895823562fffb611e3c29 7d9c2d4612aeeb32850078 New payload: 000b14f003d63ab31aef5fedde2b504699547dd1f 6869ac57b Base58checkEncode: 1QCXRuoxWo5Bya9NxHaVBArBQYhatHJrU7 21
  • 24. Wallets ▚ Bitcoin wallets contain keys, not coins. Each user has a wallet containing keys. Wallets are really keychains containing pairs of private/public keys. ▚ Users sign transactions with the keys, thereby proving they own the transaction outputs 24
  • 26. Nondeterministic (Random) Wallets ▚ Wallets were simply collections of randomly generated private keys. ▚ This type of wallet is nicknamed "Just a Bunch Of Keys" (JBOK). 26
  • 27. Deterministic (Seeded) Wallets ▚ Deterministic, or "seeded" wallets are wallets that contain private keys that are all derived from a common seed, through the use of a one-way hash function. ▚ The seed allows a user to easily backup and restore a wallet without needing any other information. 27
  • 28. Mnemonic Code Words ▚ Mnemonic codes are English word sequences that represent (encode) a random number used as a seed to derive a deterministic wallet. 28
  • 29. Hierarchical Deterministic Wallets ▚ Hierarchical deterministic wallets contain keys derived in a tree structure, such that a parent key can derive a sequence of children keys, each of which can derive a sequence of grandchildren keys, and so on, to an infinite depth. 29
  • 30. HD Wallet - Create Master Key ▚ HD wallets are created from a single root seed. ▚ Everything else in the HD wallet is deterministically derived from this root seed, which makes it possible to re-create the entire HD wallet from that seed. 30
  • 31. HD Wallet - Create Child Private Key ▚ HD wallets use a child key derivation (CKD) function to derive children keys from parent keys. ▚ The CKD are based on a one- way hash function that combines: � A parent private or public key. � A seed called a chain code. � An index number (32 bits). 31 point((parent_private + lefthand_hash) % G) == child_private ********************************************************************* point(child_private) == child_public parent_public + point(lefthand_hash) == child_public
  • 32. HD Wallet - Extended Key ▚ The two essential ingredients are the key and chain code, and combined these are called an extended key. ▚ An extended key consists of a private or public key and chain code, therefore it can create children, generating its own branch in the tree structure. Sharing an extended key gives access to the entire branch. 32 Chain Code Private Key / Public Key Extended Private / Public Key Base58 encode
  • 33. HD Wallet - Extended Key (cont.) ▚ Extended Key Format. � 4 bytes, version, mainnet public: 0x0488B21E, mainnet private: 0x0488ADE4, testnet public: 0x043587CF, testnet private: 0x04358394 � 1 byte, depth � 4 bytes, fingerprint, the first 4 bytes of HASH160( Public Key ) � 4 bytes, child number, n-th child � 32 bytes, chain code Base58 encode 33
  • 34. HD Wallet - Create Child Public Key ▚ An Extended public key can be used to create very secure public-key-only deployments where a server or application has a copy of an extended public key and no private keys whatsoever. ▚ Cannot spend any of the money sent to those addresses. 34
  • 35. HD Wallet - Hardened key derivation ▚ The extended public key contains the chain code, if a child private key leaked, it can be used with the chain code to derive all the other child private keys. 35
  • 36. HD Wallet - Hardened child key (cont.) ▚ Hardened derivation, which "breaks" the relationship between parent public key and child chain code. ▚ The hardened derivation function uses the parent private key to derive the child chain code, instead of the parent public key. 36
  • 39. Bitcoin Transaction Message Raw Data /* input */ 01 // number of inputs e34ac1e2baac09c366fce1c2245536bda8f7db0f6685862aecf53ebd69f9a89c // tx id 00000000 // input index 00 // unlocking script length ffffffff // sequence /* input end */ /* output */ 02 // number of outputs a025260000000000 // amount 19 // locking script length 76a914d90d36e98f62968d2bc9bbd68107564a156a9bcf88ac // locking script 5062250000000000 // amount 19 // locking script length 76a91407bdb518fa2e6089fd810235cf1100c9c13d1fd288ac // locking script /* output end */ 00000000 // 4 bytes locktime 39
  • 40. Transaction Script & Script Language ▚ Bitcoin's scripting language is called a stack-based language because it uses a data structure called a stack. ▚ The scripting language executes the script by processing each item from left to right. 40
  • 41. Transaction Script & Script Language (cont.) 41
  • 42. Script Construction (Lock + Unlock) ▚ Locking script is an encumbrance placed on an output, and it specifies the conditions that must be met to spend the output in the future. ▚ Unlocking script is a script that "solves" the conditions placed on an output by a locking script and allows the output to be spent. 42
  • 44. Standard Transactions ▚ pay-to-public-key-hash (P2PKH) ▚ pay-to-public-key (P2PK) ▚ multi-signature (limited to 15 keys) (MS) ▚ pay-to-script-hash (P2SH) ▚ data output (OP_RETURN) 44
  • 45. pay-to-public-key-hash (P2PKH) ▚ The vast majority of transactions processed on the bitcoin network are P2PKH transactions. These contain a locking script that encumbers the output with a public key hash, more commonly known as a bitcoin address. 45
  • 47. ▚ Locking script ▚ Unlocking script ▚ Combined pay-to-public-key (P2PK) <Public Key A> OP_CHECKSIG <Signature from Private Key A> <Signature from Private Key A><Public Key A> OP_CHECKSIG 47
  • 48. multi-signature (MS) ▚ An M-of-N scheme, where N is the total number of keys and M is the threshold of signatures required for validation. ▚ Locking script ▚ Unlocking script ▚ Combined (2-3 multi-signature) M <Public Key 1> <Public Key 2> ... <Public Key N> N OP_CHECKMULTISIG OP_0 <Signature B> <Signature C> OP_0 <Signature B> <Signature C> 2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG 48
  • 49. pay-to-script-hash (P2SH) ▚ Multi-sig would be about five times larger than a simple payment transaction, because this script contains very long public keys. ■ Extra-large transaction would increase fees ■ UTXO set in RAM in full node 49
  • 50. pay-to-script-hash (P2SH) (cont.) MultiSig 2 0 4 C 1 6 B 8 6 9 8 A 9 A B F 8 4 2 5 0 A 7 C 3 E A 7 E E - DEF9897D1C8C6ADF47F06CF73370D74DCCA01CDCA79DCC5C395D7EEC6984D83F1F50C900A 24DD47F569FD4193AF5DE762C58704A2192968D8655D6A935BEAF2CA23E3FB87A3495E7AF 308EDF08DAC3C1FCBFC2C75B4B0F4D0B1B70CD2423657738C0C2B1D5CE65C97D78D0E3422 4858008E8B49047E63248B75DB7379BE9CDA8CE5751D16485F431E46117B9D0C1837C9D57 37812F393DA7D4420D7E1A9162F0279CFC10F1E8E8F3020DECDBC3C0DD389D99779650421 D65CBD7149B255382ED7F78E946580657EE6FDA162A187543A9D85BAAA93A4AB3A8F044DA - DA618D087227440645ABE8A35DA8C5B73997AD343BE5C2AFD94A5043752580AFA1EC- ED3C68D446BCAB69AC0A7DF50D56231BE0AABF1FDEEC78A6A45E394BA29A1EDF518C022DD 618DA774D207D137AAB59E0B000EB7ED238F4D800 5 OP_CHECKMULTISIG P2SH 54c557e07dde5bb6cb791c7a540e0a4796f5e97 50
  • 52. data-output (OP_RETURN) ▚ OP_RETURN allows developers to add 40 bytes of nonpayment data to a transaction output. ▚ OP_RETURN outputs are recorded on the blockchain, but they are not stored in the UTXO set and therefore do not bloat the UTXO memory pool. ▚ Locking script ▚ No unlocking script OP_RETURN <data> 52
  • 54. CoinJoin ▚ Bitcoin anonymous weaknesses � Fiat money exchange � Transactions are open � The summary of the transaction will expose the owner of the other address ◇ CoinJoin � communication is not encrypted Example 54
  • 56. Nodes Types and Roles 56
  • 57. The extended bitcoin network 57
  • 58. Network Discovery ▚ When a new node boots up, it must discover other bitcoin nodes on the network in order to participate. 58
  • 59. Network Discovery (cont.) ▚ The new node will send an addr to its neighbors. The neighbors will, in turn, forward the addr message to their neighbors. ▚ The newly connected node can send getaddr to the neighbors, asking them to return a list of IP addresses of other peers. 59
  • 60. Exchange Inventory ▚ The longer blockchain peer will identify the first 500 blocks to share and transmit their hashes using an inv(inventory) message. ▚ The node missing these blocks will then retrieve them, by issuing a series of getdata messages requesting the full block data 60
  • 61. Simplified Payment Verification Node (SPV) ▚ SPV nodes download only the block headers and do not download the transactions included in each block. 61
  • 62. SPV + Bloom Filter ▚ A bloom filter is a probabilistic search filter, a way to describe a desired pattern without specifying it exactly. ▚ Bloom filters offer an efficient way to express a search pattern while protecting privacy. ▚ They are used by SPV nodes to ask their peers for transactions matching a specific pattern, without revealing exactly which addresses they are searching for. 62
  • 63. SPV + Bloom Filter (cont.) ▚ An example of a simplistic bloom filter, with a 16-bit field and three hash functions. 63
  • 64. SPV + Bloom Filter (cont.) 64
  • 65. SPV + Bloom Filter (cont.) 65
  • 66. SPV + Bloom Filter (cont.) 66
  • 67. SPV + Bloom Filter (cont.) 67
  • 68. ▚ Peers will send a merkleblock message that contains only block headers for blocks matching the filter and a merkle path for each matching transaction. ▚ Merkle path: HABCDEFGH + HIJ + HK + HK + HMNOP SPV + Bloom Filter (cont.) 68
  • 70. Bitcoin Economics and Currency Creation ▚ Each block, generated on average every 10 minutes, contains entirely new bitcoins. ▚ Every 210,000 blocks (4 years), the currency issuance rate is decreased by 50%. ▚ In approximately 2140, almost 21 million bitcoins, will be issued. 70
  • 71. Independent Verification of Transactions ▚ Every bitcoin node that receives a transaction will first verify the transaction, while invalid transactions are discarded at the first node that encounters them. ▚ Each node verifies every transaction against a long checklist of criteria: ■ The transaction's syntax and data structure must be correct. ■ Neither lists of inputs or outputs are empty. ■ …... 71
  • 72. Transaction Age, Fees, and Priority ▚ To construct the candidate block, bitcoin node selects transactions from the memory pool by applying a priority metric to each transaction and adding the highest priority transactions first. ▚ The first 50 KB of transaction space in a block are set aside for high-priority transactions even if they carry zero fees. Priority = Sum (Value of input * Input Age) / Transaction Size High Priority > 100,000,000 satoshis * 144 blocks / 250 bytes = 57,600,000 72
  • 73. Coinbase ▚ The first transaction added to the block is a special transaction, called coinbase transaction. This transaction is constructed by miner's node and is its reward for the mining effort. ▚ Coinbase do not have an unlocking script field. Instead, this field is replaced by coinbase data, which must be between 2 and 100 bytes. Total Fees = Sum(Inputs) - Sum(Outputs) Coinbase Example AntPool Coinbase 73
  • 74. Mining - Constructing the Block Header 74
  • 75. Mining - Target ▚ “Bits”first byte is a hexadecimal exponent, while the next part is the coefficient. ■ Ex, Block: 277316, Bits: 0x1903a30c 75 Target = coefficient * 2^(8 * (exponent - 3)) Example
  • 76. Mining - Difficulty Target and Retargeting ▚ To keep the block generation time at 10 minutes, the difficulty of mining must be adjusted to account for these changes. ▚ Every 2016 blocks, all nodes retarget the proof-of-work difficulty. ■ If the network is finding blocks faster than every 10 minutes, the difficulty increases. ■ If block discovery is slower than expected, the difficulty decreases. 76 New Difficulty = Old Difficulty * (Actual Time of Last 2016 Blocks / 20160 minutes) Example
  • 77. Blockchain Forks ▚ Because the blockchain is a decentralized data structure, different copies of it are not always consistent. ▚ Blocks might arrive at different nodes at different times, causing the nodes to have different perspectives of 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. 77
  • 83. Mining Pools ▚ A mining pool is the pooling of resources by miners, who share their processing power over a network. ▚ A "share" is awarded to members of the mining pool who present a valid proof of work that their miner solved. ▚ Reward types ■ Pay Per Last N Shares (PPLNS) ■ Pay Per Share (PPS) ■ Full Pay Per Share (FPPS) 83
  • 84. Consensus Attacks ▚ A miner or group of miners can achieve a significant share of the mining power, they can attack the consensus mechanism so as to disrupt the security and availability of the bitcoin network. � 51% Attack � Double spending A sent 100 BTC to B. A sent 1 BTC to B. 84

Editor's Notes

  • #3: 比特幣(Bitcoin)是一種用去中心化,基於區塊鏈作為支付技術的加密貨幣,由中本聰(化名),用共識主動性開源軟體發明創立,比特幣在全球各地皆可流通,任何人皆可參與,透過稱為挖礦的電腦運算來發行,協定數量上限為2100萬個,以避免通貨膨脹問題 使用比特幣是透過私鑰作為數位簽章,允許個人直接匯款給他人,用戶只要有證明其控制權的密鑰,用密鑰解鎖,就可以發送比特幣,不需經過第三方機構,從而避免了高手續費、繁瑣流程、以及受監管性的問題。
  • #4: 區塊鏈是由包含交易訊息的區塊從後向前有序鏈接起來的數據結構。 一個區塊就是若干交易數據的集合,它會被標記上時間戳和之前一個區塊的獨特標記。
  • #6: Merkle樹是一種雜湊二元樹,它是一種用作快速歸納和校驗大規模數據完整性的數據結構。 在比特幣網絡中,Merkle樹被用來歸納一個區塊中的所有交易,同時生成整個交易集合的數字指紋,且提供了一種校驗區塊是否存在某交易的高效途徑。生成一棵完整的Merkle樹需要遞歸地對哈希節點對進行哈希,並將新生成的哈希節點插入到Merkle樹中,直到只剩一個哈希節點,該節點就是Merkle樹的根。在比特幣的Merkle樹中兩次使用到了SHA256算法,因此其加密哈希算法也被稱為double-SHA256。
  • #8: Merkle Tree 的一個好處是可以單獨拿出一個分支來(作為一個小樹)對部分數據進行校驗,圖4是一個完整的Merkle Tree,如果我們要驗證交易K是否存在於這棵Merkle Tree中,最簡單的方式就是只取H_ABCDEFGH、H_IJ、H_L跟H_MNOP這幾組Hash值來進行驗算,最後算出的Root是否跟原本的Root一樣,若Root的Hash值相同,就可以證明說交易K存在該樹中。
  • #9: 由封面圖可以看出來,比特幣網路的節點可以在世界各地,不管你是用手機還是電腦,只要有自己跑一個比特幣客戶端,你就是這個大型分散式系統的一員。 當一個使用者要產生一筆新的交易,他需要指定從自己的哪一個地址 (address) 送錢去哪一個地址?如圖上半部可以看到使用者會擁有自己的錢包 (wallet),錢包是一個軟體裝有使用者的地址和相對應的密鑰 (private key),當然一個錢包也可以存放多組地址。 當交易創建之後就會發送到全網路上,圖的下半部可以看到有個礦工 (miner) 收集了一些尚未確認的交易,可能也包含了我們剛剛發送到網路的這筆交易,經過大量計算之後,也就是我們上一章所簡單提到的工作量證明 (PoW),礦工組成了一個新的區塊,然後發佈到比特幣網路上給其他節點驗證。 最後圖的左邊可以看到如果網路達成了共識 (consensus),新的區塊就接上區塊鏈了,數學競賽重新開始。
  • #12: 所謂的比特幣交易就相當於簽支票,而所謂的錢包其實就是一個蒐集管理支票的工具 當我要付比特幣給別人的時候,錢包就會開始找別人付給我的支票(input)。 通常會從小額的支票開始找,湊到足額的支票後,就會簽寄給別人的支票(output) 但是通常不會剛好input就會等於output,這個時候的解法就是找零。 像是假如我的錢包蒐集到一千元的支票給別人,但其實只是要付給他900元, 那當然就是再簽一張一百元的支票給自己囉 以上就是比特幣找零的基本概念 另外補充一下:找零的地址為了隱私性,通常是會再產生一個新的自己錢包的地址 如此就可以讓別人難以用單一地址就可以追蹤到該使用者的所有交易紀錄。
  • #14: 比特幣系統中,簽名(sign)和地址(address)都是由key所產生,又可細分為私鑰以及公鑰,私鑰不會存在鏈上,而是由錢包包管,有私鑰就可以產生簽名,有簽名就可以花費比特幣,所以要保管好自己的私鑰。 簡單來說三者的脈絡是,從隨機數生成私鑰 ---> 私鑰經由橢圓曲線加密演算法算出公鑰 ---> 公鑰再透過Hash function算出比特幣地址
  • #15: http://www.xorbin.com/tools/sha256-hash-calculator
  • #16: G點是美國國家標準技術研究所所決定的 K=kG [其中K,G為Ep(a,b)上的點,k為小於n(n是點G的階)的整數] 不難發現,給定k和G,根據加法法則,計算K很容易;但給定K和G,求k就相對困難了。 這就是橢圓曲線加密算法採用的難題。我們把點G稱為基點(base point),k(k<n,n為基點G的階)稱為私有密鑰(privte key),K稱為公開密鑰(public key)。 現在我們描述一個利用橢圓曲線進行加密通信的過程: 1、用戶A選定一條橢圓曲線Ep(a,b),並取橢圓曲線上一點,作為基點G。 2、用戶A選擇一個私有密鑰k,並生成公開密鑰K=kG。 3、用戶A將Ep(a,b)和點K,G傳給用戶B。 4、用戶B接到信息後,將待傳輸的明文編碼到Ep(a,b)上一點M(編碼方法很多,這裡不作討論),並產生一個隨機整數r(r<n)。 5、用戶B計算點C1=M+rK;C2=rG。 6、用戶B將C1、C2傳給用戶A。 7、用戶A接到信息後,計算C1-kC2,結果就是點M。因為 C1-kC2=M+rK-k(rG)=M+rK-r(kG)=M 再對點M進行解碼就可以得到明文。 在這個加密通信中,如果有一個偷窺者H ,他只能看到Ep(a,b)、K、G、C1、C2 而通過K、G求k或通過C2、G求r都是相對困難的。因此,H無法得到A、B間傳送的明文信息。
  • #17: 以右圖8G為例,假設Private key是8,我們只要先算出2G(G+G),就可以求4G(2G+2G),再做一次4G切線就可以得到8G 而不需要一次一次慢慢加 但是反推回來就不同了,假設我們給了123456789G = private key * G,但是我們並不知道pk是多少,因此只能一個一個計算,pk是256bits的超大數,基本上根本不可能算出來
  • #18: 因為連續曲線不適合用來加解密,因此會用mod將質域限定在特定範圍,右圖是限縮在97的圖,看似雜亂其實還是保有橢圓曲線的特性 我們自己限制在一個固定範圍的數字像在RSA裡的一樣。而不是允許曲線上點的任何值,我們把自己限制在一個固定範圍內的所有數字。 曲線圖:https://www.desmos.com/calculator/ialhd71we3 mod圖:http://graui.de/code/elliptic2/ 參考資料: https://combo.tian.yam.com/posts/126841255 http://8btc.com/thread-1240-1-1.html
  • #19: 引入壓縮格式公鑰是為了減少比特幣交易的字節數,一個公鑰是一個橢圓曲線上的點(x, y)。而橢圓曲線實際是一個數學方程,曲線上的點實際是該方程的一個解。因此,如果我們知道了公鑰的x坐標,就可以通過解方程y**2 mod p = (x**3 + 7) mod p得到y坐標。這種方案可以讓我們只存儲公鑰的x坐標,略去y坐標,從而將公鑰的大小和存儲空間減少了256比特。每個交易所需要的字節數減少了近一半,隨著時間推移,就大大節省了很多數據傳輸和存儲。 未壓縮格式公鑰使用04作為前綴,而壓縮格式公鑰是以02或03作為前綴。需要這兩種不同前綴的原因是:因為橢圓曲線加密的公式的左邊是y 2,也就是說y的解是來自於一個平方根,可能是正值也可能是負值。
  • #20: SHA-256: 任何東西輸入都將其編碼輸出32bytes摘要數值! RIPEMD-160: 任何東西輸入都將其編碼輸出20bytes摘要數值!
  • #21: 轉成人類比較不會混淆的字串,拿掉0 (零), O (大寫字母O), I (大寫的字母i),l (小寫的字母L) ,和幾個影響雙擊選擇的符號,如/, +
  • #22: 轉成人類比較不會混淆的字串,拿掉0 (零), O (大寫字母O), I (大寫的字母i),l (小寫的字母L) ,和幾個影響雙擊選擇的符號,如/, +
  • #25: 比特幣錢包只包含私鑰而不是比特幣。每一個用戶有一個包含多個私鑰的錢包。錢包中包含成對的私鑰和公鑰。用戶用這些私鑰來簽名交易,從而證明它們擁有交易的輸出(也就是其中的比特幣)。比特幣是以交易輸出的形式來儲存在區塊鏈中(通常記為vout或txout)。
  • #26: 錢包導入格式(WIF) 使為了私鑰的複製不容易出錯,可以使用錢包導入格式WIF。WIF在私鑰上使用base58Check編碼,大大降低了複製錯誤的機率:這和標準比特幣地址很類似。 一個私鑰。 在mainnet 地址之前添加一個0x80的字節或testnet 地址添加一個0xef字節。 如果與它壓縮的公鑰一起使用(在後面的小節中描述),則會添加一個0×01字節。如果未與壓縮的公鑰一起使用,則不附加任何內容。 在擴展密鑰上執行SHA-256哈希。 對SHA-256哈希的結果執行SHA-256哈希。 取第二個SHA-256哈希的前四個字節;這是校驗和。 從第2點的擴展密鑰的末尾添加第5點的四個校驗和字節。 使用Base58Check編碼將結果從字節字符串轉換為Base58字符串。
  • #27: 在最早的一批比特幣客戶端中,錢包只是隨機生成的私鑰集合。這種類型的錢包被稱作零型非確定錢包。 舉個例子,比特幣核心客戶端預先生成100個隨機私鑰,從最開始就生成足夠多的私鑰並且每把鑰匙只使用一次。這種類型的錢包有一個暱稱“Just a Bunch Of Keys(一堆私鑰)”簡稱JBOK。這種錢包現在正在被確定性錢包替換,因為它們難以管理、備份以及導入。 隨機鑰匙的缺點就是如果你生成很多,你必須保存它們所有的副本。這就意味著這個錢包必須被經常性地備份。每一把鑰匙都必須備份,否則一旦錢包不可訪問時,錢包所控制的資金就付之東流。 這種情況直接與避免地址重複使用的原則相衝突——每個比特幣地址只能用一次交易。地址通過關聯多重交易和對方的地址重複使用會減少隱私。0型非確定性錢包並不是錢包的好選擇,尤其是當你不想重複使用地址而創造過多的私鑰並且要保存它們。雖然比特幣核心客戶包含0型錢包,但比特幣的核心開發者並不想鼓勵大家使用。
  • #28: 有個確定性產出錢包的方法,通常都是透過一個Seed(只是個字串)來實作。 然後Seed讓使用者可以很輕鬆的備份跟還原,而不需要其他的輔助資訊。
  • #29: 助記碼詞彙是英文單詞序列代表(編碼)用作種子對應所確定性錢包的隨機數。單詞的序列足以重新創建種子,並且從種子那裡重新創造錢包以及所有私鑰。在首次創建錢包時,帶有助記碼的,運行確定性錢包的錢包的應用程序將會向使用者展示一個12至24個詞的順序。單詞的順序就是錢包的備份。它也可以被用來恢復以及重新創造應用程序相同或者兼容的錢包的鑰匙。助記碼代碼可以讓使用者復制錢包更容易一些,因為它們相比較隨機數字順序來說,可以很容易地被讀出來並且正確抄寫。 測試網站 https://iancoleman.github.io/bip39/ 可用的字: https://github.com/bitcoin/bips/tree/master/bip-0039
  • #30: 確定性錢包被開發成更容易從單個“種子”中生成許多關鍵的鑰匙。最高級的來自確定性錢包的形是通過BIP0032標準生成的the hierarchical deterministic wallet or HD wallet defined。 分層確定性錢包包含從數結構所生成的鑰匙。這種母鑰匙可以生成子鑰匙的序列。這些子鑰匙又可以衍生出孫鑰匙,以此無窮類推。
  • #31: HD錢包從單個root seed中創建,為128到256位的隨機數。HD錢包的所有的確定性都衍生自這個根種子。 任何兼容HD錢包的根種子也可重新創造整個HD錢包。所以簡單的轉移HD錢包的根種子就讓HD錢包中所包含的成千上百萬的密鑰被複製,儲存導出以及導入。
  • #32: 分層確定性錢包使用CKD(child key derivation)方程去從母密鑰衍生出子密鑰。 子密鑰衍生方程是基於單項哈希方程。這個方程結合了: •一個母私鑰或者公共鑰匙(ECDSA未壓縮鍵) •一個叫做鏈碼(256 bits)的種子 •一個索引號(32 bits) 鏈碼是用來給這個過程引入看似的隨機數據的,使得索引不能充分衍生其他的子密鑰。因此,有了子密鑰並不能讓它發現自己的相似子密鑰,除非你已經有了鏈碼。最初的鏈碼種子(在密碼樹的根部)是用隨機數據構成的,隨後鏈碼從各自的母鏈碼中衍生出來。 這三個項目相結合併散列可以生成子密鑰,如下。 母公共鑰匙——鏈碼——以及索引號合併在一起並且用HMAC-SHA512方程散列之後可以產生5​​12位的散列。所得的散列可被拆分為兩部分。散列右半部分的256位產出可以給子鏈當鏈碼。左半部分256位散列以及索引碼被加載在母私鑰上來衍生子私鑰。在圖4-11中,我們看到這種這個說明——索引集被設為0去生產母密鑰的第0個子密鑰(第一個通過索引)。
  • #33: 正如我們之前看到的,密鑰衍生方程可以被用來創造鑰匙樹上任何層級的子密鑰。這只需要三個輸入量:一個密鑰,一個鏈碼以及想要的子密鑰的索引。 密鑰以及鏈碼這兩個重要的部分被結合之後,就叫做extended key。術語“extended key”也被認為是“可擴展的密鑰”是因為這種密鑰可以用來衍生子密鑰。 擴展密鑰可以簡單地被儲存並且表示為簡單的將256位密鑰與256位鏈碼所並聯的512位序列。有兩種擴展密鑰。擴展的私鑰是私鑰以及鏈碼的結合。它可被用來衍生子私鑰(子私鑰可以衍生子公共密鑰)公共鑰匙以及鏈碼組成擴展公共鑰匙。這個鑰匙可以用來擴展子公共鑰匙,見“ 4.1.6生成公鑰 ”。 想像一個擴展密鑰作為HD錢包中鑰匙樹結構的一個分支的根。你可以衍生出這個分支的剩下所有部分。擴展私人鑰匙可以創建一個完整的分支而擴展公共鑰匙只能夠創造一個公共鑰匙的分支。
  • #34: 4 bytes version,這邊其實只有四種可能,0x0488B21E 代表 mainnet public,0x0488ADE4 代表 mainnet private,0x043587CF 代表 testnet public,0x04358394 代表 testnet private 1 byte depth,就是當前這個 node 在樹的深度 4 bytes fingerprint,fingerprint 是 identifier 的前 32 bits,而 identifier 是 把 public key 做一次 hash160 的結果,可以用來代表這個 node 4 bytes child number,即他是第幾個 child 32 bytes chain code,為我們剛剛提到的兩個重要參數的其中之一 33 bytes private key 或 public key,因為 private key 長度只有 32 bytes,所以前綴要補 0x00 以上總共 78 bytes 串接在一起,然後再做 base58 encoding。
  • #35: 從前面的Extended Public Key,我們可以透過一把Extended Public Key來產出底下所有的 Child Public Key,達成 Public-key-only的環境 也就是所謂的冷錢包,不用擔心Private Key被偷走 正如之前提到的,分層確定性錢包的一個很有用的特點就是可以不通過私鑰而直接從公共母鑰匙派生出公共子鑰匙的能力。這就給了我們兩種去衍生子公共鑰匙的方法:或者通過子私鑰,再或者就是直接通過母公共鑰匙。 因此,擴展的公共鑰匙可以再HD錢包結構的分支中,被用來衍生所有的公鑰(且只有公共鑰匙)。 這種快捷方式可以用來創造非常保密的public-key-only配置。在配置中,服務器或者應用程序不管有沒有私鑰,都可以有擴展公共鑰匙的副本。這種配置可以創造出無限數量的公共鑰匙以及比特幣地址。但是不可以花送到這個地址裡的任何比特幣。與此同時,在另一種更保險的服務器上,擴展私鑰可以衍生出所有的對應的可簽署交易以及花錢的私鑰。
  • #36: 硬化子密鑰的衍生 從擴展公共鑰匙衍生一個分支公共鑰匙的能力是很重要的,但牽扯一些風險。 訪問擴展公共鑰匙並不能得到訪問子私人密鑰的途徑。但是,因為擴展公共鑰匙包含有鏈碼,如果子私鑰被知道或者被洩漏的話,鏈碼就可以被用來衍生所有的其他子私鑰。 一個簡單地洩露的私鑰以及一個母鏈碼,可以暴露所有的子密鑰。更糟糕的是,子私鑰與母鏈碼可以用來推斷母私鑰。
  • #37: 為了應對這種風險,HD 錢包使用一種叫做_hardened derivation_ 的替代衍生方程。這就“打破”了母公共鑰匙以及子鏈碼之間的關係。這個硬化衍生方程使用了母私人秘鑰去推到子鏈碼,而不是母公共鑰匙。這就在母/子順序中創造了一道“防火牆”——有鏈碼但並不能夠用來推算子鏈碼或者姊妹私人秘鑰。強化的衍生方程看起來幾乎與一般的衍生的子私人秘鑰相同,不同的是是母私人秘鑰被用來輸入散列方程中而不是母公共鑰匙。 當強化私鑰衍生方程被使用時,得到的子私鑰以及鏈碼與使用一般衍生方程所得到的結果完全不同的。得到的密鑰“分支”可以被用來生產不易被攻擊的擴展公共鑰匙,因為它所含的鏈碼不能被用來開發或者暴露任何私鑰。強化的衍生也因此被用來在上一層級,使用擴展公共鑰匙的的密鑰樹中創造“間隙”。 簡單地來說,如果你想要利用擴展公共鑰匙的便捷來衍生公共鑰匙的分支而不將你自己暴露在洩露擴展鏈碼的風險下,你應該從強化母私鑰,而不是一般的母私鑰,來衍生公共鑰匙。最好的方式是,為了避免了推到出主鑰匙,主鑰匙所衍生的第一層級的子鑰匙最好使用強化衍生。 索引號小於2**31就意味著子密鑰是常規的,而大於或者等於2**31的子密鑰就是強化型的。 為了讓索引號碼更容易被閱讀和展示,強化子密碼的索引號碼是從0開始展示的,但是右上角有一個小撇號。第一個常規子密鑰因此被表述為0,但是第一個強化子密鑰(索引號為0x80000000)就被表示為0'。第二個強化密鑰依序有了索引號0x80000001,且被顯示為1',以此類推。當你看到HD錢包索引號i',這就意味著2**31 +i。
  • #39: 交易的鎖定時間 鎖定時間定義了能被加到區塊鏈裡的最早的交易時間。 在大多數交易裡,它被設置成0,用來表示立即執行。 如果鎖定時間不是0並且小於5億,就被視為區塊高度,意指在這個指定的區塊高度之前,該交易不會被打包到區塊鏈裡 如果鎖定時間大於5億,則它被當作是一個Unix紀元時間戳(從1970年1月1日以來的秒數),並且在這個指定時點之前,該交易不會被打包到區塊鏈裡 鎖定時間的使用相當於將一張紙質支票的生效時間予以後延。
  • #41: 腳本附件 http://chimera.labs.oreilly.com/books/1234000001802/apa.html 腳本語言 比特幣腳本語言被稱為基於堆疊的語言,因為它使用的數據結構被稱為堆疊。堆疊是一個非常簡單的數據結構,它可以被理解成為一堆卡片。堆疊允許兩類操作:push和pop。push是在堆疊頂部增加一個項目,pop則是從堆疊頂部移除一個項目。 腳本語言通過從左至右地處理每個項目的方式執行腳本。數字(常數)被推送至堆疊,操作符向堆疊推送(或移除)一個或多個參數,對它們進行處理,甚至可能會向堆疊推送一個結果。例如,OP_ADD將從堆疊移除兩個項目,將二者相加,然後再將二者相加之和推送到堆疊。
  • #43: 比特幣的交易驗證引擎依賴於兩類腳本來驗證比特幣交易:一個鎖定腳本和一個解鎖腳本。 鎖定腳本是一個放在一個輸出值上的“障礙”,同時它明確了今後花費這筆輸出的條件。由於鎖定腳本往往含有一個公鑰(即比特幣地址),在歷史上它曾被稱作一個腳本公鑰代碼。由於認識到這種腳本技術存在著更為寬泛的可能性,在本書中,我們將它稱為一個“鎖定腳本”。在大多數比特幣應用源代碼中,腳本公鑰代碼便是我們所說的鎖定腳本。 解鎖腳本是一個“解決”或滿足被鎖定腳本在一個輸出上設定的花費條件的腳本,同時它將允許輸出被消費。解鎖腳本是每一筆比特幣交易輸出的一部分,而且往往含有一個被用戶的比特幣錢包(通過用戶的私鑰)生成的數字簽名。由於解鎖腳本常常包含一個數字簽名,因此它曾被稱作ScriptSig。在大多數比特幣應用的源代碼中,ScriptSig便是我們所說的解鎖腳本。考慮到更寬泛的鎖定腳本要求,在本書中,我們將它稱為“解鎖腳本”。但並非所有解鎖腳本都一定會包含簽名。 每一個比特幣客戶端會通過同時執行鎖定和解鎖腳本來驗證一筆交易。對於比特幣交易中的每一個輸入,驗證軟件會先檢索輸入所指向的UTXO。這個UTXO包含一個定義了花費條件的鎖定腳本。接下來,驗證軟件會讀取試圖花費這個UTXO的輸入中所包含的解鎖腳本,並執行這兩個腳本。
  • #44: 其實我們可以這樣看待比特幣的交易:『交易的發起者懸賞若干比特幣,在網絡上貼出了一到數學題,誰解出了這道數學題,懸賞就歸誰了』。 順著這個思路,Alice對Bob的轉帳可以理解為『Alice把一道只有Bob才能解開的數學題發到網絡上,Bob解出題並拿走了懸賞』。那麼,每個交易數據中都會出現的『腳本』就是題和解,『腳本語言』就是用來描述題和解的工具。
  • #46: 絕大多數的比特幣 transaction 都是採用這個 script,就像是 Alice 的 address 送錢給 Bob 的 address 這種 transaction,前面有提到secretKey → publicKey → publicKeyHash ←→ bitcoinAddress,所以P2PKH就是直接送錢到某個比特幣地址的意思
  • #47: 絕大多數的比特幣 transaction 都是採用這個 script,就像是 Alice 的 address 送錢給 Bob 的 address 這種 transaction,前面有提到secretKey → publicKey → publicKeyHash ←→ bitcoinAddress,所以P2PKH就是直接送錢到某個比特幣地址的意思
  • #48: 經由交易驗證軟件確認的組合腳本為: <Signature from Private Key A> <Public Key A> OP_CHECKSIG 該腳本只是CHECKSIG操作符的簡單調用,該操作主要是為了驗證簽名是否正確,如果正確,則返回為真(Ture)。 直接把公鑰放在 locking script 了,所以 unlocking script 不用再給公鑰了,給 Signature 來驗證就好了。
  • #49: 多重簽名腳本設置了這樣一個條件,假如記錄在腳本中的公鑰個數為N,則至少需提供其中的M個公鑰才可以解鎖,被稱為MN組合。而 M 在比特幣裡目前有最大上限是 15 個公鑰 之所以要加上前綴OP_0,是因為最早的CHECKMULTISIG在處理含有多個項目的過程中有個小漏洞,CHECKMULTISIG會自動忽略這個前綴,它只是佔位符而已。另外這邊的 Signature 不一定要給 B 和 C,也可以是 A B 或 A C 或全都給,不過順序是重要的例如不能是 C B
  • #50: 從上面的多簽來延伸,如果現在是 2–5 的架構 locking script 會有多長,如果是 3–7 呢?locking script 太長會造成什麼負擔?我們知道 locking script 是用來保護 UTXO 不被盜用的,locking script 的增長會導致 UTXO 的肥大,而我們剛說過 UTXO 為了方便會存放在昂貴的記憶體裡面(放在UTXO Pool中),因此如果 UTXO 越來越大比特幣節點對記憶體的消耗也會越來越兇猛,因此 P2SH 就登場了。
  • #51: 從Raw Data更可以看出差異
  • #52: 整個腳本都可由僅為20個字節的Hash code所取代,首先先將Redeem Script用SH256哈希算法,隨後對其運用RIPEMD160算法,可發現計算hash redeem script的算法跟計算bitcoin address如初一撤,因此可以再進一步計算Base58check,從下表可以知道,P2SH Address跟Bitcoin Address最大差異就是編碼前的前綴不同,P2SH前綴是0x05,編碼出來的地址開頭為3,因此只要把該3開頭的地址給付款人即可,原本的多重簽證,付款人需要知道Redeem Script中的所有內容,有了P2SH Address後,唯一要做的就是把錢送到該地址。由於Base58check是可逆的,所以output中的hash redeem script只要從3xxxxxx…. address逆推就可以得到Hash redeem script。
  • #54: 不能花費的 output,它的用處是拿來紀錄的,因為區塊鏈有公開透明不可被竄改的好處,因此這種形態的 output 就產生了,純粹的資料紀錄不用於轉錢。
  • #55: 混幣原理(CoinJoin):許多人參與,一個交易中包括大量輸入和輸出,很難在輸入和輸出中找出每個人的對應對,輸入與輸出之間的聯繫被事實上割裂。多次混幣、每次少量幣,效果更好。 一、 比特幣的匿名性   比特幣網絡通過以下三個措施進行隱私保護或匿名:   1、地址的生成無需實名認證;   2、通過地址不能對應出真實身份;   3、同一擁有者的不同賬號之間沒有直接關聯,無法得知特定用戶的全部比特幣數量。   二、 比特幣的匿名性弱點   1、與法幣的兌換環節。比特幣交易所的實名認證,是有效的反匿名措施,其他要求實名的比特幣服務商也如此。有人說可以用假身份證件來逃過,在目前這是可行的,但以後交易所的身份驗證一定會越來越嚴格。   2、交易公開。只需知道一個地址就可以找到關聯人的一系列地址。另外,在論壇、微博、TWITTER、REDDIT、BBS等留下的許多信息,通過大數據分析可以匯總起來,會發現一系列的線索,除非你謹慎得像中本聰。   3、交易的匯總輸入會暴露擁有人的其他地址。一旦你發送錢包中的大部分幣給某人或某交易所,基本上會把你的全部地址都暴露無遺。因為交易會匯總大部分地址中的幣打出去。   4、™比特幣的通訊協議未加密,向外打款時,協議分析軟件可以找出IP地址與比特幣地址的對應關係,如果在全國佈署了這種監控系統,那定位到你的單位或小區就不是問題。(當然可以用TOR、VPN之類逃避)
  • #59: 新節點是如何發現網絡中的對等節點的呢?雖然比特幣網絡中沒有特殊節點,但是客戶端會維持一個列表,那裡列出了那些長期穩定運行的節點。這樣的節點被稱為“種子節點(seed nodes)”。新節點並不一定需要與種子節點建立連接,但連接到種子節點的好處是可以通過種子節點來快速發現網絡中的其他節點。在比特幣核心客戶端中,是否使用種子節點是通過“-dnsseed”控制的。默認情況下,該選項設為1,即意味著使用種子節點。另一種方式是,起始時將至少一個比特幣節點的IP地址提供給正在啟動的節點(該節點不包含任何比特幣網絡的組成信息)。在這之後,啟動節點可以通過後續指令建立新的連接。用戶可以使用命令行參數“-seednode”把啟動節點“引薦”並連接到一個節點,並將該節點用作DNS種子。在初始種子節點被用於形成“引薦”信息之後,客戶端會斷開與它的連接、並與新發現的對等節點進行通信。
  • #60: 當建立一個或多個連接後,新節點將一條包含自身IP地址的addr消息發送給其相鄰節點。相鄰節點再將此條addr消息依次轉發給它們各自的相鄰節點,從而保證新節點信息被多個節點所接收、保證連接更穩定。另外,新接入的節點可以向它的相鄰節點發送getaddr消息,要求它們返回其已知對等節點的IP地址列表。通過這種方式,節點可以找到需連接到的對等節點,並向網絡發布它的消息以便其他節點查找。
  • #61: 在建立連線之後,這個新的節點只會有一個區塊,叫做創世區塊 (genesis block),顧名思義就是第一個區塊,那他該如何同步成跟大家一樣的進度?在相連的節點之間,會互相交換著 getblocks 這個訊息,而這個訊息裡面包涵我這個節點當前最新的區塊 hash (BestHeight),以這個新節點來說他發出去的 getblocks 就會是創世區塊的 hash,因為他目前就只有一個區塊。 而相鄰的節點間,會有一個節點發現他所獲得的 getblocks 資訊並不等於自己的資訊,反而是一個已經出現過的區塊 hash,因此他就可以推定自己所擁有的區塊鏈是比較長的,然而他並不會就這樣把別人所沒有的區塊 hash 都通通傳回去讓他更新,反而是回傳一份清單 (inventory),告訴他他缺少了哪些區塊,而原節點就可以根據這份清單,重複的呼叫 getdata 來跟他要區塊資料。
  • #62: 在使用簡單支付驗證時,只要判斷出一個交易在主鏈上的某個區塊裡出現過,則可以證明該交易之前已被驗證過。 按照中本聰的原文,這裡有個細節需要注意,SPV指的是“支付驗證“,而不是“交易驗證”。這兩種驗證有很大區別。 “交易驗證”非常複雜,涉及到驗證是否有足夠餘額可供支出、是否存在雙花、腳本能否通過等等,通常由運行完全節點的礦工來完成。 “支付驗證”則比較簡單,只判斷用於“支付”的那筆交易是否已經被驗證過,並得到了多少的算力保護(多少確認數)。 區塊頭部只有80位元組。按照每小時6個的出塊速度,每年產出52560個區塊。當只保存區塊頭部時,每年新增的存儲需求約為4MB,100年後累計的存儲需求僅為400MB,即使用戶使用的是最低端的設備,正常情況下也完全能夠負載。
  • #63: Bloom過濾器是一個允許用戶描述特定的關鍵詞組合而不必精確表述的基於概率的過濾方法。它能讓用戶在有效搜索關鍵詞的同時保護他們的隱私。在SPV節點裡,這一方法被用來向對等節點發送交易信息查詢請求,同時交易地址不會被暴露。 用我們之前的例子,一位手中沒有地圖的遊客需要詢問去特定地方的路線。如果他向陌生人詢問“教堂街23號在哪裡”,不經意之間,他就暴露了自己的目的地。Bloom過濾器則會這樣問,附近有帶'堂'字的街道嗎?”這樣的問法包含了比之前略少的關鍵詞。這位遊客可以自己選擇包含信息的多少,比如“以'堂街'結尾”或者“'教'字開頭的街道”。如果他問得越少,得到了更多可能的地址,隱私得到了保護,但這些地址裡面不乏無關的結果;如果他問得非常具體,他在得到較準確的結果的同時也暴露了自己的隱私。
  • #64: Bloom過濾器的實現是由一個可變長度(N)的二進制陣列和數量可變(M)的一組雜湊函數組成。。這些雜湊函數的輸出值始終在1和N之間,該數值與二進制陣列相對應。並且該函數為確定性函數,也就是說任何一個使用相同Bloom過濾器的節點通過該函數都能對特定輸入得到同一個的結果。Bloom過濾器的準確性和私密性能通過改變長度(N)和雜湊函數的數量(M)來調節。
  • #65: Bloom過濾器陣列裡的每一個數的初始值為零。關鍵詞被加到Bloom過濾器中之前,會依次通過每一個雜湊函數運算一次。 該輸入經第一個雜湊函數運算後得到了一個在1和N之間的數,它在該陣列(編號依次為1至N)中所對應的位被置為1,從而把雜湊函數的輸出記錄下來。 接著再進行下一個雜湊函數的運算,把另外一位置為1;以此類推。當全部M個雜湊函數都運算過之後,一共有M個位的值從0變成了1,這個關鍵詞也被“記錄”在了Bloom過濾器裡。
  • #66: 增加第二個關鍵是就是簡單地重複之前的步驟。關鍵詞依次通過各雜湊函數運算之後,相應的位變為1,Bloom過濾器則記錄下該關鍵詞。 需要注意的是,當Bloom過濾器裡的關鍵詞增加時,它對應的某個雜湊函數的輸出值的位可能已經是1了,這種情況下,該位不會再次改變。 也就是說,隨著更多的關鍵詞指向了重複的位,Bloom過濾器隨著位1的增加而飽和,準確性也因此降低了。該過濾器之所以是基於概率的數據結構,就是因為關鍵詞的增加會導致準確性的降低。準確性取決於關鍵字的數量以及數組大小(N)和哈希函數的多少(M)。 更大的陣列和更多的雜湊函數會記錄更多的關鍵詞以提高準確性。而小的陣列及有限的雜湊函數只能記錄有限的關鍵詞從而降低準確性。
  • #67: 為測試某一關鍵詞是否被記錄在某個Bloom過濾器中,我們將該關鍵詞逐一代入各雜湊函數中運算,並將所得的結果與原陣列進行對比。 如果所有的結果對應的位都變為了1,則表示這個關鍵詞有可能已被該過濾器記錄。 之所以這一結論並不確定,是因為這些字節1也有可能是其他關鍵詞運算的重疊結果。簡單來說,Bloom過濾器正匹配代表著“可能是”。
  • #68: 如果我們代入關鍵詞計算後的結果某位為0,說明該關鍵詞並沒有被記錄在過濾器裡。 負匹配的結果不是可能,而是一定。也就是說,負匹配代表著“一定不是”。 假設我們現在只想要 A 和 B 兩個結果,在這套 bloom filter 之下,我們除了一定會找 A 和 B 之外,還會找到一些不相干的例如 C D E,如此魚目混珠可以讓別人不知道我們到底是要找 A B C D E 當中的哪些。如果我們把陣列變長,hash function 變多,每個特徵出來的結果就越來越獨特,不相干的可能結果也會越來越少,但也就有更高的機會被別人知道你要找的是 A 和 B 了。 回去 SPV node 的情況,我們現在的目的是希望 SPV node 在跟鄰居要 transaction 時不要暴露自己的目標 address,有了 bloom filter,他就不需要擔心他跟鄰居要的 transaction 會透露出節點裡面錢包所含的 address 了,因為 bloom filter 會讓我們多得到一些不相干的 transaction。
  • #69: 一個SPV節點欲知它錢包中某個比特幣地址即將到達的支付,該節點會在節點間的通信鏈接上建立起bloom過濾器,限制只接受含有目標比特幣地址的交易。 當節點探測到某交易符合bloom過濾器,它將以Merkleblock消息的形式發送該區塊。Merkleblock消息包含區塊頭和一條連接目標交易與Merkle根的Merkle路徑。 SPV節點能夠使用該路徑找到與該交易相關的區塊,進而驗證對應區塊中該交易的有無。SPV節點同時也使用區塊頭去關聯區塊和區塊鏈中的區域區塊。這兩種關聯,交易與區塊、區塊和區塊鏈,證明交易存在於區塊鏈。 Bloom過濾器被用來過濾SPV節點從對等節點裡收到的交易信息。SPV會建立一個只能和SPV節點錢包裡的地址匹配的過濾器。隨後,SPV節點會向對等節點發送一條包含需在該連接中使用的過濾器的filterload消息。當過濾器建好之後,對等節點將每個交易的輸出值代入過濾器中驗證。那些匹配的交易會被傳送回SPV節點。 為回應來自SPV節點的getdata信息,對等節點會發出一條只含有和過濾器匹配的區塊的區塊頭信息,以及與之相匹配的交易的merkle樹。這一對等節點還會發出一條相匹配的交易的tx消息,也就是merkle path。 SPV節點再驗證該path的雜湊值是不是跟某個Block MerkleRoot相匹配,若匹配,就可以知道該Block目前已經有幾個確認。
  • #71: 通過創造出新區塊,比特幣以一個確定的但不斷減慢的速率被鑄造出來。大約每十分鐘產生一個新區塊,每一個新區塊都伴隨著一定數量從無到有的全新比特幣。每開採210,000個塊,大約耗時4年,貨幣發行速率降低50%。在比特幣運行的第一個四年中,每個區塊創造出50個新比特幣。 2012年11月,比特幣的新發行速度降低到每區塊25個比特幣,並且預計會在2016年的某個時刻,在第420,000個區塊被“挖掘”出來之後降低到12.5比特幣/區塊。在第13,230,000個區塊(大概在2137年被挖出)之前,新幣的發行速度會以指數形式進行64次“二等分”。到那時每區塊發行比特幣數量變為比特幣的最小貨幣單位——1聰。最終,在經過1,344萬個區塊之後,所有的共20,999,999.9769聰比特幣將全部發行完畢。換句話說,到2140年左右,會存在接近2,100萬比特幣。在那之後,新的區塊不再包含比特幣獎勵,礦工的收益全部來自交易費。
  • #72: 交易的獨立校驗 錢包軟件通過收集UTXO、提供正確的解鎖腳本、構造支付給接收者的輸出這一系列的方式來創建交易。產生的交易隨後將被發送到比特幣網絡臨近的節點,從而使得該交易能夠在整個比特幣網絡中傳播。 然而,在交易傳遞到臨近的節點前,每一個收到交易的比特幣節點將會首先驗證該交易,這將確保只有有效的交易才會在網絡中傳播,而無效的交易將會在第一個節點處被廢棄。 每一個節點在校驗每一筆交易時,都需要對照一個長長的標準列表: ▷交易的語法和數據結構必須正確。 ▷輸入與輸出列表都不能為空。 ▷交易的字節大小是小於MAX_BLOCK_SIZE的。 ▷每一個輸出值,以及總量,必須在規定值的範圍內(小於2,100萬個幣,大於0)。 ▷沒有哈希等於0,N等於-1的輸入(coinbase交易不應當被中繼)。 ▷nLockTime是小於或等於INT_MAX的。 ▷交易的字節大小是大於或等於100的。 ▷交易中的簽名數量應小於簽名操作數量上限。 ▷解鎖腳本(scriptSig)只能夠將數字壓入棧中,並且鎖定腳本(scriptPubkey)必須要符合isStandard的格式(該格式將會拒絕非標準交易)。 ▷池中或位於主分支區塊中的一個匹配交易必須是存在的。 ▷對於每一個輸入,如果引用的輸出存在於池中任何的交易,該交易將被拒絕。 ▷對於每一個輸入,在主分支和交易池中尋找引用的輸出交易。如果輸出交易缺少任何一個輸入,該交易將成為一個孤立的交易。如果與其匹配的交易還沒有出現在池中,那麼將被加入到孤立交易池中。 ▷對於每一個輸入,如果引用的輸出交易是一個coinbase輸出,該輸入必須至少獲得COINBASE_MATURITY(100)個確認。 ▷對於每一個輸入,引用的輸出是必須存在的,並且沒有被花費。 ▷使用引用的輸出交易獲得輸入值,並檢查每一個輸入值和總值是否在規定值的範圍內(小於2100萬個幣,大於0)。 ▷如果輸入值的總和小於輸出值的總和,交易將被中止。 ▷如果交易費用太低以至於無法進入一個空的區塊,交易將被拒絕。 ▷每一個輸入的解鎖腳本必須依據相應輸出的鎖定腳本來驗證。 這些條件能夠在比特幣標準客戶端下的AcceptToMemoryPool、CheckTransaction和CheckInputs函數中獲得更詳細的闡述。請注意,這些條件會隨著時間發生變化,為了處理新型拒絕服務攻擊,有時候也為交易類型多樣化而放寬規則。 在收到交易後,,每一個節點都會在全網廣播前對這些交易進行校驗,並以接收時的相應順序,為有效的新交易建立一個池(交易池)。
  • #73: 比特幣節點需要為內存池中的每筆交易分配一個優先級,並選擇較高優先級的交易記錄來構建候選區塊。交易的優先級是由交易輸入所花費的UTXO的“塊齡”決定,交易輸入值高、“塊齡”大的交易比那些新的、輸入值小的交易擁有更高的優先級。如果區塊中有足夠的空間,高優先級的交易行為將不需要礦工費。 然後,挖礦節點會選出那些包含最小礦工費的交易,並按照“每千字節礦工費”進行排序,優先選擇礦工費高的交易來填充剩下的區塊,區塊大小上限為MAX_BLOCK_SIZE。 如區塊中仍有剩餘空間,挖礦節點可以選擇那些不含礦工費的交易。有些礦工會竭盡全力將那些不含礦工費的交易整合到區塊中,而其他礦工也許會選擇忽略這些交易。 在區塊被填滿後,內存池中的剩餘交易會成為下一個區塊的候選交易。因為這些交易還留在內存池中,所以隨著新的區塊被加到鏈上,這些交易輸入時所引用UTXO的深度(即交易“塊齡”)也會隨著變大。由於交易的優先值取決於它交易輸入的“塊齡”,所以這個交易的優先值也就隨之增長了。最後,一個零礦工費交易的優先值就有可能會滿足高優先級的門檻,被免費地打包進區塊。 比特幣交易中沒有過期、超時的概念,一筆交易現在有效,那麼它就永遠有效。然而,如果一筆交易只在全網廣播了一次,那麼它只會保存在一個挖礦節點的內存中。因為內存池是以未持久化的方式保存在挖礦節點存儲器中的,所以一旦這個節點重新啟動,內存池中的數據就會被完全擦除。而且,即便一筆有效交易被傳播到了全網,如果它長時間未處理,它將從挖礦節點的內存池中消失。如果交易本應該在一段時間內被處理而實際沒有,那麼錢包軟件應該重新發送交易或重新支付更高的礦工費。
  • #74: 區塊中的第一筆交易是筆特殊交易,稱為創幣交易或者coinbase交易。這個交易是由礦工節點構造並用來獎勵礦工們所做的貢獻的。獎勵每21萬個區塊減半(現在每個coinbase獎勵12.5 BTC),除了coinbase獎勵外,還可以得到該區塊所有交易的手續費。 創幣交易不包含“解鎖腳本“(又稱作scriptSig)字段,這個字段被coinbase數據替代,長度最小2字節,最大100字節。除了開始的幾個字節外,礦工可以任意使用coinbase的其他部分,隨意填充任何數據。
  • #75: 為了構造區塊頭,挖礦節點需要填充六個字段,如表8-3中所示。 區塊頭的結構 長度 字段 描述 4 字節 版本 版本號,用來跟踪軟件或協議的升級 32 字節 前區塊哈希 鏈中前一個區塊(父區塊)的哈希值 32 字節 Merkle根 一個哈希值,表示這個區塊中全部交易構成的merkle樹的根 4 字節 時間戳 以Unix紀元開始到當下秒數記錄的區塊生成的時刻 4 bytes 難度目標(Target/bits) 該區塊的工作量證明算法難度目標 4 bytes Nonce 一個用於工作量證明算法的計數器
  • #76: 我們在區塊中看到難度目標,其被標為"難度位"或簡稱"bits"。在區塊277,316中,它的值為0x1903a30c。這個標記的值被存為係數/指數格式,前兩位十六進制數字為冪,接下來得六位為係數。在這個區塊裡,0x19為冪,而0x03a30c為係數。 從公式可以推導出 Target,表示說如果我們算出 Double SHA256( Header ) < Target,就表示我們挖到礦了!
  • #77: 難度目標與難度調整 如前所述,目標決定了難度,進而影響求解工作量證明算法所需要的時間。那麼問題來了:為什麼這個難度值是可調整的?由誰來調整?如何調整? 比特幣的區塊平均每10分鐘生成一個。這就是比特幣的心跳,是貨幣發行速率和交易達成速度的基礎。不僅是在短期內,而是在幾十年內它都必須要保持恆定。在此期間,計算機性能將飛速提升。此外,參與挖礦的人和計算機也會不斷變化。為了能讓新區塊的保持10分鐘一個的產生速率,挖礦的難度必鬚根據這些變化進行調整。事實上,難度是一個動態的參數,會定期調整以達到每10分鐘一個新區塊的目標。簡單地說,難度被設定在,無論挖礦能力如何,新區塊產生速率都保持在10分鐘一個。 難度的調整是在每個完整節點中獨立自動發生的。每2,016個區塊中的所有節點都會調整難度。難度的調整公式是由最新2,016個區塊的花費時長與20,160分鐘(兩週,即這些區塊以10分鐘一個速率所期望花費的時長)比較得出的。難度是根據實際時長與期望時長的比值進行相應調整的(或變難或變易)。簡單來說,如果網絡發現區塊產生速率比10分鐘要快時會增加難度。如果發現比10分鐘慢時則降低難度。最大調整值為4。
  • #78: 因為區塊鍊是去中心化的數據結構,所以不同副本之間不能總是保持一致。區塊有可能在不同時間到達不同節點,導致節點有不同的區塊鏈視角。解決的辦法是,每一個節點總是選擇並嘗試延長代表累計了最大工作量證明的區塊鏈,也就是最長的或最大累計難度的鏈。節點通過將記錄在每個區塊中的難度加總起來,得到建立這個鏈所要付出的工作量證明的總量。只要所有的節點選擇最長累計難度的區塊鏈,整個比特幣網絡最終會收斂到一致的狀態。分叉即在不同區塊鏈間發生的臨時差異,當更多的區塊添加到了某個分叉中,這個問題便會迎刃而解。
  • #79: 在圖例中,我們可以了解網絡中發生分叉的過程。圖例代表簡單的全球比特幣網絡,在真實的情況下,比特幣網絡的拓撲結構不是基於地理位置組織起來的。相反,在同一個網絡中相互連接的節點,可能在地理位置上相距遙遠,我們採用基於地理的拓撲是為了更加簡潔地描述分叉。在真實比特幣網絡裡,節點間的距離按“跳”而不是按照真實位置來衡量。為了便於描述,不同的區塊被標示為不同的顏色,傳播這些區塊的節點網絡也被標上顏色。
  • #80: 當有兩個候選區塊同時想要延長最長區塊鏈時,分叉事件就會發生。正常情況下,分叉發生在兩名礦工在較短的時間內,各自都算得了工作量證明解的時候。兩個礦工在各自的候選區塊一發現解,便立即傳播自己的“獲勝”區塊到網絡中,先是傳播給鄰近的節點而後傳播到整個網絡。每個收到有效區塊的節點都會將其併入並延長區塊鏈。如果該節點在隨後又收到了另一個候選區塊,而這個區塊又擁有同樣父區塊,那麼節點會將這個區塊連接到候選鏈上。其結果是,一些節點收到了一個候選區塊,而另一些節點收到了另一個候選區塊,這時兩個不同版本的區塊鏈就出現了。 假設有這樣一種情況,一個在加拿大的礦工發現了“紅色”區塊的工作量證明解,在“藍色”的父區塊上延長了塊鏈。幾乎同一時刻,一個澳大利亞的礦工找到了“綠色”區塊的解,也延長了“藍色”區塊。那麼現在我們就有了兩個區塊:一個是源於加拿大的“紅色”區塊;另一個是源於澳大利亞的“綠色”。這兩個區塊都是有效的,均包含有效的工作量證明解並延長同一個父區塊。這個兩個區​​塊可能包含了幾乎相同的交易,只是在交易的排序上有些許不同。
  • #81: 比特幣網絡中鄰近(網絡拓撲上的鄰近,而非地理上的)加拿大的節點會首先收到“紅色”區塊,並建立一個最大累計難度的區塊,“紅色”區塊為這個鏈的最後一個區塊(藍色-紅色),同時忽略晚一些到達的“綠色”區塊。相比之下,離澳大利亞更近的節點會判定“綠色”區塊勝出,並以它為最後一個區塊來延長區塊鏈(藍色-綠色),忽略晚幾秒到達的“紅色”區塊。那些首先收到“紅色”區塊的節點,會即刻以這個區塊為父區塊來產生新的候選區塊,並嘗試尋找這個候選區塊的工作量證明解。同樣地,接受“綠色”區塊的節點會以這個區塊為鏈的頂點開始生成新塊,延長這個鏈。
  • #82: 假如工作在“綠色”區塊上的礦工找到了一個“粉色”區塊延長了區塊鏈(藍色-綠色-粉色),他們會立刻傳播這個新區塊,整個網絡會都會認為這個區塊是有效的
  • #83: 所有在上一輪選擇“綠色”區塊為勝出者的節點會直接將這條鏈延長一個區塊。然而,那些選擇“紅色”區塊為勝出者的節點現在會看到兩個鏈:“藍色-綠色-粉色”和“藍色-紅色”,這些節點會根據結果將“藍色-綠色-粉色”這條鏈設置為主鏈,將“藍色-紅色”這條鏈設置為備用鏈。 這些節點接納了新的更長的鏈,被迫改變了原有對區塊鏈的觀點,這就叫做鏈的重新共識。因為“紅”區塊做為父區塊已經不在最長鏈上,導致了他們的候選區塊已經成為了“孤塊”(orphan),所以現在任何原本想要在“藍色-紅色”鏈上延長區塊鏈的礦工都會停下來。全網將“藍色-綠色-粉色”這條鏈識別為主鏈,“粉色”區塊為這條鏈的最後一個區塊。全部礦工立刻將他們產生的候選區塊的父區塊切換為“粉色”,來延長“藍色-綠色-粉色”這條鏈。
  • #84: PPLNS,全稱Pay Per Last N Shares,意思是說“根據過去的N個股份來支付收益”,這意味著,所有的礦工一旦發現了一個區塊,大家將根據每個人自己貢獻的股份數量占比來分配區塊中的貨幣。 舉個例子:假設,張三、李四、王五,這三個人在同一個PPLNS礦池中挖礦,在過去的一段時間裡,張三貢獻了10個股份,李四貢獻3個,王五貢獻12個,加起來是25個股份,這時礦池發現了一個區塊,區塊中含有25個比特幣,那麼,張三就會分到10/25個區塊的獎勵,也就是10個比特幣,而李四獲得3個,王五獲得12個。 在PPLNS模式下,運氣成份非常重要,如果礦池一天能夠發現很多個區塊,那麼大家的分紅也會非常多,如果礦池一天下來都沒有能夠發現區塊,那麼大家也就沒有任何收益。 PPS全稱為Pay Per Share。為了解決PPLNS那種有時候收益很高,有時候沒有收益的情況,PPS採用了新的演算法。PPS根據你的算力在礦池中的占比,並估算了礦池每天可以獲得的礦產,給你每天基本固定的收益。 PPS模式的礦池為了避免虧本風險,往往會收取7%-8%的高額手續費。 FPPS跟PPS幾乎一樣,只差在FPPS有把Coinbase的手續費也拿出來分享。
  • #85: 當一個或者一群擁有了整個系統中大量算力的礦工出現之後,他們就可以通過攻擊比特幣的共識機制來達到破壞比特幣網絡的安全性和可靠性的目的。 共識攻擊的一個典型場景就是“51%攻擊”。想像這麼一個場景,一群礦工控制了整個比特幣網絡51%的算力,他們聯合起來打算攻擊整個比特幣系統。由於這群礦工可以生成絕大多數的塊,他們就可以通過故意製造塊鏈分叉來實現“雙重支付”或者通過拒絕服務的方式來阻止特定的交易或者攻擊特定的錢包地址。 區塊鏈分叉/雙重支付攻擊指的是攻擊者通過不承認最近的某個交易,並在這個交易之前重構新的塊,從而生成新的分叉,繼而實現雙重支付。有了充足算力的保證,一個攻擊者可以一次性篡改最近的6個或者更多的區塊,從而使得這些區塊包含的本應無法篡改的交易消失。值得注意的是,雙重支付只能在攻擊者擁有的錢包所發生的交易上進行,因為只有錢包的擁有者才能生成一個合法的簽名用於雙重支付交易。攻擊者只能在自己的交易上進行雙重支付攻擊,但當這筆交易對應的是不可逆轉的購買行為的時候,這種攻擊就是有利可圖的。