《精通比特币》英文版批注导读•第4章(2)比特币地址 — ScalersTalk成长会 – 持续行动,刻意学习 – ScalersTalk Wonderland

《精通比特币》英文版批注导读•第4章(2)比特币地址

学术研究 scalerstalk 浏览 0条评论

今天我们进入《精通比特币》第四章第二部分。这部分把钱包地址什么的,基本上讲透了。

 

本章原文地址

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, but rather 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 the owner 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), specifically SHA256 and RIPEMD160.

比特币地址根据公钥,通过单向哈希函数生成,采用的算法是SHA256 RIPEMD160。具体的过程是,先做SHA256运算,再把结果做RIPEMD160运算,最后生成一个20字节的字符串。

 

Starting with the public key K, 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}\]

where K is the public key and A is 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.

注意:比特币地址并不是比特币的公钥,是由公钥通过单向函数转换而来。比特币的地址采用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.

采用不同进制的编码的目的,是为了更加紧凑的表示数。比如十进制,就会用0-9表示10个数,十六进制就会用0-F表示16个数,BASE64编码用的是52个英文大小写、10个数字以及+/来代表64个数。BASE58主要用在加密货币中,和BASE64原理差不多,就是剔除了一些长得很像的字母,比如数字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个字节作为校验码,附在编码的最后。于是编码就分成了三部分,前缀、数据以及校验和。

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 in Base58Check 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 in Example: 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 either compressed or uncompressed public 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 the x coordinate of the point, the other for the ycoordinate. The prefix 04 is used to distinguish uncompressed public keys from compressed public keys that begin with a 02 or a 03.

公钥有两种表示方式,压缩版和未压缩版。压缩版的前缀是04,后面有两个256位的数字分别代表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.

大部分交易需要包含公钥,用于验证有效性。一枚公钥需要占据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 know the x coordinate we can calculate the y coordinate by solving the equation y2 mod p = (x3 + 7) mod p. That allows us to store only the xcoordinate of the public key point, omitting the y coordinate 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!

