《精通比特幣》英文版批注導讀?第4章(2)比特幣地址

今天我們進入《精通比特幣》第四章第二部分。這部分把錢包地址什么的,基本上講透了。

本章原文地址

https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc#decode-from-base58check

https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc#implementing-keys-and-addresses-in-c

https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc#generating-vanity-addresses


相關文章:

《精通比特幣》英文版批注導讀·第1章

《精通比特幣》英文版批注導讀?第2章比特幣工作原理

《精通比特幣》英文版批注導讀?第3-4章比特幣密鑰與地址

Bitcoin Addresses

A bitcoin address is a string of digits and characters that can be shared with anyone who wants to send you money.?Addresses produced from public keys consist of a string of numbers and letters, beginning with the digit "1." Here’s an example of a bitcoin address:

比特幣地址就是一串字符,其他人通過這個地址可以給你轉錢。地址以1打頭:

1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy

The bitcoin address is what appears most commonly in a transaction as the "recipient" of the funds. If we compare a bitcoin transaction to a paper check, the bitcoin address is the beneficiary, which is what we write on the line after "Pay to the order of." On a paper check, that beneficiary can sometimes be the name of a bank account holder, but can also include corporations, institutions, or even cash. Because paper checks do not need to specify an account, butrather use an abstract name as the recipient of funds,they are very flexible payment instruments. Bitcoin transactions use a similar abstraction, the bitcoin address, to make them very flexible. A bitcoin address can represent theowner of a private/public key pair, or it can represent something else, such as a payment script, as we will see in[p2sh]. For now, let’s examine the simple case, a bitcoin address that represents, and is derived from, a public key.

比特幣的地址不僅可以代表公私鑰對的所有權,也可以代表支付腳本等。

The bitcoin address is derived from the public key through the use of one-way cryptographic hashing.?A "hashing algorithm" or simply "hash algorithm" is a one-way function that produces a fingerprint or "hash" of an arbitrary-sized input. Cryptographic hash functions are used extensively in bitcoin: in bitcoin addresses, in script addresses, and in the mining Proof-of-Work algorithm. The algorithms used to make a bitcoin address from a public key are the Secure Hash Algorithm (SHA) and the RACE Integrity Primitives Evaluation Message Digest (RIPEMD), specificallySHA256 and RIPEMD160.

比特幣地址根據(jù)公鑰,通過單向哈希函數(shù)生成,采用的算法是SHA256?和RIPEMD160。具體的過程是,先做SHA256運算,再把結果做RIPEMD160運算,最后生成一個20字節(jié)的字符串。

Starting with the public keyK, we compute the SHA256 hash and then compute the RIPEMD160 hash of the result, producing a 160-bit (20-byte) number:

\[\begin{equation} {A = RIPEMD160(SHA256(K))} \end{equation}\]

whereKis the public key andAis the resulting bitcoin address.

Tip?A bitcoin address is not the same as a public key. Bitcoin addresses are derived from a public key using a one-way function.

注意:比特幣地址并不是比特幣的公鑰,是由公鑰通過單向函數(shù)轉換而來。比特幣的地址采用BASE58編碼。除了BASE58編碼,我們還有像BASE64編碼、BASE32編碼等。

Bitcoin addresses are almost always encoded as "Base58Check" (see?Base58 and Base58Check Encoding), which uses 58 characters (a Base58 number system) and a checksum to help human readability, avoid ambiguity, and protect against errors in address transcription and entry. Base58Check is also used in many other ways in bitcoin, whenever there is a need for a user to read and correctly transcribe a number, such as a bitcoin address, a private key, an encrypted key, or a script hash. In the next section we will examine the mechanics of Base58Check encoding and decoding and the resulting representations.Public key to bitcoin address: conversion of a public key into a bitcoin address?illustrates the conversion of a public key into a bitcoin address.

Figure 5. Public key to bitcoin address: conversion of a public key into a bitcoin address

Base58 and Base58Check Encoding

In order to represent long numbers in a compact way, using fewer symbols, many computer systems use mixed-alphanumeric representations with a base (or radix) higher than 10. For example, whereas?the traditional decimal system uses the 10 numerals 0 through 9, the hexadecimal system uses 16,with the letters A through F as the six additional symbols. A number represented in hexadecimal format is shorter than the equivalent decimal representation. Even more compact, Base64 representation uses 26 lowercase letters, 26 capital letters, 10 numerals, and 2 more characters such as “``” and "/" to transmit binary data over text-based media such as email.Base64 is most commonly used to add binary attachments to email.?Base58 is a text-based binary-encoding format developed for use in bitcoin and used in many other cryptocurrencies. It offers a balance between compact representation, readability, and error detection and prevention. Base58 is a subset of Base64, using upper- and lowercase letters and numbers, but omitting some characters that are frequently mistaken for one another and can appear identical when displayed in certain fonts. Specifically, Base58 is Base64 without the 0 (number zero), O (capital o), l (lower L), I (capital i), and the symbols “``” and "/". Or, more simply, it is a set of lowercase and capital letters and numbers without the four (0, O, l, I) just mentioned.Bitcoin’s Base58 alphabet?shows the full Base58 alphabet.

