为广大币圈朋友提供币圈基础入门专业知识!
当前位置首页 > 区块链知识> 正文

区块链如何写入数据,区块链如何写入数据库

发布时间:2023-12-06-08:17:00 来源:网络 区块链知识 区块

区块链如何写入数据,区块链如何写入数据库


请查看相关英文文档

A. Lesson 3 of the explanation: Blockchain

There was a wave of Bitcoin craze a few years ago, and readers may have heard of it at that time. Blockchain, however, recently domestic and foreign financial institutions have begun to study and launch financial services based on blockchain technology. What is so special about it that it can attract the favor of formal financial institutions?

Decentralized accounting system

Blockchain is one of the core technologies of Bitcoin. Its most important feature is its ability to create an untamperable and A centralized, highly transparent, and anonymous accounting system can provide low-cost, high-security transfer services, and can further be used as a financial management tool.

To understand the blockchain, we must first start with how it works. Taking the application of Bitcoin as an example, during each transaction, the system will seal the transaction content and related information into a set of blocks, and arrange all the blocks according to time to produce a so-called blockchain.

Since the blockchain records the information of every transaction in the world in detail, you can figure out which "wallet" it is by just counting the data from the first to the last. How much "money" do you have.

It should be noted that the blockchain does not directly store the balance in each "wallet", but the flow of "money" in each transaction. Therefore, when querying the balance, you only need to verify the area By counting the authenticity of each piece of information in the blockchain, the final balance of each "wallet" can be obtained.

Since generating blocks requires complex cryptographic calculations, if a centralized server is used for calculations, many high-performance computers will need to be prepared to meet the demand. However, Bitcoin’s approach is to distribute operations to all computers that perform “mining.” These computers are called nodes and will receive a certain amount of rewards after verifying transactions and encapsulating blocks. Therefore, there will be many miners trying to earn Bitcoins. Bitcoins are put into computers for calculation, so that no specific server is needed, but all calculation work is distributed to various nodes of the Bitcoin network.

▲The blockchain is formed by connecting many blocks in series. Since it can record transfers from the first to the last and has a high degree of security, it is very suitable for financial applications. . (Image source: Bitcoin: A Peer-to-Peer Electronic Cash System)

It is theoretically possible to crack, but in practice it is not feasible

In the block During the operation of the chain, all nodes will jointly verify each newly added block to ensure the correctness of the transaction. When the block information recorded by some nodes does not match that of other nodes, other nodes will not recognize the transaction. , so transaction records will not be written to the blockchain.

However, the security of blockchain is not theoretically unbreakable. As long as someoneBeing able to control more than half of the computing performance of the entire network (ie, controlling 51% of the computing performance), it can create fake transaction records and ensure that it can complete the block calculation and write the data before other nodes complete the calculation and raise objections. Enter the blockchain so that it can modify its transaction records and reuse the same Bitcoin for payment.

Using video games as a simple example, this attack is like using a cheat, which can modify the money to never decrease.

However, from a practical point of view, there are many users of Bitcoin, so there are quite a few nodes in the network, including many professional miners who use special computers to perform calculations, so the computing power of all nodes The total value is quite large, and it is difficult for ordinary people or organizations to grasp 51% of computing performance by themselves.

Assuming that the current computing power of all nodes is equivalent to 100 supercomputers, then the attacker would need to prepare 101 supercomputers to obtain more than half of the computing performance, which is unlikely to be achieved in the actual implementation.

If you take a step back and think about it, assuming that someone can really control more than half of the computing performance, then he can also monopolize the issuance of Bitcoin and transaction fees, and earn considerable profits from it. On the contrary, if If he chose to tamper with transaction data, Bitcoin users would lose confidence in the currency, causing the value of Bitcoin to collapse, or even "banknotes turning into wallpaper" overnight.

Therefore, assuming that the attacker is motivated by profit, then even if he can launch a 51% attack, he will not do so. This will ensure that Bitcoin and the blockchain are still safe.

▲Bitcoin is one of the most representative application examples of blockchain.

Example of using Shuowenjiezi: Blockchain

O: Blockchain can distribute the load of verifying transactions to everyone in the network node.

X: After parking the bicycle, remember to lock it with the blockchain.

B. Questions about Bitcoin (1) How a transaction is written into the block

Due to the massive calculations set by humans, the area used to store Bitcoin transaction information is limited. The speed at which the blockchain generates new blocks. What I know about this speed is that it takes about 10 minutes to produce one.

