Blockchain Exploration: Comprehensive interpretation of blockchain technology and applications from basics to depth

1. Basic concepts of blockchain

1. Development history

The birth of Bitcoin:

In 2008, a person under the pseudonym Satoshi Nakamoto published the paper "Bitcoin: A Peer-to-Peer Electronic Cash System"

On January 3, 2009, Satoshi Nakamoto developed and ran the Bitcoin client program and conducted the first mining, and obtained The first batch of 50 Bitcoins

Bitcoin is an electronic payment system based on cryptographic principles that does not require third-party intervention.

2. Blockchain definition

Blockchain is a chain data structure that combines data blocks in a chronological manner and is cryptographically guaranteed to be a distributed ledger that cannot be tampered with or forged.

3. Blockchain characteristics

Characteristics of blockchain: open and transparent, traceable and non-tamperable, high system availability, user anonymity
Insert image description here

4. Blockchain classification

In blockchain technology, there are three main types of chains: public chain, consortium chain, and private chain. They differ in many aspects, including access rights, degree of decentralization, and use cases.

Public chain Alliance chain private chain
access permission Open network, anyone can join Only authorized nodes or entities can participate in the network Only a single organization or entity controls
Decentralization Highly decentralized, each node can verify blocks and mine Moderate decentralization, the network is jointly managed by a group of entities Partially decentralized, network control is in a single entity
safety Security and transparency guaranteed through consensus algorithm Rely on the trust relationship established between the parties Security relies on access control and management by network administrators
Example Bitcoin and Ethereum Hyperledger Fabric、R3 Corda Blockchain systems used internally by some enterprises
  • Public chain is a decentralized network open to everyone.
  • Consortium chain is a moderately decentralized network participated by authorized entities.
  • Private blockchain is a network that is fully controlled by a single entity or organization.

The Impossible Triangle of Blockchain: Decentralization, efficiency and security cannot be optimal at the same time, and they need to be compatible and balanced among the three!

According to the impossible triangle principle, it is difficult to achieve the optimal state of these three goals simultaneously in the blockchain system. Improving one aspect often has an impact on others. For example:

  • Increasing decentralization may reduce scalability: More nodes participating in verification may slow down transactions and cause scalability issues.
  • The pursuit of greater efficiency may sacrifice security or decentralization: Increasing throughput may mean a reduction in security or decentralization.

5. Blockchain architecture

Blockchain consists of application layer, contract layer, incentive layer, consensus layer, network layer and data layer;

Application layer: the top-level application

Contract layer: smart contracts and script codes

Incentive layer: digital currency issuance mechanism, etc.

Consensus layer: PoW, PoS consensus mechanism

Network layer: P2P network, verification mechanism

Data layer: transaction data, chain structure, timestamp, Merkle tree, encryption, etc.

2.P2P&cryptography

1.P2P

P2P is Peer-to-Peer, peer-to-peer network. Compared with CS architecture, P2P has the following characteristics:

1. No server

2. Direct communication between any end systems

3. Nodes connect to the Internet in stages

4. The node may change IP

If you use a P2P network, you lose the centralized server, so how do you know where to download files? How to index it?

There are generallythree indexing methods in P2P networks, which respectively correspond to the P2P network architecture:

1.Centralized indexing, in centralized indexing, content and file transfer are distributed, but the content positioning trend is highly concentrated ized.

2.Flooding index, flooding query is a completely distributed architecture, each node performs query on its shared files. Index, and only index the files it shares. If the query hits, the reverse path will be used to return the query node address.

3.Hierarchical coverage network, hierarchical coverage is a method between centralized and flooding queries

2. Cryptozoology

The hash function is a special and important cryptographic algorithm in cryptography. It is a one-way function, and information entropy will be lost during its operation!

A hash function can convert a message of any length into a fixed-length hash value!
Insert image description here

In addition, there are many online hash calculation tools on the Internet, such as:Online hash calculation

An excellent hash function should have the following properties:

1. Can operate on data blocks of any length

2. Can produce fixed-length output

3. Given an input of arbitrary length, the calculation of the output is relatively easy

4. For a given hash value, it is computationally infeasible to find the original data (One-wayness)< /span>

5. For a message and its hash value, it is impossible to find another message to calculate the same hash value (Collision resistance)

Hash functions are commonly used for digital signatures and checking file integrity.

1. Symmetric encryption

Symmetric encryption refers to using the same key for encryption and decryption. The main encryption algorithm codes are DES and AES.

DESThe key length is 64 bits, but the actual effective number of bits is 56 bits, because each eighth bit is used for parity check, and due to its short length, it is easy to It was cracked by brute force and is currently no longer considered safe;

AESThe key length is 128, 192, etc., which is more secure than DES and is currently widely used.