但是我们存储的公钥其实是在椭圆曲线上的一个点,而这个点的xy坐标值其实是有公式决定的。所以其实存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 is y2, the solution for y is a square root, which can have a positive or negative value. Visually, this means that the resulting y coordinate can be above or below the x-axis. As you can see from the graph of the elliptic curve in An elliptic curve, the curve is symmetric, meaning it is reflected like a mirror by the x-axis. So, while we can omit the y coordinate we have to store the sign of y (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, the ycoordinate is either even or odd, which corresponds to the positive/negative sign as explained earlier. Therefore, to distinguish between the two possible values of y, we store a compressed public key with the prefix 02 if the y is even, and 03 if it is odd, allowing the software to correctly deduce the y coordinate from the x coordinate and uncompress the public key to the full coordinates of the point. Public key compression is illustrated in Public key compression.

但是有一个问题,如果你解出方程后,会有两个y值,一正一负,关于x轴对称,所以其实在压缩的时候,就需要有一个字段存储一下,到底是正值还是负值。在有限域的情况下,y的一正一负对应到的是奇数和偶数。(比如你解出了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 the y coordinate 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 a different bitcoin address. This can be confusing, because it means that a single private key can produce a public key expressed in two different formats (compressed and uncompressed) that produce two different bitcoin addresses. However, the private key is identical for both bitcoin addresses.

但是我们能注意到,压缩版的公钥与未压缩版的公钥长的样子不同,于是根据不同的公钥,依照上文的规则生成的比特币地址也是不同的。但是其实这个公钥又是由一个私钥生成的。

Compressed public keys are gradually becoming the default across bitcoin clients, which is having a significant impact on reducing the size of transactions and therefore the blockchain. However, not all clients support compressed public keys yet. Newer clients that support compressed public keys have to account for transactions from older clients 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!

尽管目前采用压缩的比特币地址已经成为默认的钱包选择,这样可以减少交易的大小。但是当遇到不支持压缩表示的旧版本的钱包,向新的版本钱包迁移私钥的时候,新钱包要在区块链上查找对应私钥对应的交易,而这就会有一个问题,到底应该用哪个比特币地址来搜索呢?

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 that these private keys have been used to produce compressed public keys and therefore compressed bitcoin addresses. This allows the importing wallet to distinguish between private keys originating from older or newer wallets and search the blockchain for transactions with bitcoin addresses corresponding to the uncompressed, or the compressed, public keys, respectively. Let’s look at how this works in more detail, in the next section.

解决的办法就是采用WIF的私钥数据格式,在格式里面表示,这个私钥用于生成了压缩版本的公钥,还是未压缩版本的公钥。

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 byte longer than an “uncompressed” private key. That is because the private key has an added one-byte suffix (shown as 01 in hex in Example: 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压缩格式存储私钥,这个数据其实要比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 a K or L prefix). 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 a K or L. 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 a K or L as the length of the number increases by one byte.

这里的私钥表示是不能互换的。在新的钱包中,导出的私钥通常会是K或者L作为前缀,代表采用的是压缩的公钥表示;而在旧式的钱包中,导出的就是以数字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 letter K or L, 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

 

这两节讲的是分别采用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.

这一节讲的是比特币高级的密钥形式,例如私钥加密、脚本以及多签名地址。

Encrypted Private Keys (BIP-38)

Private keys must remain secret. The need for confidentiality of the private keys is a truism that is quite difficult to achieve in practice, because it conflicts with the equally important security objective of availabilityKeeping 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 (see Paper 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的标准,来协调不同的钱包客户端。

BIP-38 proposes a common standard for encrypting private keys with a passphrase 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-based Bit Address (Wallet Details tab), can be used to decrypt BIP-38 keys.

BIP38采用短语编码加密的方式,也就是如果你要使用私钥,你需要再提供一个短语口令。采用BIP38编码的数据格式,前缀是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 begin with 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 the hash 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 opportunity to 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.

传统的比特币地址以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个签名才能生效。这种应用一般是在联合账户场景下使用。正好上周我和一位做出纳的朋友聊天,他手里就管付钱这件事情,操作一家公司的网银,但是他个人要实现转钱操作,还需要另外两个人的核验才能完成。

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靓号”的用法。靓地址的意思其实是,本来比特币地址是没有意义的随机字符,但是现在如果包含了可读的信息,比如LOVEU什么的,就会显得有不同的意义。为了实现这个效果,就要测试不同的私钥,直到试出来想要的结果。

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.

注意,比特币的地址本质上就是由数加密出来的,想要有1Kids打头的地址,本质就是要从1Kids111…1111Kidszzz…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.

如果以平均的计算能力为例,下表展示了平均多少个私钥中,会出现一个符合要求的地址。

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,所以这是以指数的复杂级数倍增的。这其实也是另外一种形式的挖矿,所以用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 enhance and to 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 that resembles any 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 steal by substituting a similar-looking address can quickly generate addresses that match the first few characters, as shown in Generating vanity addresses to match a random address.

但是另外一个问题在于,如果你在募捐的时候,对外公布了你的收款地址,万一出现有人把你的地址替换成对方自己的地址,而且因为地址是随机的,人们往往只会看前几位长得很像就确认了,这样就会带来风险。以下的表格就是,根据一个原地址,仿照出来的非常相像的地址。

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 word and 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.

纸钱包,就是把比特币的私钥印在纸上。有时候纸上也会印公钥对应的比特币地址,但是鉴于公钥可以根据私钥计算出来,所以只存私钥也是可以的。把私钥存储在纸上,作为冷存储,也可以防止黑客的攻击,以及其他在线的威胁。

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 at bitaddress.org. This page contains all the code necessary to generate keys and paper wallets, even while completely disconnected from the internet. To use it, save the HTML page on your local drive or on an external USB flash drive. Disconnect from the internet and open the file in a browser. Even better, boot your computer using a pristine operating system, such as a 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.

把地址和需要打印在一张纸上,然后确保这个过程没有任何数据连接在线。将这些纸钱包,保存在防火的保险箱中,这样可以实现一个简单但是高效的冷存储解决方案。

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

 

但是这样做仍然有一个风险,就是一旦有人获得了这张纸,通过拍照或者其他的方式就可以获取私钥,从而把钱转移。所以,一个升级的方法就是采用BIP-38协议,对比特币私钥进行加密。如果需要前面还需要输入一个短语口令,于是只要记住这个短语口令,密码也不会失窃。

 

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 wallets might 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.

当你把比特币的私钥印在纸钱包,就可以做不同主题的设计,比如说喜迎圣诞节或者新年主题的贺卡形式。这就和咱们日常生活中的传统的充值卡很像,所以它也可以成为一个,行贿受贿的好工具。如果比特币以后真的使用广泛,纪委监察委就肯定要出手了。

 

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”

 

关于比特币钱包地址,公钥私钥这部分就结束了,感谢你的阅读,给你自己午饭加个蛋吧。

 

欢迎大家关注我的新微信公众号,“刻意学习区块链”,我会把我所有关于区块链和比特币学习解析的文章,汇总在上面便于检索,这是ScalersTalk成长持续论的一个分叉。 搜索“刻意学习区块链”或者长按扫二维码关注。 

  • 用苹果手机,一竿子打赏给S私人红包

ScalersTalk成长持续论

    ★★★★★   

ScalersTalk成长会是由Scalers发起的社群生态体系,专注1000天以上的“N阶持续行动理论体系与能力构建”,以“从英语初阶到同声传译全栈解决方案”为特色,以“持续输入输出训练实践拓宽认知边界”为导向。

 

微信公众号  l  ScalersTalk成长持续论

新 浪 微 博   l  @Scalers

网           站  l   ScalersTalk.com

开 放 社 群   l  100小时训练QQ群C 456036104

畅 销 书 籍  l 《刻意学习》火热销售中

 ★★★★★ 

2018年成长会申请说明

《持续行动,为三年后的自己,扎心地做点事——ScalersTalk成长会2018年会员资格开放申请(2017.12)》(请点击)

本文原文:http://www.scalerstalk.com/1321-MasterBTC04