You create a digital stream containing complete transaction information in some way and upload it to the network. This network can be understood as the Bitcoin node network, or it can refer to a node that can verify transactions. All uses of the word "network" in this article are interpreted as such.

Certain nodes verify that your transaction is legal, and then broadcast it to the entire Bitcoin node network. This broadcast is a process of continuous verification and re-broadcast. Until transaction A is received by most nodes in the network.

Need to clarifyWhat is clear is that this process is only verification, not recording (confirmation).

What we call mining is to find a number that meets the requirements. This number represents a block just like an id.

After a transaction is confirmed in the network, it will be saved in the mining node to form a transaction pool. Miners need to select some high-priority transactions from the transaction pool to form an alternative block. , and mine according to this block. It is called a backup block because the transaction information stored in this block does not have an ID. Without an ID, it cannot be identified and cannot be approved.

In 04 Integrating Transactions & Building New Blocks, it is said that "after verifying transactions, each Bitcoin network node will add these transactions to its own memory pool". I think the node that verifies the transaction may be a non- Mining node, this node does not have the function of memory pool.

First of all, transaction fees are not fixed. To understand why it is not fixed, you need to understand a few issues:

There are a batch of transactions that need to be confirmed on the network. This batch of transactions exists in the hands of all miners, and the recording work is done by all miners. Work according to your own priorities, but confirm that the job function is completed by one of them. This miner is the miner who successfully adds the block recording the transaction to the main chain. This miner: Completed the recording work, found a new block, and successfully added the block to the network.

Multiple factors such as time and transaction volume determine the priority of transactions, and transaction fees are one of them.

Based on the above description, summary:

The miner completes the transaction confirmation.

When you initiate a transaction, you may or may not specify a transaction fee. The amount of the transaction fee is directly related to the transaction confirmation time. If no miner is willing to record your transaction, theoretically your transaction cannot be written to the blockchain, which means it cannot be confirmed. The deal would never be completed.

Assume that your transaction will eventually be written to the blockchain and effectively confirmed.

No matter how your transaction is in the hands of other miners, first of all, your transaction meets the requirements of the miner who confirmed the transaction and is added to the alternative block instead of lying in the transaction pool.

This new block containing your transaction information is successfully added to the main chain, and the main chain is effectively extended. At this point your transaction record is effectively confirmed.

C. What technology does the blockchain apply to achieve this function?

The blockchain applies the following technologies to achieve this
The first is the consensus mechanism, a commonly used consensus mechanism Mainly include PoW, PoS, DPoS, PBFT, PAXOS, etc. Since there is no center in the blockchain system,This requires a preset rule to guide the nodes of all parties to reach an agreement on data processing, and all data interactions must be carried out in accordance with strict rules and consensus;
The second is cryptography technology, which is the key to distinguishing between One of the core technologies of the blockchain, many classic algorithms of modern cryptography are used in current blockchain applications, mainly including: hash algorithm, symmetric encryption, asymmetric encryption, digital signature, etc.
The third type is distributed storage. Blockchain is a distributed ledger on a peer-to-peer network. Each participating node will independently and completely store and write block data information. The advantages of distributed storage compared with traditional centralized storage are mainly reflected in two aspects: data information is backed up on each node to avoid data loss due to single point failure; data on each node is stored independently, effectively avoiding Malicious tampering with historical data.
Smart contracts: Smart contracts allow trusted transactions without a third party. As long as one party reaches the pre-set goals of the agreement, the contract will automatically execute the transaction. These transactions are trackable and irreversible. It has the advantages of transparency, credibility, automatic execution, and mandatory performance. Blockchain technology has many unique features that make it a unique invention and give it unlimited horizons to explore.

D. Explanation of terms blockchain

Blockchain is explained as follows:

Blockchain is actually equivalent to a disintermediated database, which is composed of It consists of a series of data blocks. Each of its data blocks contains information about a Bitcoin network transaction, which is used to verify the validity of the information and generate the next block.

In a narrow sense, blockchain is a chain data structure that combines data blocks in a sequential manner in chronological order, and is cryptographically guaranteed to be inextricable. Tamper-proof and unforgeable distributed ledger.

Type

Public Blockchain

Public Block Chains: Any individual or group in the world Transactions can be sent and effectively confirmed by the blockchain, and anyone can participate in its consensus process.

Public blockchain is the earliest blockchain and the most widely used blockchain. The virtual digital currencies of all major bitcoins series are based on public blockchains. There is only one such blockchain in the world. The blockchain corresponding to the currency.