So: While both DES and AES are symmetric encryption algorithms, DES has been superseded by AES due to its shorter key length and vulnerability to brute force attacks. AES has a longer key length and higher security, so it is more common in practical applications and is regarded as a more secure and reliable encryption standard.

2.Asymmetric encryption

Asymmetric encryption is an encryption method that, unlike symmetric encryption, uses a pair of keys for encryption and decryption: a public key and a private key. This encryption method is also called public key encryption.

The sender can encrypt the data using the receiver's public key, and only the receiver with the corresponding private key can decrypt the data.

However, compared with symmetric encryption, asymmetric encryption is slower and less efficient.

Common asymmetric encryption algorithms: RSA, ECC

3.Digital signature

Digital signature is additional data attached to the original information in network communication. It is a comprehensive application mode of hash function and asymmetric encryption.

4. Ring signature

Definition: A ring signature is a variant of a digital signature that allows the signer to remain anonymous. It allows a signer to use their private key to generate a signature among a group of users without revealing the signer's identity.

How it works: In a ring signature, the signer is able to generate a signature without revealing his or her identity. The verifier of the signature only knows that the signature comes from a member of a specific group, but cannot confirm which member of the group.

The signer of a ring signature possesses a set of public keys and the private key of one of the public keys.

Applications: Ring signatures can be used in anonymous voting, privacy-preserving transactions, identity verification and other scenarios, allowing anonymous signatures and verifications.

The main difference between digital signatures and ring signatures is anonymity. Digital signatures are to confirm the authenticity of the message and the identity of the sender, while ring signatures are to ensure the anonymity of the signature, that is, the identity of the signer is not disclosed.

5. Threshold signature
  • Definition: Threshold signature is a multi-party security protocol that allows multiple signers (such as an organization or multiple individuals) to jointly generate a signature without the need to Private keys are stored centrally.

  • How it works: In threshold signatures, the private key is divided into multiple parts, such asn T parts out of the parts can generate valid signatures. This means that any t signers can cooperate to generate a signature, but less than t signers cannot complete the signing process.

  • Advantages: Threshold signatures provide greater security and resiliency because it does not require a single entity to own the entire private key, but instead stores it decentrally, reducing single points of failure and potential risk of attack.

  • Applications: Threshold signatures are usually used in scenarios that require multi-party participation and high security, such as financial transactions, multi-party authorization operations, multi-signature wallets, etc.

  • A digital signature is a signature of data by a single entity using its private key.

  • Threshold signature is a signature signed by multiple entities working together, and only requires the authorization of some entities.

3. Consensus algorithm

1. Consensus Definition

In distributed computing theory: Consensus refers to the agreement on certain data values ​​required during the calculation process

In the blockchain: consensus means that all consensus nodes (participating verification nodes) execute transactions in the same order and write them into the ledger.

We call a system with malicious nodes a Byzantine fault, otherwise it is called a non-Byzantine fault. Correspondingly, a consensus algorithm that can cope with Byzantine faults is called a Byzantine fault-tolerant, otherwise it is a non-Byzantine fault-tolerant.

2. PoW algorithm

PoW (Proof-of-Work, proof of work) is the consensus algorithm used in Bitcoin

The purpose of Bitcoin consensus is to make the ledger of each node consistent.

All nodes compete for accounting rights through workload proof. The first node to provide workload proof broadcasts its own block (bill) to the entire network. After all other nodes verify that it is correct, they will synchronize the block to their own blockchain ( ledger).

Proof of work can be embodied as a difficult problem, but there are three conditions for choosing this difficult problem:

1. The conditions of the problem are relatively complex

2. It is very convenient to verify the calculation results

3. The puzzles about each block are different

3.PoS algorithm

PoS (Proof-of-Stack) Proof of Stake

Although PoW cleverly uses proof of work to successfully prevent witch attacks, the waste of resources caused by PoW cannot be ignored. In this context, PoS emerged as the times require.

PoS believes that the more money people hold, the less likely they are to do evil.

PoS cleverly usesthe age of the currency to measure the probability of obtaining accounting rights. At the same time, once a block is mined, it will The currency age of this node is cleared

Coin age = amount of currency held * holding time

However, PoS still wastes resources and easily forms wealth centers, which is not a healthy system. PoS was used for the first time in Peercoin.

4.DPos algorithm

DPoS (Delegated Proof-of-Stake, Delegated Proof of Stake)

In DPoS, all nodes are divided into accounting nodes and ordinary nodes.

Consensus process:

1. Node applies to become a candidate accounting node

2. All currency-holding nodes participate in voting and select n accounting nodes.

3. n accounting nodes take turns participating in accounting

4. Adjust the accounting nodes after each round of accounting, and eliminate evil nodes and nodes that failed to complete accounting.