采用不同進制的編碼的目的,是為了更加緊湊的表示數(shù)。比如十進制,就會用0-9表示10個數(shù),十六進制就會用0-F表示16個數(shù),BASE64編碼用的是52個英文大小寫、10個數(shù)字以及+和/來代表64個數(shù)。BASE58主要用在加密貨幣中,和BASE64原理差不多,就是剔除了一些長得很像的字母,比如數(shù)字0和字母O等。

Example 2. Bitcoin’s Base58 alphabet

To add extra security against typos or transcription errors, Base58Check is a Base58 encoding format, frequently used in bitcoin, which has a built-in error-checking code.The checksum is an additional four bytes added to the end of the data that is being encoded.The checksum is derived from the hash of the encoded data and can therefore be used to detect and prevent transcription and typing errors. When presented with Base58Check code, the decoding software will calculate the checksum of the data and compare it to the checksum included in the code. If the two do not match, an error has been introduced and the Base58Check data is invalid.This prevents a mistyped bitcoin address from being accepted by the wallet software as a valid destination, an error that would otherwise result in loss of funds.

另外在轉換成比特幣地址的時候,在BASE58的結果后會加入校驗位,這樣在收到的時候可以檢查一下地址正確性,以免把錢轉錯造成損失。

To convert data (a number) into a Base58Check format, we first add a prefix to the data, called the "version byte," which serves to easily identify the type of data that is encoded. For example, in the case of a bitcoin address the prefix is zero (0x00 in hex), whereas the prefix used when encoding a private key is 128 (0x80 in hex). A list of common version prefixes is shown in?Base58Check version prefix and encoded result examples.

另外,為了便于識別一串字串是不是BASE58編碼,在字符串前面還要加上前綴,比如比特幣地址前面加上0x00,私鑰前面加上的是0x80。

Next, we compute the "double-SHA" checksum, meaning we apply the SHA256 hash-algorithm twice on the previous result (prefix and data):

校驗碼是通過兩次SHA256計算的方式得到,取結果的前4個字節(jié)作為校驗碼,附在編碼的最后。于是編碼就分成了三部分,前綴、數(shù)據(jù)以及校驗和。

From the resulting 32-byte hash (hash-of-a-hash), we take only the first four bytes. These four bytes serve as the error-checking code, or checksum. The checksum is concatenated (appended) to the end.

The result is composed of three items: a prefix, the data, and a checksum. This result is encoded using the Base58 alphabet described previously.?Base58Check encoding: a Base58, versioned, and checksummed format for unambiguously encoding bitcoin data?illustrates the Base58Check encoding process.

Figure 6. Base58Check encoding: a Base58, versioned, and checksummed format for unambiguously encoding bitcoin data

In bitcoin, most of the data presented to the user is Base58Check-encoded to make it compact, easy to read, and easy to detect errors. The version prefix in Base58Check encoding is used to create easily distinguishable formats,which when encoded in Base58 contain specific characters at the beginning of the Base58Check-encoded payload.These characters make it easy for humans to identify the type of data that is encoded and how to use it. This is what differentiates, for example, a Base58Check-encoded bitcoin address that starts with a 1 from a Base58Check-encoded private key WIF that starts with a 5.Some example version prefixes and the resulting Base58 characters are shown inBase58Check version prefix and encoded result examples.

加上了前綴以后,就可以比較容易地通過前綴看到地址的類型了。比如比特幣地址是1打頭,私鑰是5打頭。

Table 1. Base58Check version prefix and encoded result examples

Both private and public keys can be represented in a number of different formats. These representations all encode the same number, even though they look different. These formats are primarily used to make it easy for people to read and transcribe keys without introducing errors.Key Formats

Private key formats

The private key can be represented in a number of different formats, all of which correspond to the same 256-bit number.?Private key representations (encoding formats)shows three common formats used to represent private keys.Different formats are used in different circumstances.?Hexadecimal and raw binary formats are used internally in software and rarely shown to users. The WIF is used for import/export of keys between wallets and often used in QR code (barcode) representations of private keys.

私鑰可以有不同的表示形式,比如最原始的二進制表示,十六進制表示,WIF等。這些形式間可以相互轉換。

Table 2. Private key representations (encoding formats)

Table 3. Example: Same key, different formatsExample: Same key, different formats?shows the private key generated in these three formats.

We use the wif-to-ec command from Bitcoin Explorer (see?[appdx_bx]) to show that both WIF keys represent the same private key:All of these representations are different ways of showing the same number, the same private key.They look different, but any one format can easily be converted to any other format.?Note that the "raw binary" is not shown inExample: Same key, different formats?as any encoding for display here would, by definition, not be raw binary data.

Decode from Base58Check

考慮到篇幅原因,編碼轉換的代碼案例,我們不展開論述,原文參見

https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc#decode-from-base58check

Public key formats

Public keys are also presented in different ways, usually as eithercompressedoruncompressedpublic keys.