Industry Block Chains

Industry Block Chains (Consortium Block Chains): Multiple pre-selected nodes are designated within a certain group as bookkeepers, and each block is generated by All pre-selected nodes make a joint decision (pre-selected nodes participate in the consensus process);

Other access nodes can participate in transactions, but do not participate in the accounting process (it is essentially still managed accounting, but becomes distributed accounting) , the number of pre-selected nodes, how to decide the bookkeeper of each block becomes the main risk point of the blockchain), anyone else can pass the blockChain open API for limited query.

Private Block Chains

Private Block Chains: Only use the general ledger technology of the blockchain for accounting. It can be a company or an individual. With exclusive write access to the blockchain, this chain is not much different from other distributed storage solutions.

Traditional finance is trying to experiment with private blockchains, while public chain applications such as Bitcoin have been industrialized, and private chain application products are still being explored.

E. How to use blockchain in supply chain finance

In traditional supply chain finance, financing difficulties, high financing costs, and cumbersome financing processes have always been constraints for small, medium and micro enterprises. One of the bottlenecks to becoming bigger and stronger. The bank relies on the core enterprise's ability to control goods and regulate sales. For risk control reasons, the bank is only willing to provide factoring business to upstream suppliers (limited to first-tier suppliers) that have direct accounts payable obligations of the core enterprise, or Provide advance payment or inventory financing to its downstream dealers (first-tier suppliers). This has resulted in the needs of second- and third-tier suppliers/dealers with huge financing needs not being met, and the business volume of supply chain finance being restricted. The lack of timely financing for small and medium-sized enterprises can easily lead to product quality problems. , will harm the entire supply chain system.

To solve these problems, the decentralized, non-tamperable, and distributed ledger characteristics of blockchain technology can be used to create a blockchain supply chain financial platform.

1. The core enterprise issues a receivable voucher to the distributor. After the distributor signs the receipt, it indicates that a purchase and sales contract has been signed, and the core enterprise delivers the goods.

2. Distributors need financial loans due to financial constraints.

3. The financial institution will transfer the loan amount to the core enterprise after review and approval.

4. Distributors repay the loan and interest after selling the goods

F. How to explain blockchain in a popular way

“Blockchain technology is considered to be the successor to After steam engines, electricity, and the Internet, the next generation of disruptive core technologies comes. If steam engines have released people’s productivity, electricity has solved people’s basic living needs, and the Internet has completely changed the way information is transmitted, then blockchain, as a platform for building trust, Machines will have the potential to completely change the way value is delivered throughout human society."


I have just come into contact with the blockchain, and there are too many basics that need to be understood and known. Don’t worry about knowledge. Today I will popularize this knowledge for you. Today, let’s first take a look at what public chains, private chains, alliance chains, and side chains are.

G. Tutorials for getting started with blockchain