Although DPoS avoids the waste of resources caused by mining, the accounting rights are only in the hands of a few nodes, so it has been questioned as violating the original intention of decentralization.

5.VRF

The core of the algorithms of PoW, PoS, and DPoS are to randomly select a node to record and package blocks, and all other nodes verify and accept the blocks.

VRF itself is not a consensus algorithm, it is a random mechanism

The random mechanism must satisfy:

1. Ability to resist witch attacks

2. The random results are unified across the entire network

3. Random results are unpredictable

4. Random results can be verified
Insert image description here

In blockchain, using VRF (Verifiable Random Function) to select block producers usually involves the following process:

  1. Node registration and certification: First, nodes in the network need to register and prove their identity. Typically, nodes need to provide a certain amount of collateral or have a certain number of tokens to participate in this process to show their interest in participating in block production.

  2. Usage of VRF: Once nodes are registered on the network, they can use VRF to generate a random number. This random number is usually the result of a function operation based on the node's private key and some random inputs. This number is considered unpredictable.

  3. Verification process: After a node generates a random number, it will submit the random number to the network, and then other nodes will verify the legality and correctness of the random number. Other nodes can verify the validity of this random number using the VRF's public key and the input required to generate the random number, thereby confirming the legitimacy of the random number generated by this node.

  4. Select the block node: Once the verification is passed, the network can determine which node will be selected as the next block node based on the generated random number. Normally, the conditions for selecting a block node may be related to the random number and the size of a certain interval. For example, select the node with the smallest random number to produce blocks.

By using VRF, the blockchain network can implement a random but verifiable block generation mechanism. This method ensures fairness and attack resistance through random numbers, and other nodes can verify the legitimacy of this random number. VRF is considered an effective and secure way to select block producers while avoiding centralized control.

4. Introduction to Bitcoin

1. Bitcoin Concept

Bitcoin is a digital currency ecosystem built on a series of concepts and technologies.

Bitcoin represents the culmination of decades of research in cryptography and distributed systems

Bitcoin includes four key innovations:
Insert image description here

2. How Bitcoin works

The Bitcoin system consists of users, transactions, and miners.

Bitcoin transaction: Inform the entire network that the holder of this part of Bitcoin has authorized the transfer to a new holder.
Insert image description here
Bitcoin transactions can be divided into the following three categories:

1.General transaction 2.Collection transaction 3.Distribution transaction
Insert image description here

The construction of Bitcoin transactions generally goes through three processes:

1. Get transaction input 2. Create transaction output 3. Broadcast transaction

4. After the transaction is broadcast, it will be transmitted to each node through the Bitcoin P2P network for verification and calculation.

A transaction will only become part of the blockchain after it is packaged into a block by a miner who finds the proof of work.

In addition, it is generally believed that a block is considered irrevocable after more than six confirmations!

The difference between blockchain depth and height:

“Depth” usually refers to the distance of a specific block relative to the most recent block in the blockchain. It represents the block number of a specific block relative to the current latest block. For example, if the height of the latest block is 100 and the height of a particular block is 90, then the depth of that particular block is 10 (the height of the latest block minus the height of that particular block).

Depth can be used to describe the number of confirmations of a transaction or to determine the transaction's position on the blockchain. As a transaction is included in more and more blocks in the blockchain, its depth increases, which usually means that the transaction is confirmed by more and more blocks.

"Height" usually refers to the position or number of a specific block in the blockchain within the overall blockchain. It represents the order or serial number of blocks in the blockchain. For example, the height of the first block (the genesis block) is 0, and with each new block, the height of the blockchain increases by one.

Therefore, the height of the blockchain represents the length of the blockchain, that is, the number of blocks already included in the current blockchain.

Summary: Depth refers to the distance of a specific block relative to the latest block, while height represents the order or number of blocks in the entire blockchain. Depth is used to describe the relative position of a block or transaction in the blockchain, while height represents the absolute position in the blockchain.

5. Bitcoin Core Client

1. Get the hash value of the specified height block

bitcoin-cli getblockhash <index>

2. Get information about the specified block

bitcoin-cli getblock <hash>

3. View core client status information

bitcoin-cli getinfo

4. View the command list

bitcoin-cli help

5. Return transaction information in hexadecimal

bitcoin-cli getrawtransaction <txid>

6. Decode serialized transaction information

bitcoin-cli decoderawtransaction

7. Create a new Bitcoin address

bitcoin-cli getnewaddress

8. Obtain the private key corresponding to the specified address

bitcoin-cli dumpprivkey <address>

9. Obtain the connection information of all peer nodes

bitcoin-cli getpeerinfo

