Blockchain 2.0 Ethereum talk (2)

Yin Cheng 2021-11-24 08:10:32 阅读数:956

blockchain ethereum talk

The purpose of Ethereum is based on script 、 Competition currency and chain yuan agreement (on-chain meta-protocol) Integrate and improve concepts , Enables developers to create arbitrary consensus based 、 Extensible 、 standardized 、 Characteristic complete 、 Easy to develop and collaborative applications . Ethereum builds the ultimate Abstract foundation layer - A blockchain built with Turing complete programming language - Enables anyone to create contracts and decentralized applications and set up their freely defined ownership rules 、 Transaction mode and state transition function . The main framework of domain currency only needs two lines of code , Other protocols such as currency and reputation systems can be implemented in less than 20 lines of code . Intelligent contract - An encrypted box that contains value and can only be opened if certain conditions are met - We can also create... On our platform , And because of Turing's completeness 、 Value awareness (value-awareness)、 Blockchain awareness (blockchain-awareness) And multi state, which is much more powerful than the smart contract provided by bitcoin script .

Ethereum account :

In Ethereum system , The state is defined by what is called “ Account ”( Each account has a 20 Address of byte ) Object and the state transition of transferring value and information between two accounts . Ethereum's account consists of four parts :

(1) random number , A counter used to determine that each transaction can only be processed once

(2) The current Ethernet balance of the account

(3) The contract code of the account , If any

(4) Account storage ( The default is empty. )

Ether money (Ether) It is the main encryption fuel inside Ethereum , Used to pay transaction costs . generally speaking , Ethereum has two types of accounts : All external accounts ( Controlled by the private key ) And the contract account ( Controlled by contract code ). All external accounts have no code , People can send messages from an external account by creating and signing a transaction . Every time the contract account receives a message , The code inside the contract will be activated , Allow it to read and write to internal storage , And send other messages or create contracts .

Messages and transactions :

Ethereum's message is somewhat similar to bitcoin trading , But there are three important differences between the two :

First of all , Ethereum messages can be created by external entities or contracts , However, bitcoin transactions can only be created from the outside .

second , Ethereum messages can optionally contain data .

Third , If the recipient of Ethereum message is a contract account , You can choose to respond , This means that Ethereum messages also contain the concept of functions .

In Ethereum “ transaction ” A signed packet that stores messages sent from an external account . The transaction contains the recipient of the message 、 Used to confirm the sender's signature 、 Ether account balance 、 The data to be sent and the two are called STARTGAS and GASPRICE The numerical . In order to prevent exponential explosion and infinite loop of code , Each transaction requires a calculation step triggered by the execution of the code - Including the initial message and all messages raised during execution - Make restrictions .STARTGAS That's the limit ,GASPRICE Is that each calculation step needs to pay the miner's fee . If during the execution of the transaction ,“ Ran out of gas ”, All state changes return to the original state , However, the transaction costs already paid are not recoverable . If there is still gas left when the transaction is suspended , Then the gas will be returned to the sender . There are separate transaction types and corresponding message types for creating contracts ; The address of the contract is calculated based on the random number of the account and the hash of the transaction data .

An important result of the message mechanism : It's Ethereum “ First-class citizen ” property - Contracts have the same rights as external accounts , Including the right to send messages and create other contracts . This allows the contract to play multiple different roles at the same time , for example , Users can make decentralized organizations ( A contract ) A member of becomes an intermediary account ( Another contract ), A customized Lambert signature based on quantum proof for a paranoid use ( The third contract ) And an account that is secured by five private keys ( The fourth contract ) The co signing entity provides mediation services . The strength of Ethereum platform is that decentralized organization and agency contracts do not need to care about the type of account of each participant in the contract .

Ethereum state transition function :

Ethereum's state transition function :APPLY(S,TX) -> S', It can be defined as follows :

(1) Check whether the format of the transaction is correct ( That is, there is the correct value )、 Whether the signature is valid and whether the random number matches the random number of the sender's account . If no , Returns an error .

(2) Calculate transaction costs :fee=STARTGAS * GASPRICE, And determine the sender's address from the signature . Subtract transaction costs from the sender's account and increase the sender's random number . If the account balance is insufficient , Returns an error .