However, there are very few simple and easy-to-understand introductory articles. What exactly blockchain is and what makes it special is rarely explained.
Next, I will try to write a best-understood blockchain tutorial. It's not that difficult after allThings, the core concept is very simple and can be explained clearly in a few sentences. I hope that after reading this article, you will not only understand the blockchain, but also understand what mining is, why mining is getting more and more difficult, and other issues.
It should be noted that I am not an expert in this area. Although I have been paying attention to it for a long time, my detailed understanding of blockchain started at the beginning of this year. You are welcome to correct any errors or inaccuracies in the article.
1. The essence of blockchain
What is blockchain? In a word, it is a special distributed database.
First of all, the main function of blockchain is to store information. Any information that needs to be saved can be written to the blockchain and read from it, so it is a database.
Secondly, anyone can set up a server, join the blockchain network, and become a node. In the world of blockchain, there is no central node. Every node is equal and stores the entire database. You can write/read data to any node, because all nodes will eventually be synchronized to ensure that the blockchain is consistent.
2. The biggest features of blockchain
Distributed databases are not a new invention, and there have been such products on the market for a long time. However, blockchain has a revolutionary feature.
Blockchain has no administrator, it is completely centerless. Other databases have administrators, but blockchain does not. If one wanted to add auditing to the blockchain, it would not be possible because it is designed to prevent the emergence of a central authority.
It is precisely because it is unmanageable that blockchain can be uncontrollable. Otherwise, once big companies and large groups control the management, they will control the entire platform, and other users will have to take orders from them.
However, without an administrator, everyone can write data into it. How can we ensure that the data is trustworthy? What if it is modified by a bad person? Please read on, this is the wonderful thing about blockchain place.
3. Block
Blockchain is composed of blocks. Blocks are much like database records. Every time data is written, a block is created.
Each block contains two parts.
Head: records the characteristic values ​​of the current block
Body: actual data
The block header contains multiple characteristic values ​​of the current block.
Generation time
Hash of the actual data (i.e. block body)
Hash of the previous block
...
Here, you need to understand what a hash is , which is necessary to understand blockchain.
The so-called hashing means that the computer can calculate a characteristic value of the same length for any content. The hash length of the blockchain is 256 bits, which means that no matter what the original content is, a 256-bit binary number will be calculated in the end. And it can be guaranteed that as long as the original content is different, the corresponding hash must be different.
For example, the hash of the string 123 is (hexadecimal), which is 256 bits when converted to binary, and only 123 can be obtainedthis hash. (Theoretically, it is possible for other strings to get this hash, but the probability is extremely low and can be approximated as impossible.)
Therefore, there are two important inferences.
Corollary 1: The hash of each block is different, and the block can be identified by the hash.
Corollary 2: If the content of the block changes, its hash will definitely change.
4. The non-modifiable nature of Hash
Blocks and hashes have a one-to-one correspondence, and the hash of each block is calculated based on the block header (Head). That is to say, the characteristic values ​​​​of the block header are connected together in order to form a very long string, and then the hash is calculated on this string.
Hash = SHA256 (block header)
The above is the calculation formula of block hash. SHA256 is the hash algorithm of the blockchain. Note that this formula only contains the block header and not the block body. In other words, the hash is uniquely determined by the block header.
As mentioned before, the block header contains a lot of content, including the hash of the current block body. , and the hash of the previous block. This means that if the content of the current block body changes, or the hash of the previous block changes, it will definitely cause the hash of the current block to change.
This point has great significance for blockchain. If someone modifies a block, the hash of the block changes. In order for subsequent blocks to still be connected to it (because the next block contains the hash of the previous block), the person must modify all subsequent blocks in sequence, otherwise the modified block will be removed from the blockchain . Due to the reasons mentioned later, hash calculation is very time-consuming, and it is almost impossible to modify multiple blocks in a short period of time, unless someone controls more than 51% of the computing power of the entire network.
It is through this linkage mechanism that the blockchain ensures its own reliability. Once the data is written, it cannot be tampered with. This is just like history, what happened happened, and it can’t be changed from now on.
Each block is connected to the previous block, which is where the name blockchain comes from.
5. Mining
Since synchronization between nodes must be ensured, the adding speed of new blocks cannot be too fast. Just imagine, you have just synchronized a block and are preparing to generate the next block based on it, but at this time, another node generates a new block, and you have to give up half of the calculations and synchronize again. Because each block can only be followed by one block, you can only generate the next block after the latest block. So, you have no choice but to sync as soon as you hear the signal.
So, the inventor of the blockchain, Satoshi Nakamoto (this is a pseudonym, and his true identity is still unknown) deliberately made it difficult to add new blocks. His design is that on average, the entire network can generate a new block every 10 minutes, which is only six per hour.
This output speed is not achieved through commands, but by deliberately setting up massive calculations. In other words, only through an extremely large amount of calculations can the effective hash of the current block be obtained, thereby converting the new block intoBlocks are added to the blockchain. Because the amount of calculation is too large, it cannot be done quickly.
This process is called mining, because the difficulty of calculating a valid hash is like finding a grain of sand that meets the conditions among the sand in the world. The machine that calculates hashes is called a mining machine, and the person who operates the mining machine is called a miner.
6. Difficulty coefficient
After reading this, you may have a question. People say that mining is difficult, but isn’t mining just about using a computer to calculate a hash? This is the strength of computers. How could it be? It becomes very difficult, why can’t it be calculated?
It turns out that not just any hash can be used, only hashes that meet the conditions will be accepted by the blockchain. This condition is particularly harsh, causing most hashes to fail to meet the requirements and must be recalculated.
It turns out that the block header contains a difficulty coefficient (difficulty), which determines the difficulty of calculating the hash. For example, the difficulty coefficient of the 100,000th block is 14484.16236122.
The blockchain protocol stipulates that the target value (target) can be obtained by dividing the difficulty coefficient by a constant. Obviously, the greater the difficulty coefficient, the smaller the target value.
The validity of the hash is closely related to the target value. Only hashes smaller than the target value are valid, otherwise the hash is invalid and must be recalculated. Since the target value is very small, the chance that the hash is smaller than this value is extremely slim, and it may be calculated 1 billion times before it is considered a hit. This is the fundamental reason why mining is so slow.
As mentioned earlier, the hash of the current block is uniquely determined by the block header. If the hash of the same block needs to be calculated repeatedly, it means that the block header must keep changing, otherwise it is impossible to calculate different hashes. All feature values ​​in the block header are fixed. In order to make the block header change, Satoshi Nakamoto deliberately added a random item called Nonce.
Nonce is a random value. The role of the miner is actually to guess the value of Nonce so that the hash of the block header can be smaller than the target value so that it can be written to the blockchain. Nonce is very difficult to guess. At present, we can only use trial and error one by one through exhaustive methods. According to the protocol, Nonce is a 32-bit binary value, which can reach a maximum of 2.147 billion. The Nonce value of the 100,000th block is 274148111. It can be understood that the miner started from 0 and calculated 274 million times before obtaining a valid Nonce value so that the calculated hash can meet the conditions.
If you are lucky, you may find Nonce in a while. If you are unlucky, you may have calculated it 2.147 billion times without finding the Nonce, that is, it is impossible to calculate a hash that meets the conditions for the current block body. At this time, the protocol allows miners to change the block body and start a new calculation.
7. Dynamic adjustment of difficulty coefficient
As mentioned in the previous section, mining is random, and there is no guarantee that a block will be produced in exactly ten minutes. Sometimes it will be calculated in one minute, and sometimes it will be severalThere may be no results for hours. Overall, with the improvement of hardware equipment and the increase in the number of mining machines, the computing speed will definitely become faster and faster.
In order to keep the output rate constant at ten minutes, Satoshi Nakamoto also designed a dynamic adjustment mechanism for the difficulty coefficient. He stipulated that the difficulty factor should be adjusted every two weeks (2016 blocks). If the average block generation speed in these two weeks is 9 minutes, it means that it is 10% faster than the legal speed, so the next difficulty factor will be increased by 10%; if the average block generation speed is 11 minutes, it means It is 10% slower than the legal speed, so the difficulty factor of the next step must be lowered by 10%.
The difficulty coefficient is adjusted higher and higher (the target value is getting smaller and smaller), which makes mining more and more difficult.
8. Forks of the blockchain
Even if the blockchain is reliable, there is still an unresolved problem: if two people write data to the blockchain at the same time, that is to say, two people write data to the blockchain at the same time. Blocks join because they are connected to the previous block, forming a fork. Which block should be adopted at this time?
The current rule is that new nodes always adopt the longest blockchain. If there is a fork in the blockchain, it will look at which branch is behind the fork to reach 6 new blocks first (called six confirmations). Based on a block calculation of 10 minutes, it can be confirmed in one hour.
Since the generation speed of new blocks is determined by computing power, this rule means that the branch with the most computing power is the authentic blockchain.
9. Summary
Blockchain, as an unmanaged distributed database, has been running for 8 years since 2009 without major problems. This proves it works.
However, in order to ensure the reliability of data, blockchain also has its own price. The first is efficiency. You have to wait at least ten minutes to write data to the blockchain. All nodes synchronize the data, which requires more time. The second is energy consumption. The generation of blocks requires miners to perform countless meaningless calculations. This is Very energy consuming.
Therefore, the applicable scenarios of blockchain are actually very limited.
There is no management authority that all members trust
The written data does not require real-time use
The benefits of mining can make up for its own costs
If the above conditions cannot be met, then the traditional database is Better solution.
Currently, the largest application scenario (and possibly the only application scenario) of blockchain is the cryptocurrency represented by Bitcoin.

H. How to store blockchain transaction information

Blockchain is a large distributed ledger, and detailed data must be stored on the longest chain. , verify data through hashing, and only data verified by most nodes can be saved on the longest chain. The latest data can be synchronized between nodes, and at the same time, distributed storage of data is achieved, which is not easy to be tampered with. Each transaction corresponds to a timestamp, and the status of each transaction can be queried based on the timestamp, which is traceability.

博客主人唯心底涂
男,单身,无聊上班族,闲着没事喜欢研究股票,无时无刻分享股票入门基础知识,资深技术宅。
  • 36897 文章总数
  • 3637265访问次数
  • 3078建站天数