bitcoin-cli getblockhash <index>                                   # 获取指定高度区块的哈希值
bitcoin-cli getblock <hash> [verbosity]                            # 获取指定区块的信息
bitcoin-cli getinfo                                                # 查看核心客户端状态信息
bitcoin-cli help                                                   # 查看命令列表
bitcoin-cli help getblockhash                                      # 查看特定命令说明
bitcoin-cli getrawtransaction <txid>                               # 查看十六进制返回交易信息
bitcoin-cli decoderawtransaction <hexstring>                       # 查看解码后的交易信息
bitcoin-cli getnewaddress                                          # 创建新的比特币地址
bitcoin-cli dumpprivkey address                                    # 获取指定地址对应的私钥
bitcoin-cli getpeerinfo                                            # 列出全部对等节点连接信息

Insert image description here

6.Keys and addresses

1. Public key and private key

The private key is calculated through elliptic curve multiplication to obtain the public key.

The characteristic of elliptic curve multiplication is that it is easy to calculate in one direction, but it cannot be deduced in the opposite direction!

Each Bitcoin account includes a private key and a public key. The private key (k) is a randomly generated number. With private

key, we can use the elliptic curve number to multiply this one-way encryption function to generate a public key (K). With the public key (K),

We can then use a one-way cryptographic hash function to generate the Bitcoin address (A). Private key, public key and Bitcoin address

The relationship between them is shown in the figure below:
Insert image description here

1.Private key

Generating a Bitcoin private key is essentially 1- 2 256 2^{256} 2Randomly select a number between 256

The original private key generation method: you can use coins to randomly generate the private key: toss a coin 256 times, heads will be counted as 1, tails will be counted as 0.

In this way, a 256-bit binary number can be obtained as the Bitcoin private key.

WIF format private key:

WIF (Wallet Import Format) is a standard format for importing private keys between various Bitcoin wallets. A private key in WIF format is an encoding of the original private key to make it easier to manage and transmit private key information.

The main feature of the WIF format private key is that it represents the private key in a format that is easy to recognize and use. Usually it starts with a letter indicating the network of the private key (such as mainnet or testnet), followed by a hash of the private key (Base58 encoded). This format contains not only the private key, but also the checksum and other information, making it easier to identify and convert to a hexadecimal private key.

Using the private key in WIF format allows users to more conveniently import it into a Bitcoin wallet and use it in Bitcoin transactions without exposing the private key.

2.Public key

Bitcoin public keys are generated through cryptographic algorithms

K = k ∗ G K=k*G K=kG

Calculate the public key from the private key. This is an irreversible process. Elliptic curve multiplication is a function called a trap door in cryptography. It is easy to calculate in one direction, but impossible in the opposite direction. calculate. This is the basis for unforgeable and secure digital signatures of Bitcoin ownership.
Insert image description here
Public key format:

Traditional public keys are usually represented by the prefix 04 followed by two 256-bit numbers, one of which is the x coordinate and the other is the y coordinate
Insert image description here
Can we find a way to compress it?

After all, x and y satisfy the elliptic curve relationship, so you only need to store x to calculate the y coordinate, but you also need to retain the sign of y.

Therefore, the compression method came out!

If the y-coordinate is an odd number, the prefix of the compressed public key is 03

If the y coordinate is even, the prefix of the compressed public key is 02

2. Bitcoin address

The public key can be turned into a public key hash after double hashing or Hash160, and the public key hash can be turned into a Bitcoin address after being encoded by Base58check! The specific process is as follows:
Insert image description here
Base64 representation is composed of 26 lowercase letters, 26 uppercase letters, 10 numbers from 0 to 9, and two characters + and /!

Base58 is a subset of Base64, but Base58 discards the substrings in Base64 that are easy to misread and confuse. In short, Base consists of substrings that do not include 0 (zero), O (uppercase O), and l (lowercase letter L). , I (capital letter i) consists of four characters of uppercase and lowercase letters and numbers.

Base58 encoding process:
Insert image description here

3. Advanced Keys and Addresses

Suppose you traveled back in time 10 years ago and purchased a large amount of Bitcoin. How to safely keep the private key and wait for the appreciation in value many years later?

1. You can use a long password to encrypt the WIF-encoded private key, and then store the WIF format private key and the long password in different paper wallets.

2. In addition, multi-signature technology can also be used, which requires the use of multiple private keys for authorization to conduct a transaction.

3. Do not publish the private key on the public network or expose it to an unencrypted environment

7. Bitcoin trading principles

1. Basic concepts

UTXO: output for spending transactions

In fact, there is no concept of balance in the Bitcoin system. In fact, all available UTXO corresponding to a wallet address

Bitcoin actually stores transactions one after another, and in the end there is always only the unspent transaction output, which is UTXO

Transaction types are mainly divided into currency creation transactions and ordinary transactions.
Insert image description here