(3) Set the initial value GAS =STARTGAS, And subtract a certain amount of gas value according to the number of bytes in the transaction .

(4) Transfer value from sender's account to receiver's account . If the receiving account does not exist , Create this account . If the receiving account is a contract , The code that runs the contract , Until the code runs out or the gas runs out .

(5) If the value transfer fails because the sender's account does not have enough money or the code execution runs out of gas , Return to the original state , But there are transaction costs , The transaction fee is added to the miner's account .

(6) otherwise , Return all remaining gas to the sender , The consumed gas is sent to the miners as a transaction fee . for example , Suppose the contract code is as follows :

It should be noted that , In reality, the contract code uses the underlying Ethereum virtual machine (EVM) The code is written . The above contract is in our high-level language Serpent Written in language , It can be compiled into EVM Code . Suppose the contract memory is empty at the beginning , One is worth 10 The etheric , Gas is 2000, The gas price is 0.001 Etheric and 64 Bytes of data , The first 32-byte block represents the number 2 And the second CHARLIE After the transaction is sent , The processing process of the state transition function is as follows :

(1) Check whether the transaction is valid 、 Is the format correct .

(2) Check that the transaction sender has at least 2000*0.001=2 An ether . If there is , Subtract... From the sender's account 2 An ether .

(3) Initial setting gas=2000, Suppose the transaction length is 170 byte , The cost per byte is 5, subtract 850, So there's still 1150.

(4) Subtract... From the sender's account 10 An ether , Add... To the contract account 10 An ether .

(5) Run code . In this contract , It's easy to run the code : It checks that the contract memory index is 2 Has been used at , Notice that it is not used , Then set its value to CHARLIE. Suppose this consumes 187 Unit gas , So the remaining gas is 1150 - 187 = 963.

(6) Add... To the sender's account 963*0.001=0.963 An ether , Return to the final state . If there is no contract to receive the transaction , Then all transaction costs are equal to GASPRICE Multiplied by the byte length of the transaction , Transaction data has nothing to do with transaction costs . in addition , It should be noted that , Contract initiated messages can allocate gas limits to the calculations they produce , If the sub calculation runs out of gas , It only returns to the state when the message was sent . therefore , Like a deal , The contract can also set strict restrictions on the subcalculation it generates , Protect their computing resources .

Code execution :

The Ethereum contract code is written in a low-level stack based bytecode language , go by the name of “ Ethereum virtual machine code ” perhaps “EVM Code ”. The code consists of a series of bytes , Each byte represents an operation . generally speaking , Code execution is an infinite loop , Every time the program counter increases ( The initial value is zero ) Just do it once , Until the code is executed or an error is encountered ,STOP perhaps RETURN Instructions . Operations can access three types of data storage spaces :

·      Stack , A last in first out data store ,32 Byte values can be stacked , Out of the stack .

·      Memory , Infinitely scalable byte queue .

·      Long term storage of contracts , A key / Storage of values , Where the key and value are 32 Byte size , Different from the stack and memory reset at the end of the calculation , The stored content will remain for a long time .

Code can access values just as it accesses block header data , The data in the sender and the received message , The code can also return a byte queue of data as output .

EVM The formal execution model of the code is surprisingly simple . When the Ethereum virtual machine is running , Its complete computational state can be represented by tuples (block_state, transaction, message, code,memory, stack, pc, gas) To define , here block_state Is the global status that contains all account balances and storage . Each round of execution , By calling up the... Of the code pc( Program counter ) Bytes , The current instruction was found , Each instruction defines how it affects tuples . for example ,ADD Take the two elements out of the stack and put their sum on the stack , take gas( Gas ) Subtract... Together pc Add one ,SSTORE Take the top two elements out of the stack and insert the second element into the contract storage location defined by the first element , Also reduce the most 200 Of gas Value and will pc Add one , Although there are many ways to optimize Ethereum through real-time compilation , But the basic implementation of Ethereum can be implemented in hundreds of lines of code .

Blockchain and mining :