As we saw previously, the public key is a point on the elliptic curve consisting of a pair of coordinates (x,y). It is usually presented with the prefix 04 followed by two 256-bit numbers:one for thexcoordinate of the point, the other for theycoordinate.The prefix 04 is used to distinguish uncompressed public keys from compressed public keys that begin with a 02 or a 03.

公鑰有兩種表示方式,壓縮版和未壓縮版。壓縮版的前綴是04,后面有兩個256位的數(shù)字分別代表x坐標值和y坐標值。如果是壓縮版本的公鑰,則采用02或者03前綴。以下為示例。

Here’s the public key generated by the private key we created earlier, shown as the coordinates x and y:

Here’s the same public key shown as a 520-bit number (130 hex digits) with the prefix 04 followed by x and then y coordinates, as 04 x y:

Compressed public keys

Compressed public keys were introduced to bitcoin to reduce the size of transactions and conserve disk space on nodes that store the bitcoin blockchain database.Most transactions include the public key, which is required to validate the owner’s credentials and spend the bitcoin.Each public key requires 520 bits (prefix + x + y), which when multiplied by several hundred transactions per block, or tens of thousands of transactions per day, adds a significant amount of data to the blockchain.

大部分交易需要包含公鑰,用于驗證有效性。一枚公鑰需要占據(jù)520位的長度,而每一筆交易都存儲一個公鑰,那造成的開銷也不小。

As we saw in the section?Public Keys, a public key is a point (x,y) on an elliptic curve. Because the curve expresses a mathematical function, a point on the curve represents a solution to the equation and, therefore, if we knowthexcoordinate we can calculate theycoordinate by solving the equation y2?mod p = (x3?+ 7) mod p. That allows us to store only thexcoordinate of the public key point, omitting theycoordinate and reducing the size of the key and the space required to store it by 256 bits. An almost 50% reduction in size in every transaction adds up to a lot of data saved over time!

但是我們存儲的公鑰其實是在橢圓曲線上的一個點,而這個點的x和y坐標值其實是有公式?jīng)Q定的。所以其實存x的值,然后通過方程算出y的值,其實也是可以的,這樣還能減少50%的存儲空間。

Whereas uncompressed public keys have a prefix of 04, compressed public keys start with either a 02 or a 03 prefix. Let’s look at why there are two possible prefixes: because the left side of the equation isy2, the solution foryis a square root, which can have a positive or negative value. Visually, this means that the resultingycoordinate can be above or below the x-axis. As you can see from the graph of the elliptic curve inAn elliptic curve, the curve is symmetric, meaning it is reflected like a mirror by the x-axis. So,while we can omit theycoordinate we have to store thesignofy(positive or negative); or in other words, we have to remember if it was above or below the x-axis because each of those options represents a different point and a different public key. When calculating the elliptic curve in binary arithmetic on the finite field of prime order p, theycoordinate is either even or odd, which corresponds to the positive/negative sign as explained earlier. Therefore, to distinguish between the two possible values ofy, we store a compressed public key with theprefix 02 if theyis even, and 03 if it is odd,allowing the software to correctly deduce theycoordinate from thexcoordinate and uncompress the public key to the full coordinates of the point. Public key compression is illustrated inPublic key compression.