2. Transaction introduction

Transactions include transaction inputs and transaction outputs

The transaction inputs include: transaction ID (txid), output index (vout), unlocking script (scriptSig) and serialization (sequence)

The transaction output includes multiple outputs, each output corresponding to the transaction amount (value) and the lock script (scriptPubKey)

In addition, the specific transaction structure can be viewed through decoding in the Bitcoin Core client. The steps are as follows:

bitcoin-cli getrawtransaction txid # 查看txid对应的系列化后的原始交易数据
bitcoin-cli decoderawtransaction <origin data> # 即可查看对应的交易数据结构

In addition, the total input minus the total output of a transaction is the transaction fee for each transaction, which is used to compensate Bitcoin Miner for its efforts in ensuring network security and at the same time prevent the proliferation of transactions.

1. Bitcoin Scripting Language

The Bitcoin transaction script language is called script. It is a reverse Polish expression language based on stack execution. It is non-Turing complete. When each transaction is verified, the unlocking script scriptSig in each input and the corresponding output The locking script scriptPubKey is executed together to determine whether the transaction meets the payment conditions.

The unlocking script consists ofsignature and public key, while the locking script mainly includesoperators and public key hash, as shown below:
Insert image description here
The Bitcoin scripting language is non-Turing complete, which prevents the transaction verification mechanism from being used as a vulnerability And take advantage of it!

3. Time lock

Time locks can be divided into relative time locks and absolute time locks, which can be divided into transaction-level and script-level time locks respectively.
Script-level time locks need to be used in conjunction with transaction-level time locks. For example, to use CLTV transaction-level time locks, you need to add Time ClockLockTimeVerify Drop to the lock script in the transaction output. During verification, the nLockTime in the field needs to be greater than the time corresponding to CLTV before it can be used, otherwise the transaction cannot pass verification.
The locking principle of relative time is similar.
Insert image description here

8. Bitcoin Network

1. Network model

1.CS architecture

The end user initiates a request, and the server processes each request.
Insert image description here

2.P2P architecture

Every computer in the same network is a peer of each other, and each node jointly provides network services. There is no special node.

Why does Bitcoin use the P2P model:

1.Simple topology

2. Bitcoin itself is designed as a peer-to-peer digital cash system

3.Node function

Node functions: wallet, mining, saving the complete blockchain, and routing

Wallet: Collect UTXO related to wallet address, calculate balance and construct transactions

Miner: Collect transactions, create block headers and obtain block rewards and transaction fees

Network: Routing function, all nodes have this function, in fact, it verifies and propagates transactions

Blockchain: Save complete blockchain information
Insert image description here

4.Node type

1. Ordinary full node

As long as the complete and latest blockchain data is downloaded, it is a full node

2. Bitcoin Core Full Node

It is the node with the most complete functions, first of all, it is a full node, and it also has wallet and miner functions.

3.SPV node

Also known as light node, it does not have complete blockchain information and needs to request necessary transaction data from the full node. It only has Wallet and Network functions

4. Independent mining node
Mainly mining, collecting transactions, making block headers, and obtaining outgoing rewards and transaction fees
Insert image description here

2. Communication process

We talked about the four node types earlier, so how do new nodes that join the network connect to the Bitcoin network? What conditions are needed?

The communication process is as follows:

1. Discover peer nodes through DNS seed nodes

2. Establish a TCP connection with one of the peer nodes on port 8333 (this port is used by Bitcoin)

3. When establishing a connection, the new node first sends version information (version number, block number, and time) to its peer node

4. After receiving the version information, the peer node checks whether its version information is compatible with the local one. If it is compatible, it will send a verack message to confirm the connection.

5. After the connection is established, the new node will send an Addr message containing its own IP address to its neighbor node. In addition, it can also send a getaddr message to the neighbor to request the return of the IP address list of other peer nodes.
Insert image description here

In addition, every online node must perform two tasks regularly:

1. Recommendation work when new nodes join

2. Send messages regularly and communicate within 90 minutes. The connection will be considered disconnected.

3. Bloom filter

1. Comparison between SPV nodes and full nodes

It should be noted here that SPV nodes will only collect andverify transactions involving their wallet addresses without storing the entire blockchain, so They can verify payments and balances without downloading the entire blockchain.

So how can the SPV node verify the existence and legality of the transaction without complete blockchain information?

When SPV receives a certain transaction information, it will first use the Bloom filter to filter to see if it is an address that it is interested in. If it successfully passes the Bloom filter, it will request the Merkel path from the full node for verification. The legality of a certain transaction. In addition, the use of Bloom filters can also greatly protect the privacy of SPV nodes, without exposing the addresses of interest to the outside world.