Although there are some differences , However, Ethereum's blockchain is similar to bitcoin blockchain in many ways . The difference between their blockchain architectures is , The Ethereum block contains not only transaction records and recent status , It also contains block serial number and difficulty value . The block confirmation algorithm in Ethereum is as follows :

(1) Check whether the previous block referenced by the block exists and is valid .

(2) Check whether the timestamp of the block is larger than the last block referenced , And less than 15 minute .

(3) Check the block serial number 、 Difficulty value 、 Transaction root , Uncle Gen and gas limit ( Many underlying concepts unique to Ethereum ) Whether it works .

(4) Check whether the workload certificate of the block is valid .

(5) take S[0] Assigned to... Of the previous block STATE_ROOT.

(6) take TX List of transactions assigned as blocks , Altogether n transaction . To belong to 0……n-1 Of i, State transition S[i+1]= APPLY(S[i],TX[i]). If an error occurs in any of the transformations , Or how long it takes the program to execute here (gas) More than the GASLIMIT, Returns an error .

(7) use S[n] to S_FINAL assignment , Pay the miners a block reward .

(8) Check S-FINAL Whether or not STATE_ROOT identical . If the same , Blocks are valid . otherwise , The block is invalid .

At first glance, this confirmation method seems inefficient , Because it needs to store all the states of each block , But in fact, the confirmation efficiency of Ethereum can be compared with that of bitcoin . The reason is that the state is stored in the tree structure (tree structure), For each block added, only a small part of the tree structure needs to be changed . therefore , generally speaking , Most of the tree structure of two adjacent blocks should be the same , So store data once , You can use pointers ( That is, subtree hash ) Quote twice . One is called “ Patricia tree ”(“Patricia Tree”) The tree structure can achieve this , This includes the modification of Merkel's tree concept , It is not only allowed to change nodes , You can also insert and delete nodes . in addition , Because all the status information is part of the last block , So there is no need to store all the block history - If this method can be applied to bitcoin system , After calculation, the storage space can be 10-20 Times the savings .


application :

In general , There are three applications on Ethereum . The first is financial applications , Provide users with a more powerful way to manage and participate in contracts with their money . Including sub currency , Financial derivatives , Hedging contracts , Savings wallet , will , Even some kind of comprehensive employment contract . The second category is semi financial applications , There is money here, but there are also important non money aspects , A perfect example is the self imposed reward for solving computational problems . Last , There are also complete non-financial applications such as online voting and decentralized governance .

Token system :

On chain token system has many applications , From sub currencies representing assets such as dollars or gold to corporate stocks , Individual tokens represent smart assets , Secure and unforgeable coupons , A token system used to reward points that has nothing to do with traditional values . Implementing token systems in Ethereum is surprisingly easy .

The key point is to understand all currency or token systems , Basically, it is a database with the following operations : from A Subtract from X Unit and put X The unit is added to B On , The premise is that :(1):A At least... Before trading X Company ,(2): The deal was A approval . Implementing a token system is to implement such logic into a contract .

use Serpent The basic code of implementing a token system in language is as follows :

This is essentially what this article will further describe “ The banking system ” A minimal implementation of the state transition function . Additional code needs to be added to provide the ability to distribute money in initial and other edge situations , Ideally, a function will be added to let other contracts query the balance of an address . That's enough .

Theoretically , The token system based on Ethereum as a sub currency may include an important function that bitcoin based chain coins lack : The ability to pay transaction fees directly in this currency .

The way to achieve this capability is to maintain an Ethernet account in the contract to pay transaction fees for the sender , By collecting the internal currencies used as transaction costs and auctioning them off in a running auction , The contract continuously injects capital into the Ethereum account . In this way, users need to use ether “ Activate ” Their accounts , But once there is ether in the account, it will be reused because each contract will recharge it .

Financial derivatives and currencies with stable values :

Financial derivatives are “ Intelligent contract ” The most common application of , It is also one of the easiest to implement in code . The main challenge of implementing financial contracts is that most of them need to refer to an external price publisher ; for example , A very demanding application is one used to hedge against ether ( Or other cryptographic currencies ) Smart contracts that fluctuate relative to the dollar , But the contract needs to know the price of ether against the dollar . The simplest way is through a specific agency ( For example, NASDAQ ) Maintenance of “ Data provided “ Contract for , The design of the contract enables the organization to update the contract as needed , An interface is provided to enable other contracts to obtain a reply containing price information by sending a message to the contract .