但是有一個問題,如果你解出方程后,會有兩個y值,一正一負,關于x軸對稱,所以其實在壓縮的時候,就需要有一個字段存儲一下,到底是正值還是負值。在有限域的情況下,y的一正一負對應到的是奇數(shù)和偶數(shù)。(比如你解出了a,那另外一個值就是p-a,兩個的奇偶性正好相反。

Figure 7. Public key compression

Here’s the same public key generated previously, shown as a compressed public key stored in 264 bits (66 hex digits) with the prefix 03 indicating theycoordinate is odd:

This compressed public key corresponds to the same private key, meaning it is generated from the same private key. However,it looks different from the uncompressed public key.More importantly, if we convert this compressed public key to a bitcoin address using the double-hash function (RIPEMD160(SHA256(K)))it will produce adifferentbitcoin address.This can be confusing, because it means that a single?private key can produce a public key expressed in two different formats (compressed and uncompressed) that produce two different bitcoin addresses.However, the private key is identical for both bitcoin addresses.

但是我們能注意到,壓縮版的公鑰與未壓縮版的公鑰長的樣子不同,于是根據(jù)不同的公鑰,依照上文的規(guī)則生成的比特幣地址也是不同的。但是其實這個公鑰又是由一個私鑰生成的。

Compressed public keys are gradually becoming the default across bitcoin clients, which is having a significant impact on reducing the size of transactions and therefore the blockchain. However, not all clients support compressed public keys yet. Newer clients that support compressed public keys have to account for transactions from older clients that do not support compressed public keys. This is especially important when a wallet application is importing private keys from another bitcoin wallet application, because the new wallet needs to scan the blockchain to find transactions corresponding to these imported keys. Which bitcoin addresses should the bitcoin wallet scan for? The bitcoin addresses produced by uncompressed public keys, or the bitcoin addresses produced by compressed public keys? Both are valid bitcoin addresses, and can be signed for by the private key, but they are different addresses!

盡管目前采用壓縮的比特幣地址已經(jīng)成為默認的錢包選擇,這樣可以減少交易的大小。但是當遇到不支持壓縮表示的舊版本的錢包,向新的版本錢包遷移私鑰的時候,新錢包要在區(qū)塊鏈上查找對應私鑰對應的交易,而這就會有一個問題,到底應該用哪個比特幣地址來搜索呢?

To resolve this issue, when private keys are exported from a wallet, the WIF that is used to represent them is implemented differently in newer bitcoin wallets, to indicate thatthese private keys have been used to producecompressedpublic keys and thereforecompressedbitcoin addresses.This allows the importing wallet to distinguish between private keys originating from older or newer wallets and search the blockchain for transactions with bitcoin addresses corresponding to the uncompressed, or the compressed, public keys, respectively. Let’s look at how this works in more detail, in the next section.

解決的辦法就是采用WIF的私鑰數(shù)據(jù)格式,在格式里面表示,這個私鑰用于生成了壓縮版本的公鑰,還是未壓縮版本的公鑰。

Compressed private keys

Ironically, the term "compressed private key" is a misnomer, because when a private key is exported as WIF-compressed it is actually one bytelongerthan an "uncompressed" private key. That is because the private key has an added one-byte suffix (shown as 01 in hex inExample: Same key, different formats), which signifies that the private key is from a newer wallet and should only be used to produce compressed public keys. Private keys are not themselves compressed and cannot be compressed. The term "compressed private key" really means "private key from which only compressed public keys should be derived," whereas "uncompressed private key" really means "private key from which only uncompressed public keys should be derived."You should only refer to the export format as "WIF-compressed" or "WIF" and not refer to the private key itself as "compressed" to avoid further confusion

但是這里有個不一致的命名問題:如果采用WIF壓縮格式存儲私鑰,這個數(shù)據(jù)其實要比WIF未壓縮更長。這里說的壓縮,其實不是私鑰的壓縮,而是告訴你,私鑰算出來的公鑰,用的是壓縮形式。

Example: Same key, different formats?shows the same key, encoded in WIF and WIF-compressed formats.

Table 4. Example: Same key, different formats

Remember, these formats are?not?used interchangeably. In a newer wallet that implements compressed public keys,the private keys will only ever be exported as WIF-compressed (with aKorLprefix).If the wallet is an older implementation and does not use compressed public keys, the private keys?will only ever be exported as WIF (with a 5 prefix).?The goal here is to signal to the wallet importing these private keys whether it must search the blockchain for compressed or uncompressed public keys and addresses.Notice that the hex-compressed private key format has one extra byte at the end (01 in hex). While the Base58 encoding version prefix is the same (0x80) for both WIF and WIF-compressed formats, the addition of one byte on the end of the number causes the first character of the Base58 encoding to change from a 5 to either aKorL. Think of this as the Base58 equivalent of the decimal encoding difference between the number 100 and the number 99. While 100 is one digit longer than 99, it also has a prefix of 1 instead of a prefix of 9. As the length changes, it affects the prefix. In Base58, the prefix 5 changes to aKorLas the length of the number increases by one byte.

這里的私鑰表示是不能互換的。在新的錢包中,導出的私鑰通常會是K或者L作為前綴,代表采用的是壓縮的公鑰表示;而在舊式的錢包中,導出的就是以數(shù)字5作為前綴。

If a bitcoin wallet is able to implement compressed public keys, it will use those in all transactions. The private keys in the wallet will be used to derive the public key points on the curve, which will be compressed. The compressed public keys will be used to produce bitcoin addresses and those will be used in transactions. When exporting private keys from a new wallet that implements compressed public keys, the WIF is modified, with the addition of a one-byte suffix 01 to the private key. The resulting Base58Check-encoded private key is called a "compressed WIF" and starts with the letterKorL, instead of starting with "5" as is the case with WIF-encoded (noncompressed) keys from older wallets.

Tip?"Compressed private keys" is a misnomer! They are not compressed; rather, WIF-compressed signifies that the keys should only be used to derive compressed public keys and their corresponding bitcoin addresses. Ironically, a "WIF-compressed" encoded private key is one byte longer because it has the added 01 suffix to distinguish it from an "uncompressed" one.

Implementing Keys and Addresses in C++

Implementing Keys and Addresses in Python

這兩節(jié)講的是分別采用C++和Python來生成密鑰與地址的案例,主要是代碼運行,所以有興趣的請到原地址閱讀。

https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc#implementing-keys-and-addresses-in-c

Advanced Keys and Addresses

In the following sections we will look at advanced forms of keys and addresses, such as encrypted private keys, script and multisignature addresses, vanity addresses, and paper wallets.

這一節(jié)講的是比特幣高級的密鑰形式,例如私鑰加密、腳本以及多簽名地址。

Encrypted Private Keys (BIP-38)

Private keys must remain secret. The need forconfidentialityof the private keys is a truism that is quite difficult to achieve in practice,because it conflicts with the equally important security objective ofavailability.Keeping the private key private is much harder when you need to store backups of the private key to avoid losing it. A private key stored in a wallet that is encrypted by a password might be secure, but that wallet needs to be backed up. At times, users need to move keys from one wallet to another—to upgrade or replace the wallet software, for example. Private key backups might also be stored on paper (seePaper Wallets) or on external storage media, such as a USB flash drive. But what if the backup itself is stolen or lost? These conflicting security goals led to the introduction of a portable and convenient standard for encrypting private keys in a way that can be understood by many different wallets and bitcoin clients, standardized by BIP-38 (see?[appdxbitcoinimpproposals]).

比特幣的私鑰需要保密,然而保密和可用性是矛盾的。而且為了防止丟失又需要多重備份,但是如果備份丟了,又是麻煩事。針對這些情況,有一個BIP38的標準,來協(xié)調不同的錢包客戶端。

BIP-38 proposes a common standard for encrypting private keys with apassphrase?and encoding them with Base58Check so that they can be stored securely on backup media, transported securely between wallets, or kept in any other conditions where the key might be exposed. The standard for encryption uses the Advanced Encryption Standard (AES), a standard established by the NIST and used broadly in data encryption implementations for commercial and military applications.

BIP35采用的短語編碼的方式,并采用AES加密的方法來保存密碼。

A BIP-38 encryption scheme takes as input a bitcoin private key, usually encoded in the WIF, as a Base58Check string with the prefix of "5." Additionally, the BIP-38 encryption scheme takes a passphrase—a long password—usually composed of several words or a complex string of alphanumeric characters.The result of the BIP-38 encryption scheme is a Base58Check-encoded encrypted private key that begins with the prefix 6P.If you see a key that starts with 6P, it is encrypted and requires a passphrase in order to convert (decrypt) it back into a WIF-formatted private key (prefix 5) that can be used in any wallet. Many wallet applications now recognize BIP-38-encrypted private keys and will prompt the user for a passphrase to decrypt and import the key. Third-party applications, such as the incredibly useful browser-basedBit Address?(Wallet Details tab), can be used to decrypt BIP-38 keys.

BIP38采用短語編碼加密的方式,也就是如果你要使用私鑰,你需要再提供一個短語口令。采用BIP38編碼的數(shù)據(jù)格式,前綴是6P。采用BIP38的方式編碼,可以適用的地方是“冷錢包”,也就是把私鑰打印出來存儲。這樣你只要記住一個“提示語”,就能確保安全性。

The most common use case for BIP-38 encrypted keys is for paper wallets that can be used to back up private keys on a piece of paper. As long as the user selects a strong passphrase,a paper wallet with BIP-38 encrypted private keys is incredibly secure and a great way to create offline bitcoin storage(also known as "cold storage").

Test the encrypted keys in?Example of BIP-38 encrypted private key?using bitaddress.org to see how you can get the decrypted key by entering the passphrase.

Table 5. Example of BIP-38 encrypted private key

As we know, traditional bitcoin addresses begin with the number “1” and are derived from the public key, which is derived from the private key. Although anyone can send bitcoin to a “1” address, that bitcoin can only be spent by presenting the corresponding private key signature and public key hash.Pay-to-Script Hash (P2SH) and Multisig Addresses

Bitcoin addresses that beginwith the number “3” are pay-to-script hash (P2SH) addresses, sometimes erroneously called multisignature or multisig addresses.?They designate the beneficiary of a bitcoin transaction as thehash of a script,instead of the owner of a public key. The feature was introduced in January 2012 with BIP-16 (see[appdxbitcoinimpproposals]), and is being widely adopted because it provides the opportunityto add functionality to the address itself.?Unlike transactions that "send" funds to traditional “1” bitcoin addresses, also known as a pay-to-public-key-hash (P2PKH), funds sent to “3” addresses?require something more than the presentation of one public key hash and one private key signature as proof of ownership.The requirements are designated at the time the address is created, within the script, and all inputs to this address will be encumbered with the same requirements.

傳統(tǒng)的比特幣地址以1打頭,但是也有以3打頭的腳本哈希地址。這些地址是一段腳本的哈希,因為可以給地址增加功能,所以也廣泛采用。在向以3打頭的地址支付的時候,不僅需要公鑰與復分解的簽名。但是生成地址的方式其實和比特幣1打頭的地址是一致的。

A P2SH address is created from a transaction script, which defines who can spend a transaction output (for more details, see?[p2sh]). Encoding a P2SH address involves using the same double-hash function as used during creation of a bitcoin address, only applied on the script instead of the public key:

The resulting "script hash" is encoded with Base58Check with a version prefix of 5, which results in an encoded address starting with a 3. An example of a P2SH address is 3F6i6kwkevjR7AsAd4te2YB2zZyASEm1HM, which can be derived using the Bitcoin Explorer commands script-encode, sha256, ripemd160, and base58check-encode (see?[appdx_bx]) as follows:

Tip?P2SH is not necessarily the same as a multisignature standard transaction. A P2SH address most often represents a multi-signature script, but it might also represent a script encoding other types of transactions.

Multisignature addresses and P2SH

Currently, the most common implementation of the P2SH function is the multi-signature address script. As the name implies, the underlying script requires more than one signature to prove ownership and therefore spend funds. The bitcoin multi-signature feature is designed to require?M signatures (also known as the “threshold”) from a total of N keys, known as an M-of-N multisig, where M is equal to or less than N.For example, Bob the coffee shop owner from[ch01_intro_what_is_bitcoin]could use a multisignature address requiring 1-of-2 signatures from a key belonging to him and a key belonging to his spouse, ensuring either of them could sign to spend a transaction output locked to this address. This would be similar to a “joint account” as implemented in traditional banking where either spouse can spend with a single signature. Or Gopesh, the web designer paid by Bob to create a website, might have a 2-of-3 multisignature address for his business that ensures that no funds can be spent unless at least two of the business partners sign a transaction.

多簽名地址的意思就是,花錢的時候,要不止一個人的私鑰簽名。比如一個m-n簽名機制就是,需要n個人里面至少m個簽名才能生效。這種應用一般是在聯(lián)合賬戶場景下使用。正好上周我和一位做出納的朋友聊天,他手里就管付錢這件事情,操作一家公司的網(wǎng)銀,但是他個人要實現(xiàn)轉錢操作,還需要另外兩個人的核驗才能完成。

We will explore how to create transactions that spend funds from P2SH (and multi-signature) addresses in?[transactions].

Vanity Addresses

Vanity addresses are valid bitcoin addresses that contain human-readable messages. For example, 1LoveBPzzD72PUXLzCkYAtGFYmK5vYNR33 is a valid address that contains the letters forming the word "Love" as the first four Base-58 letters.Vanity addresses require generating and testing billions of candidate private keys, until a bitcoin address with the desired pattern is found.?Although there are some optimizations in the vanity generation algorithm, the process essentially involves picking a private key at random, deriving the public key, deriving the bitcoin address, and checking to see if it matches the desired vanity pattern, repeating billions of times until a match is found.

Vanity在英文中有“虛榮、浮華”的意思,為了顯得好聽一些,我把這個譯成“比特幣靚地址”,仿照“QQ靚號”的用法。靚地址的意思其實是,本來比特幣地址是沒有意義的隨機字符,但是現(xiàn)在如果包含了可讀的信息,比如LOVEU什么的,就會顯得有不同的意義。為了實現(xiàn)這個效果,就要測試不同的私鑰,直到試出來想要的結果。

Once a vanity address matching the desired pattern is found, the private key from which it was derived can be used by the owner to spend bitcoin in exactly the same way as any other address.Vanity addresses are no less or more secure than any other address.?They depend on the same Elliptic Curve Cryptography (ECC) and SHA as any other address. You can no more easily find the private key of an address starting with a vanity pattern than you can any other address.

一旦找到了這樣的靚地址,就可以和其他地址一樣正常使用。從安全性上,和其他普通類型,并沒有太大的差別。

In?[ch01_intro_what_is_bitcoin], we introduced Eugenia, a children’s charity director operating in the Philippines. Let’s say that Eugenia is organizing a bitcoin fundraising drive and wants to use a vanity bitcoin address to publicize the fundraising. Eugenia will create a vanity address that starts with "1Kids" to promote the children’s charity fundraiser. Let’s see how this vanity address will be created and what it means for the security of Eugenia’s charity.

下面舉了一個利用比特幣募集給孩子的基金的例子,于是募集者希望有一個帶有?1Kids的地址。

Generating vanity addresses

It’s important to realize that a bitcoin address is simply a number represented by symbols in the Base58 alphabet.The search for a pattern like "1Kids" can be seen as searching for an address in the range from 1Kids11111111111111111111111111111 to 1Kidszzzzzzzzzzzzzzzzzzzzzzzzzzzzz.?There are approximately 5829?(approximately 1.4 * 1051) addresses in that range, all starting with "1Kids."?The range of vanity addresses starting with "1Kids"?shows the range of addresses that have the prefix 1Kids.

注意,比特幣的地址本質上就是由數(shù)加密出來的,想要有1Kids打頭的地址,本質就是要從1Kids111…111到1Kidszzz…zzz的搜索空間內,找到一個私鑰,使生成的地址在這個空間里。

Table 6. The range of vanity addresses starting with "1Kids"

Let’s look at the pattern "1Kids" as a number and see how frequently we might find this pattern in a bitcoin address (see?The frequency of a vanity pattern (1KidsCharity) and average search time on a desktop PC). An average desktop computer PC, without any specialized hardware, can search approximately 100,000 keys per second.

如果以平均的計算能力為例,下表展示了平均多少個私鑰中,會出現(xiàn)一個符合要求的地址。

Table 7. The frequency of a vanity pattern (1KidsCharity) and average search time on a desktop PC

As you can see, Eugenia won’t be creating the vanity address "1KidsCharity" anytime soon, even if she had access to several thousand computers.?Each additional character increases the difficulty by a factor of 58.?Patterns with more than seven characters are usually found by specialized hardware, such as custom-built desktops with multiple GPUs. These are often repurposed bitcoin mining "rigs" that are no longer profitable for bitcoin mining but can be used to find vanity addresses. Vanity searches on GPU systems are many orders of magnitude faster than on a general-purpose CPU.

從這里可以看到,每增加一位的地址,就需要多乘以58,所以這是以指數(shù)的復雜級數(shù)倍增的。這其實也是另外一種形式的挖礦,所以用GPU也是可以加速的。目前有人專門做給錢幫你找靚地址的生意,給錢就可以,而且快。

Another way to find a vanity address is to outsource the work to a pool of vanity miners, such as the pool at?Vanity Pool. A pool is a service that allows those with GPU hardware to earn bitcoin searching for vanity addresses for others. For a small payment (0.01 bitcoin or approximately $5 at the time of this writing), Eugenia can outsource the search for a seven-character pattern vanity address and get results in a few hours instead of having to run a CPU search for months.

Generating a vanity address is a brute-force exercise: try a random key, check the resulting address to see if it matches the desired pattern, repeat until successful.?Vanity address miner?shows an example of a "vanity miner," a program designed to find vanity addresses, written in C++. The example uses the libbitcoin library, which we introduced in?[alt_libraries].

下面作者放了一個運行示例,考慮篇幅,請到鏈接上看原版的代碼。

https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc#generating-vanity-addresses

Vanity address security

Vanity addresses can be used to enhanceandto defeat security measures;they are truly a double-edged sword. Used to improve security, a distinctive address makes it harder for adversaries to substitute their own address and fool your customers into paying them instead of you. Unfortunately, vanity addresses also make it possible for anyone to create an address thatresemblesany random address,or even another vanity address, thereby fooling your customers.

靚地址其實是一把雙刃劍,既可以增加安全,也可以削弱。因為地址前幾位是可讀的,所以攻擊者就很難把你的地址替換成其他人的地址,因為可讀從而有意義,容易辨認;但是問題也來自于可讀,如果攻擊者也生成一個前幾位和某個地址一致的地址,不管是否可讀,這樣就很容易冒充了。

Eugenia could advertise a randomly generated address (e.g., 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy) to which people can send their donations. Or, she could generate a vanity address that starts with 1Kids, to make it more distinctive.

In both cases,?one of the risks of using a single fixed address (rather than a separate dynamic address per donor) is that a thief might be able to infiltrate your website and replace it with his own address, thereby diverting donations to himself. If you have advertised your donation address in a number of different places, your users may visually inspect the address before making a payment to ensure it is the same one they saw on your website, on your email, and on your flyer. In the case of a random address like 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy, the average user will perhaps inspect the first few characters "1J7mdg" and be satisfied that the address matches. Using a vanity address generator, someone with the intent to stealby substituting a similar-looking address can quickly generate addresses that match the first few characters,?as shown inGenerating vanity addresses to match a random address.

但是另外一個問題在于,如果你在募捐的時候,對外公布了你的收款地址,萬一出現(xiàn)有人把你的地址替換成對方自己的地址,而且因為地址是隨機的,人們往往只會看前幾位長得很像就確認了,這樣就會帶來風險。以下的表格就是,根據(jù)一個原地址,仿照出來的非常相像的地址。

Table 8. Generating vanity addresses to match a random address

以地址1Kids33q44erFfpeXrmDSz7zEqG2FesZEN為例,假如一般人看到1Kids33,就會感覺地址是正確的,所以攻擊者要算出一個高仿的冒充地址,需要比原有的位長多算3364?次(58 × 58)。如果我們把靚地址做到8位長,那要高仿就得算到10位,那這樣對于正常的使用者來說,代價可以承受,但是對于攻擊者的代價就很高昂,這是比較合適的。也就是要找到一個難度,使得我們可以承受這個難度的1倍,但是攻擊者卻無法承受這個難度的3364倍。

So does a vanity address increase security? If Eugenia generates the vanity address 1Kids33q44erFfpeXrmDSz7zEqG2FesZEN, users are likely to look at the vanity pattern wordand a few characters beyond, for example noticing the "1Kids33" part of the address. That would force an attacker to generate a vanity address matching at least six characters (two more), expending an effort that is 3,364 times (58 × 58) higher than the effort Eugenia expended for her 4-character vanity. Essentially, the effort Eugenia expends (or pays a vanity pool for)"pushes" the attacker into having to produce a longer pattern vanity.?If Eugenia pays a pool to generate an 8-character vanity address, the attacker would be pushed into the realm of 10 characters, which is infeasible on a personal computer and expensive even with a custom vanity-mining rig or vanity pool.What is affordable for Eugenia becomes unaffordable for the attacker, especially if the potential reward of fraud is not high enough to cover the cost of the vanity address generation.

Paper Wallets

Paper wallets are bitcoin private keys printed on paper.Often the paper wallet also includes the corresponding bitcoin address for convenience, but this is not necessary because it can be derived from the private key. Paper wallets are a very effective way to create backups or offline bitcoin storage, also known as?"cold storage."As a backup mechanism, a paper wallet can provide security against the loss of key due to a computer mishap such as a hard-drive failure, theft, or accidental deletion. As a "cold storage" mechanism, if the paper wallet keys are generated offline and never stored on a computer system, they are much more secure against hackers, keyloggers, and other online computer threats.

紙錢包,就是把比特幣的私鑰印在紙上。有時候紙上也會印公鑰對應的比特幣地址,但是鑒于公鑰可以根據(jù)私鑰計算出來,所以只存私鑰也是可以的。把私鑰存儲在紙上,作為冷存儲,也可以防止黑客的攻擊,以及其他在線的威脅。

Paper wallets come in many shapes, sizes, and designs, but at a very basic level are just a key and an address printed on paper.?Simplest form of a paper wallet—a printout of the bitcoin address and private key?shows the simplest form of a paper wallet.

Table 9. Simplest form of a paper wallet—a printout of the bitcoin address and private key

Paper wallets can be generated easily using a tool such as the client-side JavaScript generator atbitaddress.org. This page contains all the code necessary to generate keys and paper wallets,even while completely disconnected from the internet.To use it, save the HTML page on your local drive or on an external USB flash drive. Disconnect from the internet and open the file in a browser. Even better, boot your computer using a pristine operating system, such as a CD-ROM bootable Linux OS. Any keys generated with this tool while offline can be printed on a local printer over a USB cable (not wirelessly), thereby creating paper wallets whose keys exist only on the paper and have never been stored on any online system.?Put these paper wallets in a fireproof safe and "send" bitcoin to their bitcoin address, to implement a simple yet highly effective "cold storage" solution.?An example of a simple paper wallet from bitaddress.org?shows a paper wallet generated from the bitaddress.org site.

把地址和需要打印在一張紙上,然后確保這個過程沒有任何數(shù)據(jù)連接在線。將這些紙錢包,保存在防火的保險箱中,這樣可以實現(xiàn)一個簡單但是高效的冷存儲解決方案。

Figure 8. An example of a simple paper wallet from bitaddress.org

但是這樣做仍然有一個風險,就是一旦有人獲得了這張紙,通過拍照或者其他的方式就可以獲取私鑰,從而把錢轉移。所以,一個升級的方法就是采用BIP-38協(xié)議,對比特幣私鑰進行加密。如果需要前面還需要輸入一個短語口令,于是只要記住這個短語口令,密碼也不會失竊。

The disadvantage of a simple paper wallet system is that the printed keys are vulnerable to theft.?A thief who is able to gain access to the paper can either steal it or photograph the keys and take control of the bitcoin locked with those keys.?A more sophisticated paper wallet storage system uses BIP-38 encrypted private keys.?The keys printed on the paper wallet are protected by a passphrase that the owner has memorized. Without the passphrase, the encrypted keys are useless. Yet, they still are superior to a passphrase-protected wallet because the keys have never been online and must be physically retrieved from a safe or other physically secured storage.An example of an encrypted paper wallet from bitaddress.org. The passphrase is "test."?shows a paper wallet with an encrypted private key (BIP-38) created on the bitaddress.org site.

Figure 9. An example of an encrypted paper wallet from bitaddress.org. The passphrase is "test."

Warning?????Although you can deposit funds into a paper wallet several times, you should withdraw all funds only once, spending everything. This is because in the process of unlocking and spending funds some walletsmight generate a change address if you spend less than the whole amount.?Additionally, if the computer you use to sign the transaction is compromised, you risk exposing the private key. By spending the entire balance of a paper wallet only once, you reduce the risk of key compromise. If you need only a small amount, send any remaining funds to a new paper wallet in the same transaction.


注意你可以向一個錢包里多次轉錢,但是如果要取錢或者花錢的話,最好一次全部取出。如果你花的錢比這個地址上的少的話,有的錢包會生成零錢地址。如果錢包所在計算機或者設備被入侵,安全性受到威脅,花剩下的錢,私鑰有可能泄露。如果你沒有花完一張冷錢包上所有的錢,就在花錢的時候,同時把剩余的錢,轉到一個新的紙錢包。

Paper wallets come in many designs and sizes, with many different features.Some are intended to be given as gifts and have seasonal themes, such as Christmas and New Year’s themes.?Others are designed for storage in a bank vault or safe with the private key hidden in some way, either with opaque scratch-off stickers, or folded and sealed with tamper-proof adhesive foil. Figures#paper_wallet_bpw?through?#paper_wallet_spw?show various examples of paper wallets with security and backup features.

當你把比特幣的私鑰印在紙錢包,就可以做不同主題的設計,比如說喜迎圣誕節(jié)或者新年主題的賀卡形式。這就和咱們日常生活中的傳統(tǒng)的充值卡很像,所以它也可以成為一個,行賄受賄的好工具。如果比特幣以后真的使用廣泛,紀委監(jiān)察委就肯定要出手了。

Figure 10. An example of a paper wallet from bitcoinpaperwallet.com with the private key on a folding flap

Figure 11. The bitcoinpaperwallet.com paper wallet with the private key concealed

Other designs feature additional copies of the key and address, in the form of detachable stubs similar to ticket stubs, allowing you to store multiple copies to protect against fire, flood, or other natural disasters.

Figure 12. An example of a paper wallet with additional copies of the keys on a backup "stub"

?

關于比特幣錢包地址,公鑰私鑰這部分就結束了,感謝你的閱讀,給你自己午飯加個蛋吧。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容