Bloom filters are used by an SPV node to filter transactions received from its peer nodes, selecting only the transactions that the SPV node is interested in without exposing the addresses or keys it is interested in.

2. Bloom filter

Bloom Filter is a data structure used to quickly check whether an element belongs to a set. Its design is based on hash functions and bit arrays.

Bloom filters have the following characteristics:

  1. Efficient member checking: can quickly determine whether an element may be in the set, or it must not be in the set.
  2. Low space occupied: uses less space and requires less space than other data structures to store the same number of elements.
  3. Hash function: Bloom filters use multiple hash functions to hash elements and map the results to multiple bits of the bit array.
  4. There is a misjudgment: There is a certain misjudgment rate, that is, elements that do not belong to the set may be mistaken for belonging to the set, but no misjudgment will occur.

Basic operations include insertion and inspection:

  • Insertion (Add): For the element to be inserted, hash it multiple times and mark the corresponding bit array position as 1.
  • Check: For the element to be checked, hash it the same number of times and check whether all corresponding bit array positions are 1. If any position is not 1, the element must not be in the set; if all positions are 1, the element may be in the set (there may be a misjudgment).

Common applications of Bloom filters include network caching, spell checking, preventing duplicate submissions, etc., where the tolerance for false positives is a factor that needs to be weighed.

9. Block and chain

1. Basic concepts

A block is a container data structure that aggregates transaction information included in the blockchain.

A block consists of a block header and a block body. The block header is only 80 Byte, and the size of the block body is uncertain. It mainly records transaction information, and the size of each block does not exceed 1MB.

The block header includes version protocol, previous block hash value, timestamp, difficulty target, Merkle tree root, random number, etc.

1. Block identifier

The block identifier mainly includes the block header hash value and block height.

The block hash value can uniquely and clearly identify a block, and any node can calculate the hash by simply hashing the block header can obtain the hash value of the block. In addition, it should be noted that the block header hash value is not included in the data structure of this block, but is usually stored as metadata in an index database table for quick retrieval.

Block height: Identified by the position of the block in the blockchain.

While a single block will always have a clear, fixed block height, the reverse is not true and a block height does not always identify a single block.

Think about it here, the block hash value can uniquely identify a block, so can the block height uniquely identify a block?

Haha, of course it’s not possible here, because there may be multiple miners digging out a legal block at the same time, and then there will be a fork, which will lead to multiple blocks having the same block height, and the block The chain itself also has a main block chain and a backup chain, etc.

2. Genesis block

The first block in the blockchain is called the genesis block, which is the common ancestor of all blocks, that is, No matter from any block If you start backtracking at a high level, you can eventually find the genesis block.

The first transaction in each block is a Coinbase transaction. Because it is issuing Bitcoin, there is no transaction input. Therefore, customized data can be added to the transaction input. Earlier, some people expressed love and confession in it.

The Coinbase transaction input in the genesis block contains "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks." This sentence was the title of the Times' front-page article that day. This sentence tells people the importance of an independent monetary system!

3. Merkle tree

Each block in the Bitcoin blockchain contains all transactions in the block, represented by a Merkle tree.
A Merkle tree is a hashed binary tree, a data structure used for rapid induction and transactional large-scale data integrity.

Because the Merkle tree is a binary tree, it requires an even number of leaf nodes. If there are only an odd number of transactions that need to be summarized, the last transaction will be copied to form an even number of leaf nodes. .

Furthermore, in order to prove that a specific transaction is included in a block, a transaction only needs to be calculated l o g 2 N log_{2}N log2N*32-byte hash value forms an authentication path or Merkel path from a specific transaction to the root of the tree. As the number of transactions increases, such The amount of calculation is particularly important.

With a Merkle tree, a node can only download the block header (80Byte/block), and then authenticate the existence of a transaction through a Merkle path through a full node without the need to store or transmit a large number of blocks. Most of the content in the chain.

10. Mining mechanism

1. Introduction to mining

In fact, the word mining is a bit misleading. Mining in a general sense is similar to the extraction of precious metals, so people focus more on the rewards obtained after creating each block. Although the behavior of mining will be incentivized by this reward, the main purpose of mining is not this reward or the new coins generated. The mining process will create new coins, but mining is not the ultimate goal, but a means of motivation. Decentralized security can be achieved through mining.

Mining is a decentralized transaction clearing mechanism through which transactions are verified and cleared.

On average, a block is generated every ten minutes in the Bitcoin system. This block contains all transactions that occurred during the period from the previous block to the present. These transactions are added to the blockchain in turn.

Mining ensures the security of the system. Miners will receive two types of rewards during the mining process: new currency rewards for creating new blocks and transaction fees for all transactions in the block.