When these key elements are in place , Hedging contracts will look like the following :

(1) wait for A Input 1000 Ether money ..

(2) wait for B Input 1000 Ether money .

(3) Provide contracts by querying data , take 1000 The dollar value of ether , for example ,x dollar , Record to memory .

(4)30 Days later , allow A or B“ Reactivate “ Contract to send value x The dollar's ether ( Re query the data supply contract to obtain the new price and calculate ) to A And send the rest of the ether to B.

Such contracts have extraordinary potential in cryptography business . One of the problems that cryptography currency is often criticized is its price volatility ; Although a large number of users and businesses may need the security and convenience brought by cryptographic assets , But they are not willing to face the fall of assets during the day 23% The case of value . Until now, , The most common recommendation is that the issuer endorse the asset ; The idea is that the issuer creates a seed currency , For this seed currency, they have the right to issue and redeem , To give ( Offline ) Provide them with a unit specific related asset ( For example, gold , dollar ) People have a unit of sub currency . The publisher promises that when anyone returns a unit of cryptographic assets . Return the related assets of a unit . This mechanism enables any non cryptographic asset to be “ upgrade “ For cryptographic assets , If the publisher is trustworthy . However, in practice, developers are not always trustworthy , And in some cases, the banking system is too fragile , Or not honest enough to make such a service impossible to exist .

Financial derivatives offer an alternative . There will no longer be a single issuer that provides reserves to support an asset , Instead, there is a decentralized market of speculators who bet that the price of a cryptographic asset will rise . Different from the publisher , Speculators have no bargaining power , Because hedging contracts freeze their reserves in contracts . Note that this approach is not completely decentralized , Because we still need a trusted data source to provide price information , Although still controversial, this is still reducing infrastructure demand ( Different from the publisher , A price publisher does not need a license and seems to fall into the category of free speech ) And reducing the risk of potential fraud .

Identity and reputation system :

The earliest alternative currency , Domain name currency , Try to use a bitcoin like block chain to provide a name registration system , Where users can register their names with other data in a public database . The most common application cases are like ““( Or in the domain currency ,”bitcoin.bit“) The same domain name with a IP The domain name system corresponding to the address . Other applications include e-mail authentication systems and potentially more advanced reputation systems . Here is the basic contract for Ethereum to provide a name registration system similar to domain name coin :

The contract is very simple, that is, a database in the Ethereum network that can be added but cannot be modified or removed . Anyone can register a name as a value and never change . A more complex name registration contract will contain information that allows queries from other contracts “ Functional terms “, And the owner of a name ( The first registrant ) Mechanisms for modifying data or transferring ownership . You can even add reputation and trust network functions to it .

Decentralized storage :

In the past few years, there have been some popular online file storage startups , The most outstanding thing is Dropbox, It seeks to allow users to upload their hard disk backups , Provide backup storage services and allow users to access, so as to charge users monthly . However , At this point, the file storage market is sometimes relatively inefficient ; A cursory observation of existing services shows that , Especially in “ Mysterious Valley “20-200GB At a level where there is neither free space nor enterprise user discounts , The monthly price of mainstream file storage cost means paying the cost of the whole hard disk in one month . The Ethereum contract allows the development of a decentralized storage ecosystem , In this way, users can get a small profit by renting out their own hard disk or unused cyberspace , This reduces the cost of file storage .

The basic component of such a facility is what we call “ De centralization Dropbox contract “. The contract works as follows : First , Someone divides the data that needs to be uploaded into fast , Encrypt every piece of data to protect privacy , And build a Merkel tree . Then create a contract with the following rules , Every time N Block , The contract will extract a random index from the Merkel tree ( Provide randomness by using the hash of the last block that can be accessed by the contract code ).

Then give the first entity X Ethernet to support a payment with similar simplified verification (SPV) Proof of ownership of the block at a specific index in the tree . When a user wants to download his file again , He can use the micro payment channel protocol ( For example, every 32k Byte payment 1 Saab ) Restore file ; In terms of cost, the most efficient way is that the payer does not publish the transaction until the end , Instead, use a slightly more cost-effective transaction with the same random number in every 32k Bytes to replace the original transaction .

