In terms of the Bitcoin white paper, the essence of the blockchain is a P2P (peer-to-peer) distributed ledger. When a node sends a transaction, it needs to broadcast to surrounding nodes. Full nodes (as well as light nodes, etc., light nodes generally only store information related to themselves). data), write the received transaction information into the block body, and obtain the accounting authority (that is, to authenticate some transaction data, as well as other mechanisms such as PoS and DPoS) under the action of the consensus mechanism (PoW is mining, as well as other mechanisms such as PoS and DPoS). Permission to write blocks into the blockchain), broadcast the new block to the surrounding nodes, and other nodes synchronize the local state according to the block data after verifying the validity of the data and the accounting authority, so as to achieve the same state of the entire block network. At the same time, because the new block header contains the associated information of the previous block, the blocks are connected to form a blockchain.
Simply put, it means that all nodes in the network perform the exact same operations to maintain a state-consistent distributed system locally.
Blockchain structure: block + hash link
- Chain: New blocks are associated through inter-block hashing (a hash algorithm is an algorithm that generates a fixed output from a fixed input, which can be understood as generating an identity ID for the input), and the blocks are linked into a chain through this association
block:
block body:
- The structure of the block body is often a tree
- The leaf nodes of the tree store the actual data, that is, ledger information (such as transaction information), etc.
- The hash value is obtained layer by layer to form a hash tree (ie Merkle Tree or its variant structure)
Block header: responsible for basic functions, generally including the following parts
- Evaluate the hash of the previous block (hash only the content of the block header of the previous block)
- root hash of hash tree
- timestamp
- Wait
Tamper-proof:
- Single block: When the transaction information in a single block is modified by a node, it will inevitably affect the root hash of the hash tree stored in the block header layer by layer, so the root hash needs to be modified to achieve a single block. Block data tampering validity
- Chain: If the root hash in a block is modified, then hashing the block's header will inevitably produce a new value, and the value of its hash reference in the next block If not, it will inevitably affect all subsequent blocks on the entire chain, so all subsequent blocks need to be modified to achieve the validity of the tampering
- The feasibility of tampering with the entire blockchain needs to destroy the consensus that has been formed, and requires a repressive advantage. In theory, it is difficult to achieve in a system with many participants, thus ensuring the tamper-proof feature of the blockchain.
bitcoin
condition
The Bitcoin node maintains a local ledger called UTXO (Unspent Transaction Output), that is, the unused transaction output, which can be simply understood as an unused transfer input, which is used for the transfer of subsequent transfers.
Operating mechanism
The block body of a Bitcoin block stores each new transaction in a hash tree structure.
An example of a protocol message for a single transaction is as follows:
In:
// 表示这次交易使用的资金的来源
Previous tx: f5d8...430901c91
// 资金来源所在交易的哈希
Index: 0
// 资金来源交易哈希中的哪个转出
scriptSig: 3045...798a4 618c...41501
// 对声明的资金来源的解锁脚本,含有签名和公钥
// 可以简单理解为银行卡号和密码
Out: // 表明这次交易的输出
Value: 5000000000
// 金额
scriptPubKey: OP_DUP OP_HASH160 4043...549d OP_EQUALVERIFY OP_CHECKSIG
// 锁定脚本,含有对公钥的哈希和一些运算符,使用这笔转出的交易需要在它的 scriptSig 提供可以通过脚本的信息才能解锁
// 可以理解为银行卡号的哈希和一些操作指令
Popular science of asymmetric encryption concepts:
- The public and private keys are generated in pairs
- The public key is publicly available to other nodes in the system, and the private key is reserved for individuals
- The wallet address is generally obtained by performing a series of operations using the public key
We do not clearly distinguish between the wallet address and the public key, which can be inaccurately understood as
- Public key, wallet: account number
- Private key: account password
Public key and private key also have a cryptographic feature: data encrypted by a single key must and can only be decrypted by another key
- Encryption: The sender encrypts the content with the recipient's public key, and only the recipient can decrypt the content with its own private key, avoiding data leakage on the sending path
- Signature verification: Going further, the sender signs the content with his own private key, sends the signature and content to the receiver, and the receiver decrypts the signature using the sender's public key, and finds that the signature and the content are consistent, indicating that on the sending path, Content has not been tampered with
Transaction information: Each transaction is based on the previous transaction record, and the input needs to be equal to the output (in fact, there is a difference, and the difference will be used as the node's work fee)
Example: Account A wants to pay 6 bitcoins to account D, then the transaction data is written as:
enter:
- The output of a previous transaction (account B paid 2 bitcoins to account A)
- The output of a previous transaction (account C paid 3 bitcoins to account A)
- The output of a previous transaction (account D pays 2 bitcoins to account A)
output:
- Pay 6 BTC to D account
- Pay 1 bitcoin to account A
Features:
- The source of the expenditure needs to be stated
- The amount in the stated source of funds cannot be split, and the extra part can be transferred to yourself by way of change
Transaction information into the chain:
distributed:
- Many nodes on the network perform storage and data authentication
- Sending node broadcasts transaction information to surrounding nodes
- Each node holds complete or partial data of the blockchain
Validity: If an account sends multiple contradictory transaction information at the same time
- The full node will verify the received transaction information and write it into the block
The verification process will use the script in the transaction information
The transaction information sent by the node contains
- Description of the source of funds
- Unlock information for each funding source
Node that received the message:
- Confirm UTXO: Verify that the source of funds exists in the UTXO, i.e. is not used
Execute the script:
- After splicing the unlocking signature and the locking script contained in the corresponding transaction output, it is executed in a stack structure
- Take the sample information as an example, splicing it into
[private key signature, public key] (provided by the unlock script) [OP_DUP, OP_HASH160, public key hash, OP_EQUALVERIFY, OP_CHECKSIG] (provided by the lock script)
The implementation is roughly:
- Take out the public key (OP_DUP)
- Perform Hash 160 operation (OP_HASH160)
- Compare the result to the public key hash for equality (OP_EQUALVERIFY)
- Verify Signature (OP_CHECKSIG)
Confirmation: How to confirm the ownership of UTXO
- The process of comparing the public key hash in the unlocking script with the public key hash in the locking script during script execution is the operation to determine all ownership
- Confirm that the provided bank card account is indeed the account with the balance
Anti-counterfeiting of transaction information:
Sending node:
- Get a digest of the transaction hash
- Encrypt the digest with the sending node's private key to generate a signature
- Broadcast content and signatures
Receiving node: process of executing
OP_CHECKSIG
- Decrypt the signature using the public key of the sending node to get digest 1
- Hash the content, get digest 2
- Digest 1 is equal to Digest 2, the public key and private key match, and the content is credible
- That is, the transaction information is written by the owner of the corresponding private key that unlocks the public key of the transaction output.
Consistency: network transmission problems, the transaction information received by each node may be different, then the transactions they verify and write into the block may be different, and if they are all uploaded to the chain, the final generated block information will be inconsistent.
- PoW: Using consensus rules, only one node has the right to legally publish blocks within a unit of time (about 10 minutes), that is, the right to bookkeeping
rule:
- Combine the contents of the new block (the previous block header hash, the basic information of this block, the root hash of the transaction information of the new block) into a string
- Add a random number to the end of the new block string, and perform SHA-256. If the first 72 bits of the result are all 0s, the work is completed. This is a lot of work by chance.
- As the overall computing power increases, the difficulty will increase (increase the number of 0s, etc.), and the block time will be stabilized at 10 minutes
- This process is also called mining, which requires a lot of computing power. Nodes that perform PoW are also called miners.
Node income:
- Bitcoin network reward: Nodes will write a reward transaction (Coinbase Newly Generated Coins) for 6.25 Bitcoin outputs to their addresses when a block is generated. This reward is halved every 210,000 blocks and is also Bitcoin’s How to issue coins
- Transaction fee in the block: the difference between all input and output amounts in the block, written by the miner to himself
- Fork: It happens that two blocks are generated at the same time, then the two blocks will be included in the chain together, forming a temporary fork. In the subsequent calculation, the longest chain principle is adopted, and the fork with a small number of additional blocks is discarded.
- Transaction confirmation: It is precisely because of the existence of forks and waste blocks that transactions generally need to be added after multiple blocks are added before they are confirmed. Bitcoin generally needs to be added after 6 blocks to be considered relatively safe.
- Tampering: Super high computing power is required. The computing power of the tamperer needs to exceed the computing power of the entire network to achieve tampering, so that the tampering fork can become the longest chain and complete the tampering.
Summarize
- Use SHA-256 hash algorithm and asymmetric encryption to make digital signature for anti-counterfeiting
- Execute the script verification in the transaction information to verify the signature
- Use the blocks of the blockchain to store bitcoin transaction information, use the hash tree to store and prevent transaction data from tampering
- Achieving network consistency with additional work rules (combining power)
- Pay network rewards and transaction fees to miner nodes
Ethereum
Ethereum Yellow Paper
https://ethereum.github.io/yellowpaper/paper.pdf
Ethereum is also a transaction-driven state machine that supports smart contracts, a programmable blockchain, and a platform for decentralized applications.
We see that Bitcoin has certain script execution capabilities, but its script is relatively simple and only supports several fixed transaction protocols and script commands. Ethereum is different, it is Turing complete, and blockchain developers can freely program within the scope of support.
structure
block header
- parentHash: Calculate the hash of the block header of the previous block
- ommersHash: uncle block hash
- beneficiary: the account address of the block reward
- stateRoot: state tree root hash
- transactionsRoot: transaction tree root hash
- receiptsRoot: Receipt tree root hash
- logsBloom: Data Bloom filter
- gasLimit: the upper limit of the block gas fee, which is jointly maintained by the miners
- Wait
ommersHash
Due to the faster block generation speed of Ethereum, the possibility of temporary forks is higher. ommersHash is designed for the purpose of suppressing forks. The idea is as follows. The valid blocks are written into ommersHash (up to Two) waste blocks can also get block rewards, the first level is 7/8, the second level is 6/8, and a valid block is written into a waste block will also have a 1/32 reward.
Bloom filter
Bloom filter is a relatively efficient but inaccurate search algorithm. The general mechanism is as follows:
- Provide a batch of hash functions
- map the input to several points of the array
- When querying, you can query whether the corresponding points of the array have values.
Such as:
live:
- apple maps to points 1, 7, 9
- banana maps to points 1, 3, 7
check:
- The orange mapping value is 1, 3, 9, all have values, then orange may exist
- The peach mapping value is 2, 3, 7, and 2 has no value, then peach must not exist
It can be seen that the judgment of the existence of the Bloom filter will be false, but the non-existence will not be false, so it is suitable for filtering large amounts of data.
block body
Unlike Bitcoin, there are three trees in the block body of Ethereum: the state tree, the transaction tree, and the receipt tree. The data of the tree will be maintained in the local database by the full node.
State tree:
- A variant of compressed prefix hash tree (Merkle Patricia Tree, MPT)
Stores the state of all known (that is, transactions that have occurred) accounts
- External account: wallet address, no code, able to transfer money or execute smart contracts
- Contract account: It is generated when a contract is created, has code, and can be triggered to execute smart contracts
Account Status:
- nonce: the number of transactions or contracts of the address
- balance: balance
- codeHash: The hash of the code for the contract account, not for external accounts
- storageRoot: root hash of the account content (also an MPT tree)
- The new block will only actually store the new state of the account that has changed, and the unchanged block will point to the corresponding position of the previous block state tree
Transaction tree: The drive state tree changes, which is also MPT, and only saves the transaction information that occurs in the block
- message call information
- Information about contract account creation
Receipt Tree: Also MPT
- Specific information during transaction execution is encoded as transaction data and stored in a tree whose index is the key
- The log created during the transaction constitutes the Bloom filter of the block header
consensus mechanism
At present, Ethereum also uses PoW (Proof of Work), that is, mining, to determine the accounting rights.
Generate a small data set (MB level) from a seed, and then generate a large data set (GB level size) from the small data set, use the block header and a nonce value to obtain a hash, map to the large data set, Read the target position and adjacent elements in the large data set, hash again, and cycle 64 times to calculate a hash and mining target value comparison. If it fails, replace the nonce in the block header and recalculate.
At the same time, Ethereum also has a plan to convert the PoS mechanism. There is a difficulty factor in the difficulty adjustment mechanism of Ethereum. This difficulty factor will double every 100,000 blocks, which is an exponential factor, so it is also called difficulty. Bomb, because the PoS mechanism did not go online smoothly, and the difficulty bomb caused the block generation speed to increase too fast, so Ethereum modified its code, so that 3 million blocks were subtracted from the calculation of the difficulty factor, which was also caused by the code upgrade. A hard fork of the Fang network, but fortunately, all the nodes of the forked network have undergone code upgrades.
smart contract
As mentioned earlier, there is a contract account in the Ethereum network, and there is a piece of code in the account, so a smart contract is the code that is executed according to the established logic.
transfer
An external account calls a contract account, and a contract account call initiated by an external account can also call another contract account.
When the external account is called, write the target function and parameters in the data field, and initiate a transaction to the contract account.
A way for a contract to call a contract:
contract A {
event LogCallFoo (string str);
function foo (string str) returns (uint) {
emit LogCallFoo(str);
return 123;
}
}
contract B {
uint ua; // callAFooDirectly 的执行返回值
function callAFooDirectly (address addr) public {
A a = A(addr);
ua = a.foo("call foo directly); // 调用 a 地址的 foo 方法
}
}
Create and run
- After the smart contract code is written (solidity, etc.), it is compiled into bytecode
- Create: The external account initiates a transaction to the 0*0 address and puts the code in the data field
- Smart contracts run in EVM
- The transaction calling the smart smart contract writes the function and parameters in the data field of the transaction, and after publishing it on the blockchain, the miner who receives the message will execute the code according to the parameters
The account that initiates the call needs to pay the gas fee GasLimit
- The full amount will be deducted before the execution, and the execution will begin. More refunds and less compensation. If not enough, the status will be rolled back, and the gas fee will not be refunded.
- If there is an error in the execution, the overall status will be rolled back, and the gas fee will not be refunded: a non-rigorous example, the smart contract can initiate transfers to A and B. If the transfer to B is wrong, the status of the transfer to A will also be rolled back.
- After each transaction is executed, a receipt is formed, which contains information such as the execution result.
one example
Here is an auction bid smart contract:
contract SimpleAuctionV1 {
address public beneficiary; // 受益人
uint public auctionEnd; // 结束时间
address public highestBidder; // 当前最高出价地址
mapping(address => unit) bids; // 所有出价
address[] bidders; // 所有出价地址
bool ended; // 是否结束
event HighestBidIncreased(address bidder, uint amount);
event AuctionEnded(address winner, unit amount);
constructor(uint _biddingTime, address _beneficiary) public {
beneficiary = _beneficiary;
auctionEnd = now + _biddingTime
}
}
// 参与拍卖的地址向此合约地址发起交易并支付货币
function bid() public payable {
require(now <= auctionEnd);
require(bids[msg.sender]+msg.value > bids[highestBidder]);
// 没出过价则把出价人存起来
if (!(bids[msg.sender] == unit(0))) {
bidders.push(msg.sender);
}
// 如果出价最高则修改当前最高出价人
highestBidder = msg.sender;
bids[msg.sender] += msg.value;
emit HighestBidIncreased(msg.sender, bins[msg.sender]);
}
// 拍卖结束
function auctionEnd()public {
require(now > auctionEnd);
require(!ended);
// 把最高出价转给受益人
beneficiary.transfer(bids[highestBidder]);
// 给没竞拍成功的人退钱
for (uint i = 0; i< bidders.length; i++) {
address bidder = bidders[i];
if (bidder == highestBidder) continue;
bidder.transfer(bids[bidder]);
}
ended = true;
emit AuctionEnded(highestBidder, bids[highestBidder]);
}
- There is a problem here:
beneficiary.transfer
, if beneficiary is a contract address that cannot accept payment (payable keyword is not declared), thenauctionEnd
will fail to execute, resulting in all bids locked in the smart contract address and can never be taken out - In addition to this, there are reentrancy attacks, that is, the calling contract account may be called in reverse, causing circular execution
Code Is Law。
The logic of the smart contract is determined by the code. The released contract code cannot be modified. If a new code is released, another contract account address will be generated, so even if there is a bug, it cannot be modified.
The DAO (Decentralized Autonomous Organization): Using the re-entrancy attack, the hacker wrote the code to call The DAO in the collection function of his contract account, and transferred 50 million/150 million US dollars using the method of circular calling. about 10% of the total amount of ether in the ethereum system. In order to make up for the significant impact on the stability of ethereum, after a soft fork repair failed, ethereum pledged for voting, ethereum chose a hard fork, The forcible transfer of the ether in The DAO caused a split in the community, resulting in a hard fork of ethereum into ETH and ETC.
NFT
As can also be seen from the smart contract example, the developer of the smart contract can maintain a state tree inside the contract account.
One of the application methods is to issue Tokens in the blockchain network based on smart contracts, and maintain the status of all holders in the contract account.
NFT is such an application, which is called a non-fungible token. A major feature of NFT is that based on the characteristics of the blockchain, the ownership of an address to a digital work is publicly and tamper-proof.
An example of NFT data on the blockchain of an ERC721 standard (a standard for issuing NFTs on Ethereum):
- Address: 0x40468d172cE354d3fAdAb06D0FA53eDdB2F3AA45
- id:6
- tokenURI:https://Opensea-creatures-api.herokuapp.com/api/creature/6)
Since the content of https will be modified, the tokenURI will generally be replaced by IPFS (distributed file storage system). This example shows that an address owns an item numbered 6 with the content of the tokenURI.
From the perspective of most NFT implementations, only the address of the owner of a work, the number of the work, and the link to the work are recorded on the blockchain, while the work itself is off-chain. Therefore, there have also been cases where the works of artists are taken away by others and sold as NFTs, so NFTs cannot solve offline problems. , NFT will provide the liquidity of digital assets, but it cannot give value to the item .
By calling the functions of the smart contract, the transfer and transaction of NFT can be carried out. So you can know that NFT does not only refer to a certain token, but a type of token. You can also issue your own NFT or NFT platform by creating your own smart contract.
metaverse
Blockchain should be a technology realized by the Metaverse, as the basis for confirming the rights of digital assets in the digital world that can be copied arbitrarily, such as the existing virtual land of Decentraland and the sale of creations.
At the same time, for virtual items born in the digital world, since there is no need to solve offline problems, the applicability of NFT should be higher.
other
- Empty block: In some blockchains, after a new block is generated, the block header will be broadcast first and then the block body. Since the block body data is large, it will take time to download, and some miner nodes will start after receiving the block header. In mining, since the transaction information written to the new block body cannot conflict or duplicate with the existing block, in order to ensure the validity of the new block without obtaining the information of the previous block, the new block will not be sent to the new block. The actual transaction information (except reward information) is written into the body, resulting in an empty block.
Summarize
- The blockchain has been criticized for slow transactions and high energy consumption, but it is faster than the existing solutions in specific scenarios based on scene observation.
- In theory, blockchain-based NFT digital asset transactions will provide the liquidity of digital assets, but cannot give value to the items themselves.
- Investment is risky, and chasing hot spots should be cautious.
References
- Most of the information sources: https://www.bilibili.com/video/BV1Vt411X7JF
- https://blog.csdn.net/vigor2323/article/details/122711205
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。