To receive these rewards, miners compete to complete a mathematical puzzle based on a cryptographic hashing algorithm. The answers to these puzzles, known as proof-of-work, are placed in new blocks as proof that miners put in a lot of computational work. In a proof-of-work competition, the winner is rewarded and has accounting rights on the blockchain, which is the basis of the Bitcoin security model.

In addition, the reward mechanism is designed in a mode of diminishing returns. The number of Bitcoins that miners get by creating new blocks is reduced by half every four years. After 2140, no new Bitcoins will be generated. In addition to coin creation rewards, miners will also compete for transaction fees. Each transaction may include a transaction fee. The transaction fee is the difference between the input and output of each transaction.
Insert image description here
Since the random number is 32 bits, you may have tried all the random numbers and still not found a solution that meets the requirements. At this time, you can add data implementation to the coinbase transaction, and then try the random number again from 0 number, if the solution still cannot be found in the post-order, the timestamp can also be updated.

2. Mining difficulty adjustment

To put it simply, the difficulty of mining will be dynamically adjusted according to the computing power of the entire network. If the problem is fixed, then as the computing power of the entire network increases, the difficulty of mining will become easier and easier, which may lead to The time it takes to dig out a block in the later period is much less than ten minutes, which does not meet the requirements. Therefore, the difficulty of Bitcoin will be dynamically adjusted according to the computing power of the entire network.

The specific difficulty adjustment is calculated by comparing the time spent on the most recent 2016 blocks with 20160 minutes.
To put it simply, if the network finds that the block generation cycle is faster than 10 minutes, it will increase the mining difficulty; otherwise, it will decrease the difficulty.
This formula can be summarized in the following format:
Insert image description here

3. Mining methods

Mining has gone through four processes, from initial CPU mining to GUP mining, then to ASIC mining, and now we use computing power to mine! ,

Since the computing level of the entire Bitcoin network continues to increase exponentially, no single device or a small amount of computing power can obtain the block rewards provided by the Bitcoin network on the Bitcoin network. After the computing power of the entire network increases to a certain level, the probability of obtaining rewards is too low, prompting some people to develop a method that can combine a small amount of computing power for joint operation. The website established using this method is called a mining pool!

If a miner joins the mining pool, the reward for successful block generation will be paid to the Bitcoin address of the mining pool, not to the individual miner. Miners participating in the mining pool divide the workload of searching for candidate blocks and earn shares based on their mining contributions. The mining pool sets a higher target value (lower difficulty) for earning shares, usually higher than Bitcoin The difficulty of the network is over 1000 times lower.

By setting a lower difficulty for obtaining shares, the mining pool can measure the amount of work completed by each worker. Whenever the worker finds a block header hash value that is less than the difficulty of the mining pool, it proves that it has completed its assigned share. The hash calculation required to find the result.

11. Applications of Bitcoin

1.Basic module

In order for applications to function properly and long-term, Bitcoin provides a series of guarantees that can be used as the basic building blocks to create applications.

These include:

1.Prevent double spending: Ensure that UTXO will not be spent twice

2.Immutable: Once the transaction is recorded in the block and then enough confirmation blocks are added (more than 6) , then the transaction data can be considered non-tamperable

3.Neutral: Any node can pay enough fees to create a valid transaction

4.Safe Timestamp: Reject any block with a timestamp that is too far away from the present (either in the past or in the future)

5.Authorization: Digital signatures provide authorization guarantee

6.Auditability: All transactions are public and auditable

7.Accountable: Transaction input = transaction output + transaction fee

8.Never expires: A valid transaction never expires

9.Fairness: Transactions cannot be modified by destroying the signature

10.Transaction atomicity: Transactions are either verified and confirmed, or they are not

11**.Fixed face value**: The transaction output is a fixed face value and indivisible unit

12.Quorum: Multi-signature emphasizes the number of authorized persons

13.Time lock: Support relative and absolute time lock

14.Replicability: After a transaction is created and verified to be valid, it will be copied and broadcast across the entire network

15.Anti-counterfeiting protection: Bitcoin cannot be created or counterfeited out of thin air

16.Consistency: The deeper the block depth, the less likely it is to be changed

17.Can record external status: Each transaction can submit a data through OP_RETURN to represent the status change of the external system

18.Predictable issuance: less than 21 million Bitcoins in total

Based on these basic modules, there are some typical applications:

1.Digital notarization (immutability + timestamp + persistence)

A digital fingerprint can be submitted to the blockchain through a transaction to prove that the file existed during the time it was archived (security timestamp). The digital fingerprint cannot be modified at any time (immutability), and the evidence will be stored permanently (persistence).

2.Payment channel (quorum + time lock + no double spending + never expires + auditable + authorization)

A quorum 2-2 multisig with a time lock is used to settle transactions on a payment channel and can be held or spent in any practice authorized by either party. Both parties can then create a double spend settlement confirmation transaction in a shorter practical lock.