An important feature of this agreement is , Although it looks like a person trusts many random nodes that are not ready to lose files , But he can divide the document into many small pieces through secret sharing , Then, through the monitoring contract, it is known that each small block is still saved by a node . If a contract is still paying , Then it provides evidence that someone is still saving the file .

Decentralized autonomous organization :

Generally speaking “ Decentralized autonomous organization (DAO, decentralized autonomous organization)” The concept of is a virtual entity with a certain number of members or shareholders , Rely on, for example 67% More to decide how much to spend and modify the code . Members collectively decide how the organization allocates funds . The method of allocating funds may be a reward , Wages or more attractive mechanisms, such as rewarding work with internal currency . This simply uses cryptography block chain technology to fundamentally copy the legal meaning of traditional companies or non-profit organizations to achieve enforcement . So far, many people around DAO The discussion is all about a shareholder with dividends and tradable shares “ Decentralized autonomous companies (DAC,decentralized autonomous corporation)” Of “ capitalist ” Pattern ; As an alternative , One is described as “ Decentralized autonomous communities (decentralized autonomous community)” The entity will give all members equal rights in decision-making and require 67% The majority agreed that . Everyone can only have one membership, which needs to be enforced by the group .

Here's how to implement... In code DO The outline of . The simplest design is a piece of code that can be modified by itself if two-thirds of the members agree . Although the code is theoretically immutable , However, by placing the code trunk in a separate contract and pointing the address of the contract call to a changeable storage, it is still easy to bypass the obstacles and make the code modifiable , In such a DAO There are three types of transactions in the simple implementation of contracts , Distinguished by the data provided by the transaction :

(1)[0,i,K,V]  The registration index is i The storage address index for is K to v Suggestions for changes to the contents of .

(2)[0,i]  Register for suggestions i Vote for .

(3)[2,i]  If there are enough votes, confirm the proposal i.

Then the contract has specific terms for each item . It will maintain a record of all open storage changes and a table of who voted . There is also a table of all members . When any change to the stored content is agreed by a two-thirds majority , A final transaction will execute this change . A more complex framework will add built-in voting functions to realize, such as sending transactions , Increase or decrease members , Even provide voting representatives such as appointed democracy ( That is, anyone can entrust another person to vote on his behalf , And this delegation is transitive , So if A Commissioned B then B Commissioned C that C Will decide A Vote for ). This design will make DAO Grow organically as a decentralized community , So that people can finally hand over the task of selecting suitable candidates to experts , Different from the current system , As community members continue to change their standing in line, experts will easily appear and disappear over time . An alternative model is decentralized companies , Any account there can have 0 To more shares , The decision requires the consent of a two-thirds majority of the shares . A complete framework will include asset management functions - You can submit orders for buying and selling shares and accept such orders ( The premise is that there is an order matching mechanism in the contract ). Representatives still exist in a democratic way of appointment , Produced “ Board of directors ” The concept of .

More advanced organizational governance mechanisms may be implemented in the future ; Now a decentralized organization (DO) It can be from decentralized autonomous organizations (DAO) Begin to describe .DO and DAO The difference is vague , A general dividing line is whether governance can be through a political process or “ Automatically ” Process realization , A good intuition test is “ No common language ” standard : If two members don't speak the same language, can the organization work normally ? obviously , A simple traditional holding company will fail , Such as bitcoin protocol is likely to succeed , Robin · Hansen's “futarchy”, A mechanism to achieve organizational governance by predicting the market is a real illustration “ autonomous ” A good example of what type of governance might look like . Note that one does not have to assume that all DAO More than all DO superior ; Autonomy is just a tool that has great advantages in some specific scenarios , But paradigms that may not work elsewhere , Many half DAO Possible .

website :

Want to get the coinage technology and a full set of virtual machine information

Blockchain technology exchange QQ Group :756146052   remarks :CSDN

Wechat of Yin Cheng College : remarks :CSDN

版权声明:本文为[Yin Cheng]所创,转载请带上原文链接,感谢。