今天我們進入《精通比特幣》第三章,比特幣實現參考,以及第四章的第一部分。第四章比較長,所以大家要有耐心,因為真正的學習就是沉下心慢慢看,慢慢品。
本章原文地址
第四章原文地址
https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc
相關文章:
?第3章比特幣實現參考?
Bitcoin Core: The Reference Implementation
Bitcoin is an?open source?project and the source code is available under an open (MIT) license, free to download and use for any purpose. Open source means more than simply free to use. It also means that bitcoin is developed by an open community of volunteers. At first, that community consisted of only Satoshi Nakamoto. By 2016, bitcoin’s source code had more than 400 contributors with about a dozen developers working on the code almost full-time and several dozen more on a part-time basis. Anyone can contribute to the code—including you!
比特幣的代碼是公開的,由社區共同維護。到2016年,已經有400多位代碼貢獻者。你也可以給代碼提建議(前提是你能看得懂)。
When bitcoin was created by Satoshi Nakamoto,?the software was actually completed before the whitepaper?reproduced in?[satoshi_whitepaper]?was written. Satoshi wanted to make sure it worked before writing about it. That first implementation, then simply known as "Bitcoin" or "Satoshi client," has?been heavily modified and improved.?It has evolved into what is known as?Bitcoin Core, to differentiate it from other compatible implementations. Bitcoin Core is the?reference implementation?of the bitcoin system, meaning that it is the authoritative reference on how each part of the technology should be implemented. Bitcoin Core implements all aspects of bitcoin, including wallets, a transaction and block validation engine, and a full network node in the peer-to-peer bitcoin network.
中本聰是先寫完比特幣的代碼,再寫白皮書的。不過比特幣最初由中本聰實現的版本,已經大幅修改,并演進成“比特幣核心”版本,這也是比特幣的參考實現。比特幣核心版本實現了比特幣的各個方面,包括錢包、交易、塊驗證引擎、以及比特幣網絡的全節點。
Warning?Even though Bitcoin Core includes a reference implementation of a wallet,?this is not intended to be used as a production wallet for users or for applications.?Application developers are advised to build wallets using modern standards such as BIP-39 and BIP-32 (see [mnemonic_code_words] and [hd_wallets]). BIP stands for Bitcoin Improvement Proposal.
盡管有比特幣參考實現,但是仍然建議采用更新的修正版本,例如BIP-39或者BIP-32.
Bitcoin Core architecture (Source: Eric Lombrozo)?shows the architecture of Bitcoin Core.
Figure 1. Bitcoin Core architecture (Source: Eric Lombrozo)
下面講的就是如何在你的計算機上部署比特幣,由于有較多計算機指令,建議讀者自行閱讀原文,根據指示步驟處理。
?第4章比特幣密鑰與地址(第一部分)?
這一章將進入密碼學的范疇。
https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc
Keys, Addresses
You may have heard that bitcoin is based on?cryptography, which is a branch of mathematics used extensively in computer security.?Cryptography means "secret writing" in Greek, but the science of cryptography encompasses more than just secret writing, which is referred to as encryption.?Cryptography can also be used to prove knowledge of a secret without revealing that secret (digital signature), or prove the authenticity of data (digital fingerprint).?These types of cryptographic proofs are the mathematical tools critical to bitcoin and used extensively in bitcoin applications. Ironically, encryption is not an important part of bitcoin, as its communications and transaction data are not encrypted and do not need to be encrypted to protect the funds. In this chapter we will introduce some of the cryptography used in bitcoin to control ownership of funds, in the form of keys, addresses, and wallets.
密碼學的英文單詞的希臘語含義是“秘密書寫”,也就是所謂的加密。除了加密,還能可以在不泄密的情況下證明自己掌握了秘密(簽名)以及證明數據真實性(電子指紋)。加密不是比特幣中的重要屬性,因為比特幣中的交易公開,并不需要通過加密來保證其安全性。本章將介紹比特幣中采用的密碼技術。
Introduction
Ownership of bitcoin is established through?digital keys,?bitcoin addresses, and?digital signatures.?The digital keys are not actually stored in the network, but are instead created and stored by users in a file, or simple database, called a?wallet. The digital keys in a user’s wallet are completely independent of the bitcoin protocol and can be generated and managed by?the user’s wallet software without reference to the blockchain or access to the internet.?Keys enable many of the interesting properties of bitcoin, including decentralized trust and control, ownership attestation, and the cryptographic-proof security model.
比特幣的所有權是通過電子密鑰、比特幣地址以及電子簽名構成。電子密鑰不保存在比特幣網絡,僅僅存在用戶的錢包中,而且不需要連網或者連區塊鏈就能訪問到。
Most bitcoin transactions require a valid digital signature to be included in the blockchain, which can only be generated with a secret key; therefore, anyone with a copy of that key has control of the bitcoin. The digital signature used to spend funds is also referred to as a?witness, a term used in cryptography. The witness data in a bitcoin transaction testifies to the true ownership of the funds being spent.
大部分比特幣交易需要有效數字簽名,這個簽名只能由用戶密鑰完成。我們可以把用戶私鑰簽名的過程,想象成紅頭文件蓋的章,簽名其實和蓋章一樣。一般人拿不到公章,于是當你看到公章的時候,你就知道這是經過授權的。
Keys come in pairs consisting of a private (secret) key and a public key. Think of the public key as similar to a?bank account number?and the private key as similar to the?secret PIN, or signature on a check, that provides control over the account. These digital keys are very rarely seen by the users of bitcoin. For the most part, they are stored inside the?wallet file and managed by the bitcoin wallet software.
用戶的密鑰往往是由一對密鑰組成,一個是公鑰,一個是私鑰。公鑰就是公開的字符串,網上任何人都可以查到,有點像我們的銀行賬號一樣,公布出去才能收到別人給我們的轉賬。私鑰就像賬號的密碼,只有你才有。在比特幣當中,大部分情況下用戶不接觸私鑰,被保存在比特幣錢包軟件中。
In the payment portion of a bitcoin transaction,?the recipient’s public key is represented by its digital fingerprint, called a?bitcoin address,?which is used in the same way as the beneficiary name on a check (i.e., "Pay to the order of").?In most cases, a bitcoin address is generated from and corresponds to a public key.?However, not all bitcoin addresses represent public keys; they can also represent other beneficiaries?such as scripts,?as we will see later in this chapter. This way, bitcoin addresses abstract the recipient of funds, making transaction destinations flexible, similar to paper checks: a single payment instrument that can be used to?pay into people’s accounts, pay into company accounts, pay for bills, or pay to cash.?The bitcoin address is the only representation of the keys that users will routinely see, because this is the part they need to share with the world.
在比特幣的支付過程中,收方的公鑰由一串數字指紋公開表示,被稱作比特幣地址。大多數情況比特幣地址是由收方的公鑰生成,但是并不是所有的比特幣地址都如此,有的也可以由腳本來代替。這樣一個比特幣的地址就可以有多種功能,比如說,向個人賬戶支付、向公司的賬戶支付、支付賬單或者支付現金等。
First, we will introduce cryptography and explain the mathematics used in bitcoin. Next, we will look at how keys are generated, stored, and managed. We will review the various encoding formats used to represent private and public keys, addresses, and script addresses. Finally, we will look at advanced use of keys and addresses: vanity, multisignature, and script addresses and paper wallets.
Public Key Cryptography and Cryptocurrency
Public key cryptography was invented in the 1970s and is a mathematical foundation for computer and information security.
公鑰密碼學于20世紀70年代發明,是信息安全的數學基礎。
Since the invention of public key cryptography, several suitable mathematical functions, such as?prime number exponentiation?and?elliptic curve multiplication, have been discovered.?These mathematical functions are practically?irreversible, meaning that they are?easy to calculate in one direction and infeasible to calculate in the opposite direction.?Based on these mathematical functions, cryptography enables the creation of digital secrets and unforgeable digital signatures.?Bitcoin uses elliptic curve multiplication as the basis for its cryptography.
公鑰密碼學最開始是一種概念設想,之后數學家們找到了合適的數學模型用于實現。比如素數的指數運算以及橢圓曲線乘法的數學特性被相繼用來構造數學函數,這些函數的一個特點是計算不可逆。不可逆的意思是,函數正向運算比較簡單,逆運算卻非常困難。基于這樣單向不對等性,才能構造出密碼學的算法安全性。比特幣采用了橢圓曲線乘法作為密碼學的基礎。
In bitcoin, we use public key cryptography to create a key pair that controls access to bitcoin. The key pair consists of a private key and—derived from it—a unique public key.?The public key is used to receive funds, and the private key is used to sign transactions to spend the funds.
There is a mathematical relationship between the public and the private key that allows the private key to be used to generate signatures on messages. This signature can be validated against the public key without revealing the private key.
比特幣用公私鑰對來進行安全控制。公鑰拿來收錢,私鑰在花錢時拿來簽名。簽名了以后可以用公鑰驗證真偽,這樣私鑰也不會泄露。
When spending bitcoin, the current bitcoin owner presents?her public key and a signature (different each time, but created from the same private key) in a transaction to spend those bitcoin. Through the presentation of the public key and signature, everyone in the bitcoin network can verify and accept the transaction as valid, confirming that the person transferring the bitcoin owned them at the time of the transfer.
花錢的時候,手里拿著錢的人,就要把自己的公鑰以及經過簽名的交易信息公布出來。簽名相當于依據私鑰和待簽名的交易,生成一個字符串,這樣,每次的簽名都不一樣。
Tip:?In most wallet implementations, the private and public keys are stored together as a key pair for convenience. However, the public key can be calculated from the private key, so storing only the private key is also possible.
大多數錢包會把公鑰與私鑰存在一塊,實際上,根據私鑰可以算出公鑰。所以其實只存私鑰也夠。
Private and Public Keys
A bitcoin wallet contains a collection of key pairs, each consisting of a private key and a public key.?The private key (k) is a number, usually picked at random.?From the private key, we use elliptic curve multiplication, a one-way cryptographic function, to generate a public key (K). From the public key (K),?we use a one-way cryptographic hash function to generate a bitcoin address (A).?In this section, we will start with generating the private key, look at the elliptic curve math that is used to turn that into a public key, and finally, generate a bitcoin address from the public key. The relationship between private key, public key, and bitcoin address is shown in?Private key, public key, and bitcoin address.
比特幣中,私鑰P是隨機選擇的一個數,公鑰K由私鑰根據橢圓曲線算法生成,比特幣地址是根據公鑰隨機生成的一串字符。
Figure 1. Private key, public key, and bitcoin address
Why Use Asymmetric Cryptography (Public/Private Keys)?
Why is asymmetric cryptography used in bitcoin? It’s not used to "encrypt" (make secret) the transactions. Rather, the useful property of asymmetric cryptography is the ability to?generate?digital signatures.?A private key can be applied to the digital fingerprint of a transaction to produce a numerical signature.?This signature can only be produced by someone with knowledge of the private key.?However, anyone with access to the public key and the transaction fingerprint can use them to?verify?the signature. This useful property of asymmetric cryptography makes it possible for anyone to verify every signature on every transaction, while ensuring that only the owners of private keys can produce valid signatures.
注意,在密碼學里有對稱密碼與非對稱密碼(公鑰密碼)的區分。對稱密碼就是傳統中的加密,把一段信息用各種變換方法,轉換成密文,在沒有密碼的情況下,你無法知道信息。這里加密和解密都采用同樣的密碼。非對稱密碼有一個特點,就是會有兩個密鑰,一公一私。公的可以公開,私的保密,僅供使用者所有。而用私鑰簽名就是,用只有你掌握的信息生成一串數字簽名,這串數字簽名,任何其他人無法生成;而且其他人可以根據這串簽名,用你的公鑰驗證,這的確是你簽的。
這個有點類似,你去銀行取錢,你只要掌握了你的銀行卡密碼,任何工作人員驗證了是你,就可以給你錢,而不需要和你認識。
推薦閱讀一篇清華大學關于王小云教授的報道清華人物 | 解密王小云院士
Private Keys
A private key is simply a number, picked at random.?Ownership and control over the private key is the root of user control over all funds associated with the corresponding bitcoin address.?The private key is used to create signatures that are required to spend bitcoin by proving ownership of funds used in a transaction. The private key must remain secret at all times, because revealing it to third parties is equivalent to giving them control over the bitcoin secured by that key. The private key must also be backed up and protected from accidental loss, because if it’s lost it cannot be recovered and the funds secured by it are forever lost, too.
私鑰的保密就意味著全部。誰掌握了私鑰,誰就掌握了私鑰對應的所有錢。如果你丟失了私鑰,那這筆錢你也永遠拿不回來。如果你要生成私鑰,可以隨機選擇一個數字,或者扔256次硬幣。
Tip:? The bitcoin private key is just a number. You can pick your private keys randomly using just a coin, pencil, and paper: toss a coin 256 times and you have the binary digits of a random private key you can use in a bitcoin wallet. The public key can then be generated from the private key.
Generating a private key from a random number
The first and most important step in generating keys is to find a secure source of entropy, or randomness. Creating a bitcoin key is essentially the same as "Pick a number between 1 and 2256." The exact method you use to pick that number does not matter as long as it is not predictable or repeatable. Bitcoin software?uses the underlying operating system’s random number generators to produce 256 bits of entropy?(randomness). Usually, the OS random number generator is initialized by a human source of randomness, which is why you may be asked to wiggle your mouse around for a few seconds.
More precisely, the private key can be any number between 0 and n - 1 inclusive, where n is a constant (n = 1.1578 * 1077, slightly less than 2256) defined as the order of the elliptic curve used in bitcoin (see?Elliptic Curve Cryptography Explained). To create such a key,?we randomly pick a 256-bit number and check that it is less than n.?In programming terms, this is usually achieved by feeding a larger string of random bits, collected from a cryptographically secure source of randomness, into the SHA256 hash algorithm, which will conveniently produce a 256-bit number. If the result is less than n, we have a suitable private key. Otherwise, we simply try again with another random number.
私鑰的選取就是在1到?2的256次方中,隨機選擇一個小于n的數。為了確保足夠隨機,會再做一些處理;同時,還需要滿足橢圓曲線的基本要求。
Warning:?Do not write your own code to create a random number or use a "simple" random number generator offered by your programming language. Use a cryptographically secure pseudorandom number generator (CSPRNG) with a seed from a source of sufficient entropy. Study the documentation of the random number generator library you choose to make sure it is cryptographically secure. Correct implementation of the CSPRNG is critical to the security of the keys.
這里要注意的是,不要隨便用簡單的隨機數生成器生成隨機數,安全性可能會受到影響。
The following is a randomly generated private key (k) shown in hexadecimal format (256 bits shown as 64 hexadecimal digits, each 4 bits):
Tip?: The size of bitcoin’s private key space, (2^256) is an unfathomably large number. It is approximately 10^77 in decimal. For comparison, the visible universe is estimated to contain 10^80 atoms.
注意2的256次方是非常大的樣本空間,接近10^77次方,目前觀測到的宇宙的包括的原子數是10^80個。
本節的以下部分主要講了怎么在系統上查看自己的私鑰。
To generate a new key with the Bitcoin Core client (see?[ch03_bitcoin_client]), use the getnewaddress command. For security reasons it displays the public key only, not the private key. To ask bitcoind to expose the private key, use the dumpprivkey command. The dumpprivkey command shows the private key in a Base58 checksum-encoded format called the?Wallet Import Format?(WIF), which we will examine in more detail in?Private key formats. Here’s an example of generating and displaying a private key using these two commands:
The dumpprivkey command opens the wallet and extracts the private key that was generated by the getnewaddress command. It is not possible for bitcoind to know the private key from the public key unless they are both stored in the wallet.
Tip?The dumpprivkey command does not generate a private key from a public key, as this is impossible. The command simply reveals the private key that is already known to the wallet and which was generated by the getnewaddress command.
You can also use the Bitcoin Explorer command-line tool (see?[appdx_bx]) to generate and display private keys with the commands seed, ec-new, and ec-to-wif:
Public Keys
The public key is calculated from the private key using elliptic curve multiplication, which is irreversible:?K?=?k?*?G, where?k?is the private key,?G?is a constant point called the?generator point, and?K?is the resulting public key. The reverse operation, known as?"finding the discrete logarithm"—calculating?k?if you know?K—is as difficult as trying all possible values of?k, i.e., a brute-force search. Before we demonstrate how to generate a public key from a private key, let’s look at elliptic curve cryptography in a bit more detail.
在橢圓曲線上有一種稱作“點乘”的運算,可以用公式?K?=?k?*?G表示。G就是橢圓曲線上的一個點,k就是隨機選擇的一個私鑰。橢圓曲線有這樣一個性質,從小寫的k算出大寫K很容易,但是由大寫K反推小寫k有難度。這種反推就叫做“求離散對數”,這個問題在計算上是很難的。這種數學上的特性,就是構造公鑰密碼學的基石,也是比特幣用來證明貨幣歸屬的重要技術手段。
Tip??Elliptic curve multiplication is a type of function that cryptographers call a "trap door" function: it is easy to do in one direction (multiplication) and impossible to do in the reverse direction (division). The owner of the private key can easily create the public key and then share it with the world knowing that no one can reverse the function and calculate the private key from the public key.?This mathematical trick becomes the basis for unforgeable and secure digital signatures that prove ownership of bitcoin funds.
?
Elliptic Curve Cryptography Explained
Elliptic curve cryptography is a type of asymmetric or public key cryptography based on the discrete logarithm problem as expressed by addition and multiplication on the points of an elliptic curve.
橢圓曲線密碼學是一種非對稱的公鑰密碼學,依托有限域上的離散對數問題。在橢圓曲線上,運算是通過點的加法與標量乘法來實現。橢圓曲線有非常遙遠的歷史,可以追溯到數論里的整除的問題。這部分我們先不展開,你可以理解為一個二元三次方程對應在坐標軸上繪出的曲線。
An elliptic curve?is an example of an elliptic curve, similar to that used by bitcoin.
Figure 2. An elliptic curve
Bitcoin uses a specific elliptic curve and set of mathematical constants, as defined in a standard called secp256k1, established by the National Institute of Standards and Technology (NIST). The secp256k1 curve is defined by the following function, which produces an elliptic curve:
比特幣采用了以下參數的橢圓曲線y^2 = (x^3 + 7),這里讀者應該能對接上高中的數學知道了。
or
這里作者加了一個模操作,模在數學里是一個很有張力的特性。模p就是把一個數除以p,然后取余數,于是得到的結果無非就是從0到p-1。所以把上面的方程求模,本質上就映射到了一個有限的離散域上,當變成了離散的數以后,就不能畫出曲線,而是一個又一個的點了。更多知識涉及到了抽象代數的概念,這里先不展開了。
Because this curve is defined over a finite field of prime order instead of over the real numbers,?it looks like a pattern of dots scattered in two dimensions, which makes it difficult to visualize.?However, the math is identical to that of an elliptic curve over real numbers. As an example,?Elliptic curve cryptography: visualizing an elliptic curve over F(p), with p=17?shows the same elliptic curve over a much smaller finite field of prime order 17, showing a pattern of dots on a grid. The secp256k1 bitcoin elliptic curve can be thought of as a much more complex pattern of dots on a unfathomably large grid.
Figure 3. Elliptic curve cryptography: visualizing an elliptic curve over F(p), with p=17
So, for example, the following is a point P with coordinates (x,y) that is a point on the secp256k1 curve:
這里舉了一個例子,在曲線上選擇了一個點,代入到方程里正好等式成立。你可以用參數自己在計算機上算一下。
Using Python to confirm that this point is on the elliptic curve?shows how you can check this yourself using Python:
Example 1. Using Python to confirm that this point is on the elliptic curve
In elliptic curve math, there is a point called the "point at infinity," which roughly corresponds to the role of zero in addition. On computers, it’s sometimes represented by x = y = 0 (which doesn’t satisfy the elliptic curve equation, but it’s an easy separate case that can be checked).
橢圓曲線上有一個“無窮遠點”,有點像加法中的0一樣。也有一個加的運算,就和我們小學學的數的加法一樣。
There is also a + operator, called "addition," which has some properties similar to the traditional addition of real numbers that gradeschool children learn. Given two points P1?and P2?on the elliptic curve, there is a third point P3?= P1?+ P2, also on the elliptic curve.
Geometrically,?this third point P3?is calculated by drawing a line between P1?and P2. This line will intersect the elliptic curve in exactly one additional place. Call this point P3' = (x, y). Then reflect in the x-axis to get P3?= (x, –y).
There are a couple of special cases that explain the need for the "point at infinity."
假設有P3?= P1?+ P2,,那么P3的結果就是,連接P1和P2點的線,與橢圓曲線的交點,再取x軸的對稱點。當然,如果P1和P2是同一個點,那么這條線就變成了曲線的切線,也就代表了此處的斜率。
If P1?and P2?are the same point, the line "between" P1?and P2?should extend to be the tangent on the curve at this point P1. This tangent will intersect the curve in exactly one new point.?You can use techniques from calculus to determine the slope of the tangent line.?These techniques curiously work, even though we are restricting our interest to points on the curve with two integer coordinates!
In some cases (i.e., if P1?and P2?have the same x values but different y values), the tangent line will be exactly vertical, in which case P3 = "point at infinity."
If P1?is the "point at infinity," then P1?+ P2?= P2. Similarly, if P2?is the point at infinity, then P1?+ P2?= P1. This shows how the point at infinity plays the role of zero.
如果P1和P2關于x軸對稱,那連接P1和P2的點就變成垂線,斜率無窮大,P3就會是“無窮遠”點。
It turns out that + is associative, which means that (A + B) + C = A + (B + C). That means we can write A + B + C without parentheses and without ambiguity.
在這里,點的加法滿足結合律,所以A+B+C不需要通過括號來框定優先級。
Now that we have defined addition, we can define multiplication in the standard way that extends addition. For a point P on the elliptic curve, if k is a whole number, then kP = P + P + P + … + P (k times). Note that k is sometimes confusingly called an "exponent" in this case.
把k個P相加,用一個乘法表示,于是就中kP,這就是標量乘法,k也可以稱作是指數。
Generating a Public Key
Starting with a private key in the form of a randomly generated number?k, we multiply it by a predetermined point on the curve called the?generator point?G?to produce another point somewhere else on the curve, which is the corresponding public key?K. The generator point is specified as part of the secp256k1 standard and is always the same for all keys in bitcoin:
where?k?is the private key,?G?is the generator point, and?K?is the resulting public key, a point on the curve.?Because the generator point is always the same for all bitcoin users, a private key?k?multiplied with?G?will always result in the same public key?K.?The relationship between?k?and?K?is fixed, but can only be calculated in one direction, from?k?to?K. That’s why a bitcoin address (derived from?K) can be shared with anyone and does not reveal the user’s private key (k).
比特幣生成公鑰,是通過一確定的生成子G,乘以隨機選擇的私鑰?k?達成的效果。知道私鑰可以生成公鑰,反之卻不行,這是前文已經介紹過的特性。
Tip?A private key can be converted into a public key, but a public key cannot be converted back into a private key because the math only works one way.
Implementing the elliptic curve multiplication, we take the private key?k?generated previously and multiply it with the generator point G to find the public key?K:
Public key?K?is defined as a point K = (x,y):
To visualize multiplication of a point with an integer, we will use the simpler elliptic curve over real numbers—remember, the math is the same. Our goal is to find the multiple?kG?of the generator point?G, which is the same as adding?G?to itself,?k?times in a row. In elliptic curves, adding a point to itself is the equivalent of drawing a tangent line on the point and finding where it intersects the curve again, then reflecting that point on the x-axis.
Elliptic curve cryptography: visualizing the multiplication of a point G by an integer k on an elliptic curve?shows the process for deriving?G,?2G,?4G, as a geometric operation on the curve.
這里作者用可視化的方式,展示了橢圓曲線上加法的過程。
從G算到8G就是
G+G=2G,2G+2G=4G,4G+4G=8G這樣演示的。
Tip?Most bitcoin implementations use the OpenSSL cryptographic library to do the elliptic curve math. For example, to derive the public key, the function EC_POINT_mul() is used.
利用OpenSSL密碼庫可以做橢圓曲線的運算。我在大學的時候玩過這個密碼庫的源碼。
Figure 4. Elliptic curve cryptography: visualizing the multiplication of a point G by an integer k on an elliptic curve
后面講的深入很多,本來想一次全部推送完的,但是公眾號字數限制了,下一篇再接著推。
歡迎大家關注我的新號,“刻意學習區塊鏈”,我會把我所有關于區塊鏈和比特幣學習解析的文章,匯總在上面便于檢索,這是ScalersTalk成長持續論的一個分叉。?搜索“刻意學習區塊鏈”關注。?