2.Typical applications

1. Colored coins

Colored coins refer to technologies that use Bitcoin transactions to record the creation, ownership confirmation and transfer of external assets other than Bitcoin.

Colored coins are used to track digital and physical assets held by third parties and conduct transactions through colored coin ownership certificates.

For example:

It can be recorded on a banknote that it is a car exchange coupon. Then this banknote contains the asset information of a car. This banknote can be traded to achieve the purpose of buying and selling vehicle ownership. Similarly, type of information can be recorded on a Bitcoin transaction to achieve the transfer of external assets.

Today’s mainstream colored coins: Open Assets and Colu

In addition, the use of dyed coins in these two systems is isolated from each other and incompatible, and dyed coins cannot be used in ordinary systems

The essence of colored coins:

The dyed coin transaction is essentially a legal Bitcoin transaction. The special thing is that the output of the transaction contains an OP_RETURN transaction, which contains a data field that can be filled with any data. The dyed currency records data in this data field. of.

In addition, general blockchain browsers do not support the dyed currency protocol, so they cannot parse this data. However, the corresponding dyed currency protocol analysis can be used in the dyed currency browser.

2. Simple payment channel

Since the Bitcoin system produces a block every 10 minutes, the size of each block is 1MB, and there are up to 2,000-3,000 transactions. The maximum number of transactions per second in Bitcoin is only 7, which is far from meeting the needs of the public. Thus payment channels were born.

Payment channel: A mechanism for exchanging Bitcoin transactions between two parties outside the Bitcoin blockchain without requiring mutual trust between the two parties.

State channel: A payment channel is a state channel, in which the changed state is the virtual currency balance.

The process of establishing a payment channel is as follows:

1. Fund transaction: Establish a status channel between the two parties of the transaction, and the locked status is the initial balance of the channel

2. Commitment transaction: Both parties exchange signed transactions. Either party can submit settlement to the blockchain, but wait until the channel is closed before settling. There can be multiple commitment transactions, and the latest commitment transaction can invalidate the previous one.

3. Settlement transaction: occurs when cooperation ends and represents the final state of the channel.

3. Trustless channel

Simple payment channels are built under an ideal situation where both parties are working together and there are no failed transactions or attempts to cheat.

But in real situations it cannot be so smooth, for example:

If someone goes offline after paying for a payment channel, the funds in the channel cannot be withdrawn. In addition, any party can submit a transaction that benefits itself to the blockchain. For example, I bought a 1-hour video, but what I submitted to the blockchain was a half-hour fee. How can I avoid this? What about this situation?

At this time, you need to usetrustless channel
The core idea is: consumers When signing a funding transaction, a refund transaction (the first commitment transaction) is established, which has a longer time lock. In addition, each newly generated commitment transaction has a shorter locking time, as shown below:

However, it also has many shortcomings:

1. Establish a maximum time lock when the channel is first opened, limiting the service life of the channel

2. The time lock interval of the commitment transaction is set to 1 block, which requires participants to remain vigilant at all times, stay online and monitor in real time, and be ready to transmit the correct commitment transaction at any time

3. There are also quantitative restrictions on the committed transactions between the two parties.

4. Asymmetric revocable commitment

The core idea is to control Bitcoin and transaction ownership asynchronously by revoking keys and committing transactions

Its asymmetry is reflected in the fact that the commitment transaction held by each person is to pay the other party's amount immediately, but one needs to wait for a period of time to receive the funds. That is, unilaterally broadcasting a commitment transaction can put oneself at a disadvantage.

Additionally: there is a revocation key, which allows the defrauded party to punish bad actors by taking possession of the entire balance of the channel.

With this design structure, channels can remain open indefinitely and can hold billions of intermediate committed transactions.

Simple payment channel Unordered trust channel Asymmetric revocable commitment
illustrate Suitable for scenarios without deception Can solve the problem of cheating and disconnection Can solve the problem of cheating and disconnection
advantage Simple No need to worry about disconnection or fraud issues Channels can be used unlimitedly
shortcoming It is easy to cause the loss of BTC Limits the lifespan of the channel, with limited committed transactions between the two parties none
5. Hash time lock contract

Insert image description here
Congratulations, you have learned almost all the basic knowledge about blockchain. Blockchain is a new technology that can be integrated with a variety of technologies. At present, most blockchains are still used in conjunction with people. Mainly, it mainly realizes the payment function. In the future, it will be combined with things. In proportion, the blockchain is combined with the Internet of Things and 5G. Information data of the device is collected through the Internet of Things, and transmitted to the blockchain backend storage through 5G technology.

Guess you like

Origin blog.csdn.net/qq_51447436/article/details/134344549