0 65 min 1 week

  Chapter 1 Overview of Cryptography and Cryptocurrency

  Legal currency, similar to the control of the central bank’s institutions over the supply of currency + anti-counterfeiting identification on the physical currency. However, it can still be forged.

  Security measures need to be taken and confusion prevented for encrypted lottery and How to find it.

  The difference between the two lies in: the security rules of the latter need to be completely implemented through technical means, while the former relies on a central authority.

  This chapter mainly introduces hash algorithms (Hash) and digital signature (digital signature) technology in cryptography. Both are very critical for building an encrypted lottery system and how to find it. The following chapters introduce: zero-knowledge proof.

  1.1 Cryptographic hash function

  Hash function

  A hash function is a mathematical function with the following three characteristics:

  ① The input can be any size of string

  ② It produces output of a fixed size. This chapter assumes an output size of 256 bits.

  ③ It can perform effective calculations, that is, for a specific input string, the output of the hash function can be calculated within a reasonable time. The complexity of calculating the hash value for a string of n bits is O(n).

  Hash table

  Data structures created based on hash functions.

  For hash functions focused on encryption, to achieve cryptographic security, the hash function must meet the following conditions:

  ① Collision-resistance

  ② Hiding

  ③ Puzzle-friendliness

  Characteristic 1: Collision Resistance

  Collision☞: For two different inputs, the same output is produced.

  For the hash function H(·), if no collision can be found (this does not mean that collisions do not exist), then the function is said to have collision resistance.

  Note: Through counting arguments, it can be proven that collisions do exist. The input space of hash functions is infinite (including all strings of any length), and the output space is finite (only containing strings of a specific fixed length), so there must be input strings mapped to the same output strings. In fact, according to the pigeonhole principle, it is certain that a large number of possible inputs will be mapped to any specific output. For encrypted hash functions, some methods can guarantee finding collisions.

  The birthday paradox is that collisions can be found just by testing the square root of the number of possible outputs.

  Advantage: This collision detection algorithm is effective for each hash function.

  Disadvantage: The calculation takes a very long time.

  However: we have proven that there is no hash function in the world that has collision resistance. The encrypted hash functions we rely on in practice are merely functions that have not yet been found to have collisions, and we temporarily choose to believe these with hash resistance. For example, the MD5 hash function has found collisions and has been gradually phased out.

  Application: Part of information summary

  Based on the premise: if the hash function H has collision resistance, and x, y are two different inputs, then it can be assumed that the output is different.

  This argument can use the hash output as an information summary.

  For example: Alice uploaded a large file, how can she be sure that the file she downloaded is the same as the file she uploaded later.

  ⅰ The entire file is locally stored, and then compared. It is麻烦 and uploading is meaningless.

  ⅱ Collision-free hash functions solve this problem. Alice only needs to remember the original file hash value, and after downloading the file, calculate the hash value of the downloaded file and compare it. If they are the same, then.

  Here: the hash function generates a fixed-length summary or summary of information.online casino victoryJoin us

  Feature 2: Confidentiality

  Confidentiality guarantee: if only the hash function y=H(x) is known, there is no feasible way to calculate the input value x.

  To achieve confidentiality: the value of x needs to come from a very broad set. Avoid being reverse solved.

  Confidentiality hash function H has confidentiality. If: when the input r is selected from a high-order minimum entropy probability distribution, it is impossible to determine x under the condition of H(r||x). (The double vertical bars || represent a connection symbol, indicating the connection of a series of events or things)

  In information theory, the minimum entropy is a means of predicting the results of user tests. High-order minimum entropy describes the degree of dispersion of the distribution in a more intuitive way.

  Application: Commitment

  What one wants to do is called a commitment.

  The commitment here is a digital process: select a number, put it in an envelope, place it on a table visible to everyone, which then indicates that you have made a commitment to the number in the envelope. It is secret to others before opening the envelope, and after opening it, to display the committed value.

  Commitment protocol: A commitment protocol scheme consists of two algorithms.

  ①The commitment function takes information and a temporary random number as input, and the output is a commitment.

  ②The verification function takes a commitment output, a temporary random number, and information as input. Comparison.

  It requires two security features: confidentiality and constraint.

  The specific introduction is on page 10 of the book.

  How to execute commitment scheme through encrypted hash function: generate a temporary random number of 256 bits, etc. For details, see the book.

  Characteristic 3 Puzzle-friendly

  Puzzle-friendly: If for any n-bit output value y, assuming k is selected from the high-order minimum entropy distribution, if it is impossible to find a feasible method to find x in much less than 2^n time, ensuring that H(k||x) = y is established, then we call the hash function H puzzle-friendly.

  Application: search puzzle

  Search puzzle composition:

  A hash function H.

  A value selected from the high-order minimum entropy distribution, id (referred to as puzzle ID)

  Target set Y.

  The solution to this puzzle is a solution x that satisfies the following formula:

  Secure Hash Algorithm

  Secure Hash Algorithm 256, abbreviated as SHA-256

  SHA-256 is mainly adopted in the Bitcoin world.

  It is required that the hash function can accept input of arbitrary length. As long as we establish a hash function for fixed length input, through general methods, we can convert a hash function that accepts fixed length input into a hash function that can accept arbitrary length input. This process is called MD transformation. SHA-256 is one of the commonly used hash functions that adopt this transformation method.

  Compression function: In general terms, this basic type, which can be used for fixed length and has collision resistance, is called a compression function.

  It has been verified that if the basic compression function has the property of collision resistance, then the hash function generated by the transformation also has collision resistance.

  MD transformation

  The compression function takes an input value of length m and produces an output value of a shorter length n. The input of the hash function (which can be of any size) is divided into blocks of length m-n.

  MD transformation process: Bring each block and the output of the previous block together into the compression function, and the output length becomes equal to the input length of the compression function. For the first block, an initial vector needs to be selected. This number will be used again each time the hash function is called, and it can be found directly in the standard document in practice. The output of the last block is the returned result.

  SHA-256 uses a compression function to compress a 768-bit input into a 256-bit output, with each block size being 256 bits.

  SHA-256工作原理

  SHA-256工作原理

  To be continued. May 21, 2018, 22:50

  Next. May 22, 2018, 7:17

  Hash function modeling

  It is a fact that it is extremely difficult to determine a series of hash function properties to achieve full provable security, and this book mainly selects three important properties of the hash function usage in Bitcoin and other encrypted lottery and How to find it. Even within this range, not all of these properties are necessary for each use of the hash function.

  1.2 Hash pointer and data structure

  Hash pointer hash pointer: A data structure. It is a pointer that points to the storage location of the data and the hash value of its position.

  Comparison between hash and normal pointers: Normal pointers can only tell where the data is stored, while hash pointers can tell where the data is stored + give you a way to verify that the data has not been tampered with.

  哈希指针

  哈希指针

  1.2.1 Blockchain

  Blockchain block chain: Construct a linked list data structure through hash pointers.

  Normal linked list: A series of blocks, each block a has both data and a pointer to the previous block.

  In blockchain, the pointer to the previous block is replaced with a hash pointer (therefore, each block can tell where the value of the previous block is + the summary of the value = verify that the value has not changed)

  区块链

  区块链

  Application: Anti-tampering Log

  Establish a log data structure that can append data to the end of the log. If you want to tamper with the data at the beginning of the log, it can be detected.

  Analysis as follows:

  If the opponent wants to tamper with the data in the middle of the blockchain, the purpose is to make it undetectable for someone who only remembers the hash pointer at the head of the blockchain.

  ① The opponent will change the data of a certain block k, so the hash value of block k+1 (i.e., the hash value of the entire block k) will not match. (Because hash functions have collision resistance, it can be determined that the new hash value will not match the changed content)

  Result: Inconsistency between the new data in block k and the hash pointer of block k+1 can be detected.

  ② The opponent continues to try to cover this tampering by tampering with the hash value of the next block.

  Result: This strategy fails when reaching the head of the linked list. (That is, as long as the hash pointer at the head of the linked list is stored in a place where the opponent cannot change it, any tampering with any block by the opponent will be detected.)

  防篡改日志

  防篡改日志

  In short, for an opponent to tamper with any data in the blockchain, in order to ensure consistency, they must tamper with all the hash pointers all the way back to the beginning. However, they ultimately fail because they cannot tamper with the pointer at the head of the linked list. Just by remembering one hash pointer, you can basically remember the anti-tampering hash value of the entire linked list. Therefore, a blockchain network containing many blocks can be established.

  Genesis Block: The hash pointer at the head of the linked list

  1.2.3 Merkle Tree

  Merkle trees: Binary trees using hash pointers.

  Data Structure:

  ① All data blocks are regrouped in pairs, and the pointers to these data blocks are stored in the parent nodes of the previous level.

  ② These parent nodes are regrouped in pairs, and the pointers to the parent nodes are stored in the parent nodes of the previous level.

  ③ Continue to repeat.

  ④ Finally, reach the root node of the tree.

  梅克尔树

  梅克尔树

  Like blockchain, by remembering the topmost hash pointer, any attempt to tamper with any data can be detected.

  Application: Membership Proof

  Another feature of Merkle trees: they can achieve concise membership proofs. (This is different from blockchain.)

  Principle: To prove that a data block comes from a Merkle tree, it is only necessary to find the path from the data block to the root node.

  Details can be found on page 18 of the book.

  梅克尔树隶属证明内容

  梅克尔树隶属证明内容

  Non-subordinate proof:

  With the sorted Merkle tree, it is possible to verify that a certain data block is not from the Merkle tree under a logarithmic complexity condition.

  Proof that a specific block does not belong to the Merkle tree is to show the path of the blocks before and after the verified block.

  ① If the two blocks before and after are consecutive in the tree, then the verified block is not subordinate to the Merkle tree.

  ② Between two entries, it belongs to the Merkle tree.

  Summary: Hash pointers can be used in any pointer-based data structure as long as the data structure does not have a cycle. (If there is a cycle, it will not be possible to match all hash values because there is no root node to trace back)

  1.3 Digital Signature

  Digital signatures digital signatures are considered to be a digital simulation of paper handwritten signatures. Two characteristics are required:

  ① You can make your own signature, but anyone who sees it can verify its validity.

  ② It is hoped that the signature will only be associated with a specific file, so the signature cannot be used to indicate agreement or support for another different file.

  (For handwritten signatures, this ensures that others cannot tear your signature from one document and paste it at the end of another document)

  Digital signature scheme: where generateKeys and sign can use random algorithms.

  We require two valid properties: that is, valid signatures can be verified and signatures cannot be forged.

  Verification of the first property: After I sign a message with my private key sk, someone uses my public key pk to verify the signature about the same message, and the signature must be proven to be correct.

  Verification of the second property: Non-forgability – requires that it is computationally impossible to forge a signature. Non-forgability game: Both the opponent and the challenger play together. If the opponent can sign a message that has not been seen before, the opponent wins. Otherwise, the challenger wins. Prove that this digital signature scheme is non-forgable.

  Considerations in practice

  The conversion of algorithm concepts into executable digital signature mechanisms in reality requires consideration of many issues.

  i Many signature algorithms are random, so a good source of randomness is needed.

  ii Information size.

  The solution is to sign the hash value of the information, using an encrypted hash function with an output of 256 bits, and taking the hash value of the information as the message digest. Since the hash function has collision resistance, this method is secure. There is also another method that can sign the hash pointer.

  1.3.1 Elliptic Curve Digital Signature Algorithm

  Elliptic Curve Digital Signature Algorithm ECDSA: The digital signature scheme used by Bitcoin. (ECDSA is the U.S. government standard, an upgraded version of the DSA electronic signature algorithm that utilizes elliptic curves)

  Note: Bitcoin uses the ECDSA algorithm, not the standard elliptic curve ‘secp 256k1’.

  Introduction to related parameters:

  Personal private key: 256 bits.

  Public key (uncompressed): 512 bits.

  Public key (compressed): 257 bits.

  Information to be signed: 256 bits.

  Signature: 512 bits.

  Note: Although ECDSA can only sign 256-bit information, in fact, the information is always hashed before signing. Therefore, any size of information can be effectively signed.

  Using ECDSA, it is crucial to ensure a good source of randomness. Poor sources can lead to the leakage of key information. But ECDSA is peculiar, that is, if you only use poor randomness when generating the signature, and the key you use is perfect, your personal key may still be leaked. (This is the peculiar feature of DSA, not specific to elliptic curves).

  If the personal key is leaked, the opponent can forge your signature.

  Cryptocurrency is cryptography

  Bitcoin does not use any cryptography because there is no need for encryption. Many technologies (such as commitment schemes) to some extent hide information, but this is different from cryptography.

  1.4 Public key as identity

  Extract a public verification key from the digital signature scheme and equate it to the identity of an individual or a system participant. If the signature of a message is correctly verified by the public key pk, it can be considered that pk is expressing this message. From this perspective, the public key is identity, and someone must know the corresponding private key sk to speak for the pk identity.

  Result: new identities can be created at any time.

  In practice, you may use the hash of the public key (pk) as your identity (because the public key is large). When verifying, two points are needed: (1) your identity is indeed the hash of pk (2) the information can be verified by the public key pk.

  Decentralized identity management

  The system of public and private keys helps us introduce the concept of decentralized identity management. If you want a new identity, you can generate one randomly, and generate as many as you want. In fact, this is how Bitcoin treats identity. These identities are called addresses in Bitcoin language, and addresses are actually the hash of the public key.

  Note: In the Bitcoin system, you do not need to explicitly register or reveal your real name, but your behavior pattern itself may be identifiable.

  1.5 Two simple cryptocurrencies

  From cryptography to cryptocurrency.

  1.5.1 GoofyCoin

  GoofyCoin: the simplest cryptocurrency that comes to mind. It has only two rules: that Goofy can create new coins at any time, and that these newly created coins belong to him.

  Details can be found on page 27 of the book.

  高飞币交易

  高飞币交易

  Summary: The rules of GoofyCoin are

  ① Goofy can sign a statement to indicate that he creates a new coin using a unique currency number.

  ② The owner of a coin can sign a statement to indicate ‘transfer this coin to X’ (where X is the public key), transferring it to another person.

  ③ Anyone can verify the validity of a coin, follow the hash pointer to trace it back to its creation by Goofy, and verify all signatures in the process.

  The隐患 is: double spending. In fact, double spending is one of the main problems that any cryptocurrency needs to solve, but GoofyCoin has not solved this problem, so it is not secure and is not suitable as a cryptocurrency.

  1.5.2 ScroogeCoin

  The problem of double spending involves the ScroogeCoin cryptocurrency.

  财奴币是以高飞币为基础创建的,但在数据结构方面更复杂。

  第一个概念:

  一个叫财奴的指定实体将负责公布包含所有发生过的交易历史记录的仅增账目(保证了写入这个账目的任何数据都会永久保留下来)。

  若项目真的仅增,则通过要求所有的交易在被接受前都写入项目,便可预防双重支付。

  如何执行这个仅增功能?财奴创建一个区块链(形成一系列数据块,每个数据块中都包含一次交易,实践中优化的做法就是把多次交易放在同一个区块中,比如比特币,每个区块包含交易的ID和内容+上一个区块的哈希指针),进行数字签名(针对最后一个哈希指针),最后将签名和区块链一起发布。

  财奴币系统中的区块链

  财奴币系统中的区块链

  哪种交易作数?只有在财奴签名的区块链的交易财算数。

  为什么财奴签署每个区块还需一个带哈希指针的区块链?保证仅增特性。财奴可能会试图增加或移除交易记录。

  财奴币中有两种交易。

  第一种:造币CreateCoins

  基于高飞创造新币的程序,将其扩展即可在一次交易中创建多个币量。(造币交易创造了多个不同个数量和归属于不同拥有者的新货币,称为Online casino and How to find it ID即指该次交易中交易ID和货币序号的组合)详情参见书30页。

  第二种:付币PayCoins

  消耗币,创建具有相同总值的新币,新币可能属于不同的人(公钥),交易必须由一个支付该币的人来进行签署。满足以下四个条件,付币交易有效:

  ⑴被消耗的币为有效货币,即在之前交易中创建的

  ⑵被消耗的币在之前交易没被消耗掉,即不是双重支出

  ⑶本次交易产生的币值=消耗的币值量,即只有财奴才可以创建新币。

  ⑷本次交易被消耗的所有币均有其所有者的有效签署。

  注意:直至发布之前,即使满足前三条件,仍然可能是一个被双重支付抢占的交易。

  财奴币核心问题

  工作原理是:人们可以看见哪些币是有效的。防止双重支付。

  问题是:中心化。

  写于2018.5.22 12:53

  第二章 比特币如何做到去中心化

  本章目的是让你对去中心化由一个通盘的认识,以及对比特币运作机制有所了解,最终知道为什么比特币确实是安全的。

  2.1 中心化与去中心化

  互联网就是一个著名的去中心化系统。早期是在AOL记忆ComputerServe(美国最大的在线信息服务机构之一)等围墙花园式信息服务体系的竞争中,逐渐变得越来越风行。

  Email is essentially also a decentralized system of a simple mail transfer protocol SMTP.

  Centralization and decentralization are not incompatible; no system is completely centralized or completely decentralized. Although the Bitcoin system is decentralized, Bitcoin exchanges (a platform that can convert Bitcoin into other currencies), wallet software, and software for managing Bitcoin by users can be decentralized or not.

  How does Bitcoin achieve decentralization?

  Question 1: Who is maintaining the transaction ledger?

  Question 2: Who has the right to approve which transactions are legitimate and valid?

  Question 3: Who is minting new Bitcoin?

  Question 4: Who is making system change rules?

  Question 5: How does Bitcoin gain transaction value?

  2.2 Distributed consensus

  Consensus: consensus

  Distributed consensus: distributed consensus

  Bitcoin is a peer-to-peer system.

  Distributed consensus protocol: In a system with n nodes, each node has an input value, and some nodes may be faulty or even malicious. A distributed consensus protocol has the following two properties:

  ①The termination of the input value must be determined by all honest nodes

  ②This input value must be generated by the city node

  Example: When Alice pays Bob, Alice needs to broadcast to the entire Bitcoin peer-to-peer network.

  广播交易

  广播交易

  Note: Bob may not be in the above network when Alice broadcasts, but whether Bob runs a node does not affect him receiving the Bitcoin transferred to him by Alice.

  What kind of consensus does a node need to reach in the Bitcoin network?

  ⑴In the Bitcoin system, at any point in time, all nodes on the peer-to-peer network have a total ledger containing a series of blocks, with each block containing a list of transactions that have been agreed upon by all nodes.

  ⑵However, each node also has a pile of transactions that have not been packaged into a block (the network node has been notified, the transaction has occurred, but it has not been written into a block). The network node has not reached a consensus on these transactions, so each node has a slightly different, pending confirmation transaction pool. In practice, the peer-to-peer network is imperfect, so some nodes have heard of transactions while others have not.

  How do all nodes reach a consensus on a block?

  Details can be found on page 41 of the book.

  Several technical issues related to reaching a consensus:

  ⑴Reaching a consensus is generally a difficult task, with some nodes crashing or being malicious nodes.

  ⑵For Bitcoin, the peer-to-peer network is imperfect, and not all corresponding nodes are connected in pairs. Poor internet links may cause network problems, and it seems unrealistic to execute a consensus protocol involving all nodes.

  ⑶Since transaction information is distributed throughout the entire internet, there will be significant delays in information transmission.

  Delay and global time

  When the Bitcoin protocol reaches a consensus, it must confront two major obstacles:

  ①It is an imperfect network, such as information delay and node failure

  ②It is some nodes that deliberately cause disturbances.

  One consequence of severe network latency is that nodes do not have a unified global time concept. Not all nodes can reach a consensus on transaction time based on the timestamp of each transaction.

  2.2.1 Impossibility conclusions

  The lack of unity in global time brings many limitations to consensus protocol algorithms.

  A typical case is the Byzantine Generals Problem (Byzantine Generals Problem):

  Constantinople was the capital of the Eastern Roman Empire. Its army was divided into multiple divisions, each led by a general. These generals communicated through messengers to reach a common combat plan. Some generals may be traitors who want to deliberately disrupt this process, which would cause loyal generals to also be unable to reach a unified combat plan.

  How to solve this problem?

  In fact, it is to allow loyal generals to reach a unified combat plan even under the possibility of betrayal and misinformation. However, it has been proven that if the number of traitors exceeds 1/3, this problem will be insurmountable.

  Fisher-Lynch-Paterson impossibility result points out: Under certain conditions (including nodes having deterministic characteristics), even in a process with only one defect, achieving consensus is impossible. (This is a conclusion about impossibility)

  Paxos algorithm protocol: ① The Paxos algorithm can ensure that no inconsistent results are produced. However, its compromise is that under certain conditions (although not common), the protocol may become stuck, thereby unable to continue running. (This is a consensus protocol mentioned in some literature)

  2.2.2 Breaking traditional assumptions

  Impossibility conclusions are only valid under certain conditions, and the conclusions are for the research of distributed databases. But for Bitcoin, it has broken many assumptions made by traditional distributed databases. Currently, the actual performance of Bitcoin in consensus is much better than the theoretical situation.

  What classic models has Bitcoin broken and what assumptions have been made?

  ⑴ Bitcoin introduces the concept of rewards. Rewards are a new concept for distributed consensus protocols, so it can be said that Bitcoin only solves the problem of distributed consensus under a specific monetary system.

  ⑵ The Bitcoin system includes the concept of randomness. The consensus algorithm of Bitcoin relies heavily on randomness. Bitcoin does not focus on specifying the starting and ending points of consensus, and consensus is achieved over a relatively long period of time.

  2.3 Using the blockchain to achieve consensus without identity

  Different from traditional distributed consensus algorithms, each node in Bitcoin does not have a stable, long-term identity.

  Reasons for the lack of identity:

  ① Peer-to-peer network, without the phenomenon of Sybil attack (where nodes are伪造 nodes)

  ② Pseudonymity. (Bitcoin still cannot guarantee true anonymity, and the characteristics of Bitcoin do not compel the use of a real identity to join)

  For the convenience of security, a real identity would make the design easier. However, it is not. But it can be supplemented by a theoretical assumption.

  2.3.1 Implicit Consensus

  The assumption of arbitrary node selection makes implicit consensus possible.

  The consensus protocol has multiple rounds, each round corresponding to a block in the blockchain. In each round, a random node is selected, which can propose the next block of the chain.

  Without a consensus algorithm, to avoid the randomness of selecting a malicious node, the隐性共识 method is selected: other nodes implicitly accept or reject the randomly selected node. If accepted, continue to extend the chain after this block; if rejected, ignore the new block and continue the chain with the previously accepted block.

  Which block does the node choose to continue the chain? Simplified version of the Bitcoin consensus algorithm

  Assuming you can arbitrarily choose a node, these nodes will not be affected by the Sybil attack.

  ① New transactions are broadcast to all nodes

  ② Each node will put new transactions into the block

  ③ In each round, a random node can broadcast its block

  ④ Other nodes can choose to accept this block, provided that all the transactions in the block are legitimate, that is, they have real signatures

  ⑤ Nodes can put the hash values of the above blocks into their own blocks to indicate their recognition of the new block.

  Verify the effectiveness of this consensus algorithm

  Alice cannot steal Bitcoin from an address belonging to another user that is not under her control. Because if the digital signature mechanism is secure, Alice cannot forge the signature of the Bitcoin owner.

  Denial of Service Attack Alice dislikes Bob, refusing to provide services to Bob. Although Bob’s transaction has not been included in the next block proposed by Alice, it only needs to wait until the next honest node initiates a block for his transaction record to be included in this block.

  The double-spending attack assumes that Alice is a customer of Bob’s online store and has a block initiated by an honest node that includes a transaction representing Alice paying Bobentry method lottery entry methodClick to enter. (This transaction is a data structure containing Alice’s digital signature + the instruction to pay Bob’s public key (address) + a hash value)

  Note: This hash value is a pointer to the output of a previous transaction, which is the origin of Bitcoin.

  For details, see page 48, which is rather complex.

  双重支付攻击

  双重支付攻击

  Whether the double-spending attack is successful depends on which block is included in the long-term consensus chain.

  What determines which block is included? Honest nodes follow the longest valid branch extension rule, extending after which branch? There is no clear answer. (Both branches have the same length, the difference lies in the last block, but both blocks are valid, so the choice determines whether the double-spending attack is successful) Technically speaking, the two transactions are completely consistent and valid.

  In practice, the method of using the earliest heard block in the peer-to-peer network as a starting point still has problems, such as network latency, and the one heard first may not be the earliest created. If the chain containing the Alice-Bob transaction block is completely forgotten by the network, it becomes an orphan block.

  From Bob’s perspective, when Bobby allows Alice to download the software after a hasty check and allows Alice to download the software online when Alice broadcasts the transaction, this is called a zero-confirmation transaction. The result will be worse. To protect yourself from double-spending attacks, you should wait longer.

  Bob角度看待双重支付

  Bob角度看待双重支付

  Summary: The more confirmations a transaction receives, the greater the probability of being incorporated into the long-term consensus chain. Because honest nodes always choose to extend the longest consensus chain. It has been proven that the probability of a double-spending attack decreases exponentially with the number of confirmations. In the Bitcoin ecosystem, it is common to wait for 6 confirmations. The prevention of improper transactions is completely based on cryptographic methods, strengthened by consensus, and the prevention of double-spending attacks relies entirely on consensus, as cryptography plays no role, because consensus can determine which is put into the long-term consensus chain.

  Distinguish between two types of hash pointers

  A hash pointer in the block used to indicate which block it follows.

  One or more pointers in the transaction that point to the hash of the previous transaction to indicate the source of the Bitcoin.

  2.4 Reward Mechanism and Proof of Work

  Reward nodes that behave honestly with currency units.

  2.4.1 Reward One: Block Rewards

  Bitcoin has two different reward mechanisms: block rewards and transaction fees.

  According to the rules of Bitcoin, the node that creates a block can add a special transaction to this block (this transaction is a coin creation transaction similar to the coin creation in the Scrooge Coin, the node can specify the receiving address of this transaction, usually choosing an address owned by themselves, which can be regarded as the reward for the node’s service of creating blocks on the consensus chain).

  When writing this book, the block reward amount was set at 25 bitcoins. The amount will be halved every 210,000 blocks generated. The final number is 21 million, and it will be exhausted around 2140. However, the system can still run because block rewards are just one of the Bitcoin reward mechanisms.

  Note: Rewards will only be realized when the blockchain is finally incorporated into the long-term consensus chain. This is the only way new bitcoins are allowed to be created.

  2.4.1 Reward Two: Transaction Fees

  The second reward mechanism of Bitcoin.

  Any transaction creator can choose to make the output value of the transaction smaller than the input value. The first person to create a block and put transactions into the blockchain can take this difference as a transaction fee.

  If you are a node and are creating a block containing 200 transactions, then the transaction fees of these 200 transactions will be paid to the address you put in the block.

  2.4.2 Mining and Proof of Work

  There is still one problem unanswered when describing the consensus mechanism.

  ⑴ We want you to believe in this assumption: we can randomly select a node

  ⑵ The new problem caused by rewarding those nodes: if everyone gets a share of a node to obtain these rewards, the system will become unstable

  ⑶ Based on the second question, there may be attackers who create a large number of witch nodes to try to overthrow the entire consensus process.

  Solution: Proof of Work (PoW): change the random selection of nodes to select nodes based on the proportion of resources owned by nodes, hoping that such resources are not monopolizable. For example, if this resource is computing power, it is called Proof of Stake (PoS).

  Although Bitcoin does not use it, Proof of Stake is also another qualified model, used by other cryptocurrencies.

  Proof of Work: Allows nodes to compete with each other using their computing power, and the proportion of computing power determines the probability of the node being automatically selected.sports betting plan and The latest entrance

  To be continued 2018.5.22 19:53 Running away, will continue after coming back

  Continue to update 2018.5.23 21:50

  Bitcoin uses the hash function puzzle to prove the amount of work.

  Continue to update 2018.5.24 9:11

  Any node that proposes to create a block and wants to create the next one must find a temporary random number. The temporary random number needs to meet:

  A block usually contains:

  ① A series of transactions proposed by the node.

  ② A hash pointer to the previous block. (This pointer is just a string in the text, and this hash value is used as the ID to request other nodes on the network to find the block, so that after obtaining this block, it can be verified).

  ③ A temporary random number. (To increase the difficulty of finding a temporary random number that meets the requirements, the hash value of the entire block containing the temporary random number is combined together, and the output is a specific form. If the hash function has the puzzle-friendly characteristic, the only solution is to try a sufficient number of temporary random numbers until success)

  The Bitcoin system completely realizes a decentralized approach: the method of solving the hash function puzzle and the proof of work, which can completely abandon the method of randomly selecting nodes. These nodes compete independently in the process of solving the hash function puzzle, and if a node finds a temporary random number that meets the requirements, it can propose to create the next block.

  2.4.3 Hash Puzzle Characteristics: Difficult to Calculate

  The hash puzzle has three important characteristics: difficult to calculate, parameterizable cost, and easy to verify.

  Characteristics one: there should be a certain level of difficulty. In fact, the difficulty actually changes over time.

  Note: the process of continuously trying to solve the hash puzzle, i.e., Bitcoin mining, the nodes participating in mining are called miners. Technically, everyone can be called a miner, but the high cost of mining leads to the mining ecosystem consuming a large amount of energy.

  2.4.3 Hash Puzzle Characteristics: Parameterizable Cost

  Characteristics two: the cost of hope can be changed by parameters, not a fixed value.

  In the peer-to-peer network of Bitcoin: after every 2016 blocks are generated, all nodes will automatically recalculate the proportion of the target area relative to the entire output range, so that the time interval for generating subsequent blocks is approximately 10 minutes. (If the interval between block generation is too short, it will cause many inefficiencies, leading to the loss of many optimization benefits, so the interval is a fixed value, although the ideal interval is still not unified.)

  Note: the probability that any miner finds the next block is the proportion of the computing power they control to the global computing power.

  Summary: as long as the majority of miners with computing power as the weight follow the Bitcoin protocol (honest), it is impossible for a large number of attacks to occur in Bitcoin.

  Two behavioral patterns of miners: game theory believes that the biggest problem is whether the default behavior of miners is a ‘Nash equilibrium’ (Nash equilibrium).

  Bernoulli trial: solving the hash puzzle is probabilistic, by trying temporary random numbers one by one. There are only two results, and under continuous trials, the probability of each result occurring is fixed.

  Poisson process: the Bernoulli trial of a node repeatedly trying temporary random numbers is a discrete probability process, which can be approximated by the continuous probability process of the Poisson process.

  发现下一个区块所需时间的概率密度函数

  发现下一个区块所需时间的概率密度函数

  2.4.3 Hash puzzle characteristics: easy to verify

  The third characteristic: it is easy to verify that a node correctly calculates the proof of work. Any node or miner can quickly verify that the block found by other miners meets the requirements of the proof of work.

  Chapter summary:

  Mining cost: how to calculate whether mining is profitable.

  Complexity analysis:

  ①The hardware investment is fixed, electricity costs change over time.

  ②The reward miners receive depends on the speed of discovering blocks = the hardware’s ability + the proportion of computing power to the global computing power.

  ③The cost of mining is usually in US dollars and other currencies, involving the Bitcoin exchange rate.lottery local and Where is it

  ④Assuming miners honestly comply with the protocol, but miners can also adopt other strategies.

  There is no ‘1 Bitcoin’

  Bitcoin does not have a fixed face value, there is no ‘1 Bitcoin’ said, Bitcoin is a transaction output, currently can be accurate to 8 decimal places, the minimum possible value is 0.000 000 01 BTC, known as a satoshi.

  A transaction is placed into the blockchain

  A transaction is placed into the blockchain, indicating that this transaction has been confirmed many times (the number of times is not fixed, 6 is a common number, the more confirmations, the easier it is to confirm). However, there are often orphan blocks (the cause may be that this block may contain an illegal transaction or an attempt at double spending or network latency) or blocks that have not entered the consensus chain.

  Hash puzzle and mining

  Miners are a special type of node that determines the competition to create new blocks. If other miners continue to build on their blocks, the reward for their efforts is the newly created Bitcoin (new block reward) + the existing Bitcoin (transaction fees).

  Bitcoin deeply utilizes the concept of distributed consensus.

  In traditional terms, there is a consensus process to determine the exchange rate of currency.

  In Bitcoin, the blockchain completes the consensus on the ledger situation, that is, how much Bitcoin you own depends on the consensus. The Bitcoin peer-to-peer network, the total amount of Bitcoin owned by all addresses recorded in the blockchain. Owning Bitcoin is the consensus of other nodes that a given party owns these Bitcoin.

  There are two ways to change Bitcoin rules: soft fork and hard fork.

  Launch cryptocurrency

  Self-starting process bootstrapping

  There are three ideas in the Bitcoin system: the security of the blockchain, the health of the mining ecosystem, and the value of the currency interacting with each other.

  51% attack

  If the consensus fails and there is a 51% attacker who actually controls the majority of mining power in the Bitcoin network.

  Can attackers steal coins from existing addresses? No, unless there is a method to overthrow the encryption method. There may be a fork in this case.

  Can the 51% attacker suppress other transactions? No, even if successful, everyone knows that an attack has occurred.

  Can attackers change the block reward? No, this is a change to the system rules, and other nodes will not easily recognize the increase in block rewards, so he cannot use these blocks.

  Will attackers destroy everyone’s confidence in Bitcoin? If one party controls 51% of the hash power, even if no attack is launched, everyone may lose confidence in Bitcoin.

  Updated on 2018.5.24 10:37

  Chapter 3 The operating mechanism of Bitcoin

  This chapter introduces how to establish a monetary system and how to reward miners

  3.1 Bitcoin transactions

  The process of Bitcoin transactions is the process of continuously creating blocks.

  Simple ledger mode

  Establishing a system centered on the account, you can create new currency and put it into someone’s account, and then it can be transferred to others.

  基于账户的账簿

  基于账户的账簿

  Disadvantage: anyone who wants to confirm whether a transaction is real must track the balance of every account. Although it is possible to add data fields to update the account balance after the transaction, this increases the workload of bookkeeping.

  与比特币类似的基于交易的账本

  Similar to: PiggyCoin.

  Each transaction has an input value and an output value.

  The input value can be considered as the currency to be consumed (these are the coins created in the previous transaction)

  The output value is considered to be the currency created in this transaction.

  When minting new currency, only new currency is created, and old currency is not consumed. (Only output, no input)

  Each transaction has a unique ID.

  与比特币类似的基于交易的账本

  与比特币类似的基于交易的账本

  Address conversion

  Similar to the PiggyCoin, the currency output in a transaction does not exist in a partial consumption situation, either it is completely consumed in another transaction or none of it is consumed. For example: Alice’s 8 coins in this conversion can be transferred to another address owned by Alice, that is, address conversion.

  Valid verification

  Using hash pointers, for example, to verify the transaction outputs referenced by Alice, you can check from Alice’s referenced transaction to the latest transaction recorded in the ledger (without starting from the very first transaction in the ledger), without needing to add additional data structures.

  Funds consolidation

  Initiate a transaction, with multiple inputs and one output, the output address is the initiator’s address.

  Joint payment

  Initiate a transaction, with multiple inputs and one output, the output address is the recipient’s address, the output address of the ‘previous transaction’ referenced by multiple inputs is different, and multiple signatures are required: for example, the signature of 1 and the signature of 2.

  Transaction syntax

  The data structure transmitted on the Bitcoin network is a string of characters. A Bitcoin transaction is divided into three parts: metadata, a series of inputs, and a series of outputs.

  Metadata Stores some internal processing information: we can use hash pointers to point to ID. Lock time lock_time.

  元数据

  元数据

  Input All inputs are arranged in a sequence, and each input format is the same. The input needs to clearly state a specific output of the previous transaction:

  输入

  输入

  Output All outputs are arranged in a sequence, and the content of each output is divided into two parts:

  Each output must correspond to a specific public key (address), so scriptPubkey is a Bitcoin script (hash value of the public key, set of instructions).

  输出

  输出

  3.2 Bitcoin’s script

  Each transaction output determines a public key and specifies a script.

  Transaction output description: Only with the public key with hash value X and the signature of the owner of this public key can this amount of money be obtained

  Who will execute this script? The transaction input includes the script, and only after the script of the transaction input and the output script of the previous transaction are successfully executed together, can the funds be obtained.

  输入输出脚本范例

  输入输出脚本范例

  Bitcoin script language

  Developed for Bitcoin, called ‘script’ in Bitcoin.

  The Bitcoin script language inherently supports encryption operations, and purposeful instructions are used to calculate hash values and verify signatures.

  The script language is stack-based, and each instruction is executed only once, and it cannot loop linearly.

  Not Turing complete, cannot arbitrarily run powerful function features.

  Note: Turing completeness means that the language has the ability to arbitrarily execute powerful functions.

  Details see page 75.

  The execution of the script has only two results: success or failure.

  部分指令

  部分指令

  Execute a script

  There are two types of instructions: data instructions (push data to the top of the stack) and op-code instructions (starting with OP, using the data at the top of the stack as the input value).

  比特币脚本执行堆栈状态图

  比特币脚本执行堆栈状态图

  In Bitcoin, we only sign the entire transaction.

  Proof of burn

  Proof of burn is used to destroy Bitcoin (to prevent funds from being redeemed). Use

  The hash value paid to the script

  The working mechanism of Bitcoin requires the sender of the coin to explicitly specify a script during the transaction. However, in daily life, it can be very complex. How to solve it? Bitcoin uses: the recipient tells the payer to pay Bitcoin to a script address, the hash value of the script is XX, and when withdrawing, I will provide the script corresponding to the above hash value, and provide data through the script verification. The payer can achieve simple payment through P2SH.

  Note: The P2SH script only performs a hash calculation on the topmost data on the stack, and it will execute special verification when it is checked to be consistent with the given hash value: it will reinterpret the topmost data on the stack as a series of instructions and run it as a script once, while the other data on the stack serves as input values for the script.

  3.3 Application of Bitcoin Script

  Third-party payment transaction

  It is implemented using MULTISIG (multiple signatures). The funds can only be withdrawn after two out of three signatures. However, when disputes arise, a third party will decide whether to complete the payment or cancel the payment.

  Green address

  Green address: green addresses

  Problem description: Alice wants to transfer money to Bob (offline), so Bob cannot confirm whether the transfer is completed by checking the updates on the blockchain. Generally, a transaction needs to be confirmed 6 times, taking about 1 hour, which is not practical for buying and selling things or for being offline.

  Solution: a third-party bank (which may be an exchange or other financial intermediary). The bank guarantees that it will not double spend this bitcoin, which Bob believes. However, this is the guarantee of a bank in the real world, so Bob only needs to believe the bank. But if the bank has a double spending incident, people will not believe it. Now, people believe that over-reliance on ‘banks’ is risky.

  Efficient micro-payments

  Efficient micro-payments

  Example: Alice initiates a MULTISIG transaction, transferring the maximum possible amount to a MULTISIG address. Alice signs once every minute when using the traffic, paying Bob the fee generated in that minute, and transferring the remaining money to herself until the idle state (currently, these transactions are only signed by Alice). After going idle, Alice no longer pays for the traffic, Bob signs on Alice’s last transaction, puts it into the blockchain, and the last transaction will pay Bob all the traffic fees at once, returning the remaining coins to Alice (Alice’s single-signed transactions will not enter the blockchain and will be discarded). These are all ‘double spending’, but under normal operation, Bob will only sign on the last transaction.

  If Bob does not sign on the last transaction, Alice will lose all the bitcoins transferred. The lock time can be used to solve this problem.

  Lock time

  Before the small payment agreement begins, it is necessary to agree on a full refund (but the refund action is locked until the lock time is reached). Once the lock time t is reached, if Bob has not signed on the last transaction, Alice can recover all the bitcoins through a refund. (t is the lock_time: it informs miners that this transaction should not be recorded on the blockchain until t time has passed)

  Smart contracts

  Smart contracts, smart contracts, are different from ordinary contracts that require legal or arbitration institutions to protect their execution, and are contracts that can be enforced by technical means in the Bitcoin system.

  3.4 Bitcoin Blocks

  Organizing a large number of transactions into a block results in a shorter hash chain, greatly improving the efficiency of verifying the blockchain data structure.

  The blockchain combines two hash-based data structures:

  ⑴ It is the hash chain of the block, with each block having a block header that contains a hash pointer pointing to the previous block.

  ⑵ It is a tree-like data structure, storing all transaction hashes in a tree-like structure, which is the Merkle tree. To prove that a transaction is in a certain block, you can search through the path within the tree, and the length of the tree is the number of transactions contained in the block.

  Block header

  The block header also contains information related to the mining puzzle.

  The hash function of the block header must start with a lot of zeros to be valid.

  The block header also contains: a temporary random number that a miner can modify, a timestamp, and a point (used to represent the difficulty of finding this block).

  The block header is the only hash-verified chain in the mining process to verify a block, as long as you check the block header.

  The only transaction data in the block header is the root of the transaction tree ‘mrkl_root’.

  Each Merkle tree on a block contains a coinbase transaction, similar to the coin generation transaction in the satoshi coin. Coinbase transactions create new Bitcoin, characterized by:

  ① There is always only one single input and one single output.

  ② Transactions do not consume the Bitcoin from previous transaction outputs, so there are no pointers pointing to the ‘previous transaction’.

  ③ The output value is currently: a little more than 25 coins = miner’s mining income = the reward of 25 coins + all transaction transaction fees.

  3.5 Bitcoin Network

  The Bitcoin network is a peer-to-peer network, where all nodes are equal, running on the TCP network, with a random topology, with each node connected to other random nodes. If a node has not been heard from for 3 hours, it will gradually be forgotten by other nodes.

  The benefits of joining the network are to maintain the blockchain, and initiate transactions through the flooding flooding algorithm (or known as the gossip protocol).

  Example: Alice transfers money to Bob, the client initiates a transaction, and informs all nodes connected to its client of this transaction. After a node receives a transaction message, it will place the transaction in the transaction pool (transactions in the transaction pool have not yet been packaged into the blockchain), and if the transaction already exists in the transaction pool (searched through the transaction hash), it will not spread it again (ensuring that the flooding protocol will automatically terminate).

  How to verify the new transaction information received by the node? ① Transaction verification (verify that the transaction is valid in the current blockchain, the node will run verification scripts for each preceding transaction output, ensuring that the return values of the scripts are all true) ② Check for double spending ③ Check if this transaction information has already been received by this node ④ The node will only receive and pass transactions on the whitelist of standard scripts.

  Race condition: Network latency can lead to分歧 when there is a double attack, with many nodes having disagreements on which transaction should be included in the blockchain. For Bitcoin, the miner who assembles the next block will break the deadlock (deciding which transaction will ultimately be included in the block).

  Zero-verification transactions and fee replacement strategy replace-by-free

  Zero-verification transactions: Once a transaction is broadcasted on the network, the recipient immediately receives the transaction. This transaction is not used to prevent duplicate payments, as the default behavior of miners is to put the first received transaction into the transaction pool, making zero-verification transactions difficult to duplicate.

  Fee replacement strategy: The default behavior of miners for 13 years has become the fee replacement strategy. When a node encounters conflicting transactions, it will put the transaction with a higher transaction fee into its transaction pool and replace the one with a lower fee.

  Storage space requirements

  A fully valid node must be permanently online to receive all transaction data.

  A fully valid node must maintain the outputs generated by transactions, and the complete list of unspent Bitcoin.

  Lightweight nodes

  Lightweight nodes (neightweight nodes): another type of node other than a fully valid node. Also known as lightweight clients or simple payment verification (SPV).

  The security level of a SPV node is far inferior to that of a full node.

  Details can be found on page 92.

  3.6 Restrictions and optimizations

  The total amount of Bitcoin and the mining reward are likely to never change.

  Regarding the transaction processing capacity of the Bitcoin system, there is a strict regulation on the block size, with each block size limited to 1MB. Each transaction is about 250 bytes, so each block can accommodate up to 4,000 transactions. On average, every 10 minutes, a miner gains the right to record, so only 7 transactions can be processed per second.

  The second restriction is the cryptographic algorithm used by Bitcoin. The signature algorithm used by Bitcoin is ESDSA (a type of elliptic curve digital signature algorithm for secp256k1).

  Revise the protocol

  How to revise the Bitcoin protocol and introduce some new features? We can release a new version, but we cannot assume that all nodes will update to the new version. Protocol revision will produce two types of results: hard fork and soft fork.

  Hard fork: Blocks recognized as valid by nodes running the new protocol will be recognized as invalid by nodes running the old version of the protocol. This causes some blocks contained in the longest blockchain branch to be recognized as invalid blocks by old nodes, so old nodes will consider the other branch as the longest valid blockchain branch and continue to extend until they have a new version. Hard fork causes the original chain to split into 2, and will not merge again, as long as the old nodes do not update the version, they will be permanently excluded from the other chain.

  Soft fork: Add new features to make the existing verification rules more strict. Old nodes will accept all blocks, and new nodes will reject some.

  Now assume that most nodes have updated the new version of the protocol and executed the new rules (old nodes will not execute the new rules, and a sufficient number of new nodes are required to compete for the longest chain). Old nodes may mine some invalid blocks that cannot be verified under the new rules, so old nodes know that the blocks they verify as valid are not accepted by other nodes, and therefore the miners of old nodes will update the protocol. If new nodes extend the branch of old nodes with their blocks, old nodes will also turn to extend this branch.

  For example: P2SH is a classic example of a soft fork. (A valid P2SH transaction can also be verified because it only verifies whether the hash value of this transaction is the same as the hash value of the previous transaction output, without knowing that further verification of the script is also required) Relying on new nodes for verification: the script itself can actually obtain the coins from the previous transaction output.

  Written on May 23, 2018, 17:26

  Chapter 4: How to Store and Use Bitcoin

  To use Bitcoin, you must know: some public information (including content recorded on the blockchain, such as the identification information and value information of the Bitcoin) and some private information (the private key of the Bitcoin holder).

  Public information can be retrieved at any time, but private keys need to be well protected. Storing Bitcoin is actually how to save and manage Bitcoin private keys.

  There are three goals for storing and managing private keys: accessibility, security, and convenience. Different management methods are a balance of these three goals.

  4.1 Simple local storage

  Local devices

  The simplest key management: store Bitcoin on local devices.

  Analysis: Accessibility or security is not very good, spending in daily life is very convenient, but it is very easy to lose or be stolen.

  Bitcoin wallet software

  Locally store Bitcoin, generally choose to use Bitcoin wallet software (an application software that manages Bitcoin and private key information and makes it convenient for users to use). The wallet is an interface that tells you how much Bitcoin is in the wallet.

  Encoding and decoding: Base58 encoding and QR codes

  To use or receive Bitcoin, you need to exchange Bitcoin delivery addresses with the other party. Currently, there are two mainstream ways to encrypt addresses: strings and QR codes.

  ⅰ To assign a string to an address, convert the bytes of the key from binary characters to Base58. Base58 encoding uses a character set containing 58 characters to encode.

  ii A QR code represents a real Bitcoin address, and the wallet application will automatically convert the QR code into bytes representing the Bitcoin address.

  Vanity address

  Convert the address into characters that people can recognize.

  Addresses are all generated through hash calculations of random strings, how to obtain specified ones? You can only keep generating private keys until the private key contains the string you want to appear. Such addresses are called vanity addresses.

  Accelerated generation of vanity addresses. For details, see page 104.

  4.2 Hot storage and cold storage

  Hot storage

  Putting Bitcoin in your personal computer is like putting money in a wallet and carrying it with you. (Very convenient but not safe)

  Cold storage

  Offline, lock Bitcoin in other places. (Relatively safe but inconvenient)

  The hot storage can transfer money to the cold storage at any time. When the cold storage goes online, it can receive blockchain transfer information and handle these Bitcoin at any time.

  How to manage? Privacy and other considerations, use different addresses (addresses with different keys) to receive payments, and use new cold storage addresses when transferring Bitcoin from hot storage to cold storage.

  But if the cold storage is not online, how can such addresses be found?

  The direct method is to let the cold storage generate a batch of addresses at one time and send the address list to the hot storage, which can use these addresses in turn.

  Method one: Hierarchical deterministic wallet

  Use a hierarchical deterministic wallet.

  This method allows the cold storage end to create an unlimited number of addresses, and let the hot storage end know all the addresses through a brief one-time exchange. Use cryptographic techniques. Generate something called address generation information, which can generate a series of addresses. Generate private key generation information. It can generate a series of private keys. In cryptography: For each i, the ith address matches the ith private key.

  Bitcoin’s electronic signature algorithm ECDSA supports hierarchical keys. That is, the cold storage end generates any number of keys, and the hot storage end generates the corresponding addresses.

  分层确定性钱包

  分层确定性钱包

  Note: The cold storage end generates and saves the private key generation information and address generation information, and then transfers the address generation information to the hot storage end all at once. When the hot storage end needs to transfer money to the cold storage end, it generates a new address in order. After the cold storage end goes online, it also generates addresses in order and then collects the received funds from the corresponding addresses until there is no more space for receiving funds. If the cold storage needs to transfer money to the hot storage end, it will generate a private key sequence in order.

  Method two: Brain wallet

  Brain wallet brain walle: Withdraw Bitcoin with just one key.

  Main principle: Use a predictable algorithm to convert a password into a pair of public key/private key.

  However, this is very unsafe. Once your password is guessed, all the private keys in your brain wallet can be stolen. If you forget the password, it’s all over.

  How to set a secure password? Use an automatic program to generate an 80-digit number and convert it to a password. In actual operation, you can use key stretching to slow down the generation speed of the key.

  Paper wallet: Fa san

  Print the key on paper, and lock the paper in a safe. There are two ways to encode public and private keys: QR codes and base58 codes.

  Method four: tamper-resistant hardware

  Use tamper-resistant hardware to store keys or generate keys.

  4.3 Key Storage and Key Sharing

  To be continued 2018.5.24 18:39

  Continue reading 2018.5.25 10:07

  In cryptography: key storage technology can improve both the accessibility and security of the key.

  4.3.1 Method of Key Storage

  The key is divided into N segments, and as long as K segments are obtained, the original key can be restored. If the number of segments obtained is less than K, it is not possible. The key is converted into several child keys.

  Note: It is not advisable to simply split the key into several segments. A segment will reveal key information, and it is not necessary to have all segments to guess the key.

  4.3.1 Key Storage: How to Generate Child Keys

  Method: ① Mark S on the Y-axis (0, S), draw a straight line passing through this point with a random slope.

  ② Pick points on the line as many as needed. ③ Get N child keys, and K=2.

  密钥分存

  密钥分存

  Note: S (original key) is encoded into a large integer, with a random slope. The points on the slope are child keys, S (connecting any two points extended to the intersection with the Y-axis). Therefore, there is only one point, and S cannot be obtained.

  Expansion: We can implement key storage using any K and N (K

  密钥分存数学原理

  Note: If key storage is performed using several points on a curve of freedom, it is necessary to obtain at least the data of some points to restore the original key.

  4.3.2 Threshold Cryptography

  The problem with key storage still exists: after key storage, to sign with the original key, it is necessary to obtain the child keys to restore it to the original key. This process is not secure and may be hacked into and the key stolen.

  Method one to overcome the defect of single-point key storage: threshold signature

  How to solve it? Through cryptography

  Threshold signature technology: child keys are stored on different devices, and the original key is restored in a decentralized manner.

  Threshold signatures split a key into different fragments, which are stored separately. During transaction signing, it is not necessary to restore the original key.

  Multiple signatures are a feature of the Bitcoin script, transferring control of a Bitcoin account to multiple keys to collectively protect the account’s security.

  Threshold signatures and multiple signatures can overcome the defect of single-point key storage.

  Example

  Using an electronic wallet with dual security mechanisms (N=2, K=2), if the two keys are stored separately on the computer and phone, payment can be initiated on the computer (the computer will generate a signature fragment to send to the phone), and the phone will prompt for payment information and wait for your confirmation.

  If confirmed, the phone uses its child key to complete the entire signature and then broadcast it to the blockchain.

  4.3.3 Multi-signature: multisignatures

  Method two to overcome the defect of single-point key storage: Multi-signature

  Multi-signature: By Bitcoin script, the control of a Bitcoin account is given to multiple keys (not key split storage), and these keys are stored at different locations and generate signatures separately.

  4.4 Online wallet and exchange

  4.4.1 Online wallet

  Online wallet information is stored in the cloud and can be accessed via the web or mobile app.

  At the beginning of 2015, popular online wallet services were Coinbase and blockchain.info from Bitcoin base company and blockchain information company.

  Advantage: Convenience.

  Shortcoming: Risk. Due to the storage of keys on the website, although passwords are usually used to protect keys, there is a risk that staff or hackers can steal them if there is a breach.

  4.4.2 Bitcoin exchange

  Traditional bank: Deposit money, and the bank promises to give you money when you withdraw it, and during the deposit period, the bank usually uses the money for investment.

  Bitcoin exchange: Exchanges can handle Bitcoin deposits and promise to return the money (Bitcoin, fiat currency) as requested in the future.

  Note: The exchange only modifies the contract with you, and there is no need to transfer Bitcoin from one address to another on the blockchain. Therefore, before and after the transaction, Bitcoin has not truly moved in the blockchain, only the contract between you and the bank changes.

  Advantage: Transactions combine the Bitcoin economy with the fiat currency economy, allowing for free conversion.

  Shortcoming: Risk.

  Exchanges and banks face the same risks, mainly including three categories.

  Risk one: Run on the bank (people go to the bank to withdraw money at the same time, and the bank does not have enough money)

  Risk two: The bank itself is a Ponzi scheme (borrowing new to repay old)

  Risk three: Hacker intrusion (someone even an employee)

  The collapsed exchanges include Mt. Gox.

  4.4.3 Bank supervision, proof of reserve, proof of liabilities

  Bank supervision: The government supervises banks, requiring banks to have a minimum reserve requirement first and providing protection for banks or savers when necessary.

  Proof of reserve: Bitcoin exchanges or other institutions providing Bitcoin management services can use the cryptographic technology of reserve proof to prove to depositors that they have retained a portion of reserves.

  Continuing update 2018.5.26 9:10

  Proof of liabilities: Use a Merkle tree (a binary tree consisting of hash values) to prove the scale of deposits.

  负债证明

  负债证明

  User verification:

  1) The hash pointer and deposit amount field of the root node of the subtree are consistent with the values broadcasted by the exchange.

  2) Traversing from the root node of the subtree to the leaf node, the hash value of each node is indeed the hash value of the child node it points to.

  3) The customer account information corresponding to each leaf node is correct.

  4) The deposit amount field of each node = the sum of the deposit amounts of its closest child nodes.

  Chapter 5 Bitcoin Miningbitcoin mining

  5.1 Tasks of Bitcoin Miners

  To become a miner, you must join the Bitcoin network and connect to other nodes.

  After establishing a connection, six tasks need to be completed:

  1) Listen to transaction broadcasts (verify that their signatures are legitimate and valid, and that the transaction outputs have not been double-spent).

  2) Maintain the blockchain network and listen for new blocks.

  3) Assemble an alternative block. (Once you have a backup of the latest full blockchain data, you can create your own block).

  4) Find a random number that makes your block valid.

  5) Hope that your block is accepted by the entire network. (Even if you find a block, it cannot be guaranteed that the block will become part of the consensus chain concensus chain).

  6) Profit. If other miners accept your block, you can make a profit. If any transaction in the block has a transaction fee, then all transaction fees are owned by the miner.

  Miners’ tasks can be divided into two categories:

  1) Verify transactions and blocks.

  The foundation on which the Bitcoin network survives and operates, the primary reason why the Bitcoin protocol needs miners.

  2) Compete with other miners to strive to find a block and benefit from it.

  It is not essential for the existence of the Bitcoin network, but it is set up to reward miners for completing the first type of task.

  In summary, the two tasks are necessary conditions for Bitcoin to become a lottery and How to find it (miners must receive rewards to complete these tasks).

  Finding a valid block

  How can you find a random number that makes the block valid?

  The blockchain mainly has two layers of structure based on hash functions: 1) The first layer is on the blockchain, where each block’s header has a pointer to the previous block. 2) The second layer is within each block, including the Merkle tree of all transactions.

  Miners first need to select a series of valid transactions from their transaction pool and compile them into a Merkle tree. (As long as the number of transactions compiled does not exceed the limit of random numbers in each block, the number of transactions that can be compiled is selectable).

  Miners need to assemble a new block after that, making its header (which has a 32-bit random number area) point to the previous block on the blockchain. (You need to try temporary random numbers continuously to find one that makes the hash value of the entire block less than the target value (the target value is a number with zeros at the beginning of a certain number of digits)).

  What should you do if you have tried all 32-bit possible values of the random number and still haven’t found a valid hash value?

  After you have traversed all possible values of the block header random number, you can change the random number in the coinbase (for example, +1, and then change the block header random number again to find it).

  Changing the random number in the coinbase will change the hash values of all transactions on the Merkle tree (changes in coinbase values will be propagated upwards).

  Finally, a pair of temporary random number combinations are found: the header random number and the coinbase random number, which are used to generate a new block that meets the hash value requirements and announce that there is hope to obtain the corresponding block reward.

  Are everyone calculating the same puzzle?

  Each miner will put in different transactions in different orders into the block, so it is unlikely to walk on a completely identical block for calculation.

  Even if two different miners’ blocks contain the same transactions, the hash values of the two blocks are different (in coinbase transactions, miners will write their own addresses to receive new coins), unless the two miners share a public key.

  It is only possible that two miners are in the same mining pool, but they will communicate with each other to ensure that different coinbase temporary random numbers are used to avoid duplicate work.

  Is it difficult to find an effective block? Very difficult. The mining target area requires that the hash value of any effective block must be lower than this value.

  Determining difficulty

  The mining difficulty changes once every 2016 blocks mined (about every 2 weeks).

  The change in difficulty is determined by the mining efficiency of the last 2016 blocks. That is:

  Next difficulty = (Previous difficulty 201610min) / the time taken to produce the last 2016 blocks

  5.2 Hardware Required for Mining

  The core of miner computational difficulty lies in the operation of the SHA-256 hash function. (SHA-256 is a general-purpose cryptographic hash function, and SHA is Secure Hash Algorithm).

  SHA-256

  SHA family?

  In SHA-256, 256 represents 256-bit states and outputs. Technically, SHA-256 is one of the closely related members of the SHA-2 function family, including SHA-512 (with a larger state bit and more security) and SHA-1 (160-bit output, currently considered not very secure).

  SHA-256? It is a 256-bit finite state machine, divided into 8 32-bit fields, which can be optimized to run on 32-bit hardware. (32-bit modular addition, right shift, design ideas come from linear feedback shift registers).

  The following figure shows a round of SHA-256 compression function operation, a complete SHA-256 operation requires 64-bit iterations. See Figure 146.

  What is strange about the Bitcoin mechanism? Under the Bitcoin mechanism, to obtain a hash function for use by other nodes, in fact, it requires two rounds of SHA-256 operations, the reason is unclear.

  CPU mining

  First-generation mining: computation is performed through the CPU on the computer. (Miners with simple knowledge try all temporary random numbers in a linear manner, perform SHA-256 operations in the software, and check the results to confirm whether an effective block has been found).

  GPU mining

  Second-generation mining: mining using graphics cards or graphical processors (GPUs). GPUs have high throughput and high parallel processing capabilities. The parallel design of graphics cards makes them have many arithmetic logic units (ALUs) that can perform SHA-256 operations.

  In 2010, OpenCL was born, which allows GPUs to perform general-purpose languages for non-image processing tasks.

  Disadvantages:

  1) GPUs have a large amount of built-in hardware for graphics processing, which is useless for Bitcoin mining.

  2)GPU没有很好的冷却处理设置。

  3)GPU非常耗电。

  现场可编程门阵列挖矿

  2011年左右,用于现场可编程门列阵Field-Programma Gate Array 简称FPGA)硬件设计语言Verilog,第一次用于比特币挖矿。

  利用FPGA代替GPU进行挖矿。

  工作原理:追求定制硬件的最佳性能同时,用户可现场调试或者修改硬件参数。

  优点:

  1)性能比GPU好,特别是数位操作。sports betting and Latest Address

  2)FPGA易冷却。

  缺点:导致其只存在了几个月,就应运而生ASIC

  1)FPGA挖矿其实更加困难(一直在超频使用),故经常看到各种报错和故障。

  2)优化FPGA的32位加法处理上十分困难(而这个在SHA-256中非常重要)

  3)FPGA难购买。

  专用集成电路技术挖矿

  当今的挖矿市场主要被ASIC所主导,这些IC芯片被设计制造优化,就为了比特币挖矿这唯一目的。

  考虑到矿机运行所需耗费的电力成本以及冷却成本,大多数ASIC矿机都无法靠挖矿赚回成本。

  如今:专业挖矿的天下

  书中引用了Bitfury的挖矿中心图。

  如何建立一个挖矿中心?首先需要具备:气候(气温偏寒,节省冷却费用)、电费、网络接入速度。冷却时比特币挖矿最大的挑战,其挖矿本身的耗电量,用单位面积来算要超过传统的数据中心。

  与挖金矿的相似之处

  比特币挖矿经历了:从CPU到GPU,到FPGA,最后到现在的ASIC。

  5.3 能源消耗和生态环保

  根据热力学里的蓝道尔原理,任何一个不可逆转的计算都会消耗一定的能源,该计算也可被认为是一种信息丢失的过程。原理之处:任何移位运算都会消耗一定量(k Tln 2)的焦耳,k是玻耳兹曼常数,T代表芯片以开尔文为单位的温度)。综上: 每进行一个不可逆的数位运算都会消耗一个最小量的焦耳,能源是永远不会被摧毁的,只会互相转变。