Digital currency Development Part I: Serenity Tutorial for deep abstraction algorithms

Source: Internet
Author: User
Tags abstract bitmask data structures hash pow valid

Blockchain Enthusiast (qq:53016353)

We have been openly continuing to improve the plan and long-term development roadmap for the digital currency development agreement, which is also from the experience gained from errors that were not dealt with immediately before or after the release of the 1.0 release. In any case, the cyclical development of the core protocol for digital currency development has been restarted, the homestead phase is soon to come, and we have quietly begun to develop a concept prototype (PoC), with the goal of developing the largest milestone in the roadmap: Serenity.

Serenity will have two main features: a depth abstraction, a feature I first discussed here, and Casper, a margin-based proof of interest (PoS) algorithm. In addition, we are exploring a smooth deployment scalability (scalability) improvement approach, at least a scaffold, while fully addressing the concerns of parallelism here-running in a private-chain environment, the performance of the Digital Money development node on top of a multi-core CPU proprietary server will have an immediate and significant boost, Even the scalability of the public chain can be seen in 2 to 5 times times the increase. Over the past few months, Casper's research and formalized work on scalability and abstract improvements (eg. EIP101) are advancing fast, with the participants having me, Vlad Zamfir, Lucius Greg Meredith and some others. Now I am pleased to announce that the first conceptual prototype of the Serenity phase, although the things that can be done are very limited only for testing, has been completed.


Run the Python test.py in the Ethereum directory to run the concept prototype (don't forget to download and install the newest develop branch from Https://github.com/ethereum/serpentSerpent first), If you see this output, the following is true:


vub@vub-thinkpad-x250 15:01:03 Serenity/ethereum:python test.py
REVERTING 940534 gas from account 0x0000000000000000000000000000000000000000 to account 0X98C78BE58D729DCDC3DE9EFB3428820990E4E3BF with Data 0x
Warning (file "casper.se.py", line 0, Char): warning:function return type inconsistent!
Running with maximum nodes
Warning (file "casper.se.py", line 0, Char): warning:function return type inconsistent!
Warning (file "casper.se.py", line 0, Char): warning:function return type inconsistent!
Length of Validation code:57
Length of Account code:0
Joined with index 0
Length of Validation code:57
Length of Account code:0
Joined with index 1
Length of Validation code:57


In a block every 5 seconds, using the Casper+serenity protocol, this program simulates the operation of the 13 nodes; This simulation is already close to the limit that the current client can handle, but note: (i) This is written by Python, C + + and go implementations are likely to perform better , and (ii) All of these nodes are running on a single computer at the same time, so you have reason to believe that in a more "normal" environment, the Python version of Casper can handle about 169 nodes (but on the other hand, we want the consensus to cost much less than the 100% CPU footprint, So this two-point note doesn't mean you can expect Casper to work with thousands of nodes. )。 If your computer is too slow to handle 13 nodes, try Python test.py 10来 to simulate 10 nodes (or Python test.py 7来 simulate 7 nodes, you know). Of course, the study of improving Casper efficiency continues, although this improvement may be at the cost of slowing the convergence of finality (finality), and these problems will be solved gradually. The network.py file simulates a basic peer to face network interface, and the next job is to replace it with a real computer running on a real network.


The program code is split into several main files:


Serenity_blocks.py-Describes the block class, the State class, and the code for the block and transaction level status transfer functions (one times simpler than the previous version).
serenity_transactions.py-describes the code of the transaction (one-fold simpler than before).
The serpent realization of the Casper.se.py-casper contract encourages the correct betting behavior.
Bet.py-casper's betting logic and a complete client implementation.
ecdsa_accounts.py-account-related code allows you to simulate the current account validation logic on serenity.
test.py-Test Script
config.py-Parameter configuration
vm.py-Virtual machines (fastvm.py provides a faster implementation)
network.py-Network simulation
In this article, we only discuss the features of deep abstraction, so the key files are serenity_blocks.py, ecdsa_accounts.py, and Serenity_ transactions.py; In the next article on Casper, casper.se.py and bet.py will be the focus.


Abstract of the account
There are currently two types of accounts in digital currency development: Externally owned accounts, controlled by private keys, and contract accounts, controlled by code. For externally owned accounts, we have specified a special digital signature algorithm (SECP256K1 Elliptic curve signature) and an ordinal system (nonce), which requires that each transaction must contain a number 1 larger than the previous trading sequence to prevent replay attacks (replay attacks). The main change we made to improve the abstraction was that there were no more accounts of two different types, but rather a single-contract account. There will be a special "entry" account, 0x0000000000000000000000000000000000000000, where anyone can initiate a transaction from this account. Therefore, the agreement will no longer contain the account verification logic of the signed +nonce, the user must use the contract to protect their own accounts.


The simplest and most effective of such contracts may be elliptic Curve Digital signature verification contracts, which can provide exactly the same functionality as now: only transactions with valid signatures and serial numbers can be verified, and the serial number increases by 1 after the successful trading. The code for this contract is as follows:


# We assume that data takes the following schema:
# bytes 0-31:v (ECDSA sig)
# bytes 32-63:r (ECDSA sig)
# bytes 64-95:s (ECDSA sig)
# bytes 96-127:sequence Number (formerly called "Nonce")
# bytes 128-159:gasprice
# bytes 172-191:to
# bytes 192-223:value
# bytes 224+: Data


# Get the hash for transaction signing
~mstore (0, ~txexecgas ())
~calldatacopy (+, ~calldatasize ()-96)
~mstore (0, ~sha3 (0, ~calldatasize ()-64))
~calldatacopy (32, 0, 96)
# call Ecrecover contract to get the sender
~call (5000, 1, 0, 0, 128, 0, 32)
# Check Sender correctness; Exception if not
If ~mload (0)! = 0x82a978b3f5962a5b0957d9ee9eef472ee55b42f1:
~invalid ()
# Sequence Number Operations
With minusone = ~sub (0, 1):
With CURSEQ = Self.storage[minusone]:
# Check Sequence Number correctness, exception if not
If ~calldataload (*)! = Curseq:
~invalid ()
# Increment Sequence Number
Self.storage[minusone] = curseq + 1
# make the Sub-call and discard output
with x = ~msize ():
~call (msg.gas-50000, ~calldataload, ~calldataload (192), ~calldatasize ()-224, X, 1000)
# Pay-Gas
~mstore (0, ~calldataload (128))
~mstore (+, (~txexecgas ()-Msg.gas + 50000))
~call (12000, ether, 0, 0, 64, 0, 0)
~return (x, ~msize ()-X)


This code is the contract code of the user account, if the user wants to send a transaction from their account, they will first send a transaction from address 0 to this account, the transaction data will include ECDSA signature, serial number, gas price, destination address, amount and real transaction data as shown in the above code. The contract code checks the trade gas limit and the signature of the data, and then checks the transaction sequence number, and if neither is the problem, add one to the saved sequence number, send the desired message, and then send another message to pay the gas charge as the end (note that the miner can statically analyze the contract code of the account, If the trading account contract finally does not pay gas can refuse processing).


This change of serenity has a very important consequence that all transactions in the system (as long as the basic format is satisfied) are valid. At this stage, the invalid transaction will only have no effect in serenity (the invalid in the previous example is an unused opcode, which causes the program to execute an immediate exit). This means that the transaction is packaged into chunks that are no longer guaranteed to be really executed, and as a remedy, each transaction will have a receipt record (receipt entry), indicating whether it executed successfully via a return code: 0 indicates that the trade was not executed due to gas restriction, and 1 indicated that the transaction was executed but the error 2 indicates successful execution of the transaction. The receipt record can also provide more information, such as the return value of the transaction (which now has automatic logging) or a log created by itself,


The main benefit of this change is that users can innovate freely in the area of account strategy. Possible directions include:


Bitcoin-style multi-signature, the account requires a transaction with multiple private key signatures, instead of receiving one signature at a time, and then temporarily storing the intermediate results in the blockchain.
Other elliptic curves, including ed25519.
Better integration of advanced cryptographic algorithms such as Ring signature (ring signature), Threshold signature (threshold signature), 0 knowledge proof, etc.
A more advanced serial number scheme allows for higher levels of parallelism, allowing users to make multiple transactions from one account at the same time, and to quickly package these transactions. Think of the traditional serial number and bitmask (bitmask) if the combination happens. We can also use a variety of witty methods to check the validity of the time stamp or chunk hash value.
Based on UTXO's token management, some users are Yuan Qi of privacy and do not like the digital currency development to manage the ownership of tokens using accounts rather than Bitcoin's "unused trade outputs" (unspent transaction output, UTXO) models. Now you can build a de facto utxo-based system in digital currency development, and serenity no longer explicitly treats one of them in a special way.
Innovation in payment schemes, for some dapp, "payment by contract" may be more useful than "paid by the user", and users may not have the etheric currency. Now Dapp can implement this payment model. If a miner can do static analysis of its code and be sure that they can get paid, the miners will accept the deal (essentially, we achieve what Rookstock wants to do with an optional author (author-pay), but through a more abstract and flexible approach).
Better integration with applications such as digital currency development alarms, the checking code for an account does not have to check the signature, it can check the Merkle proof of receipts, or the status of other accounts, and so on.
These scenarios are presented in order to illustrate the main point, by abstracting all of these additional mechanisms can be more easily implemented, no longer need to create a "transfer layer" to feed the information to the digital currency to develop the default signature system. When no application is special, each application is special.


A particularly interesting result: in the design of serenity, digital currency development will have optional quantum security. If you're afraid the NSA will secretly have a quantum computer and want to make your account more secure, you can switch to using Lamport signatures at any time. The transition to POS mechanism further consolidates security, even though the world's NSA has quantum computers that they cannot use to implement 51% attacks. In the protocol layer developed in the digital currency the only remaining cryptographic security hypothesis is only the nature of the SHA3 collision (collision-resistance).


Another consequence of these changes is that trading data becomes simpler. The transaction will replace the current nine with four fields: Destination address, data, initial gas, and initialization code. Destination address, data and initial gas as now, "initialization code" is a field that can be used to save the creation code of the target Address account contract.


This mechanism is needed for the following reasons. At present, the development of digital currency is of an important nature, is allowed to a non-existent account transfer. In order to create a contract on the blockchain to accept the etheric currency, you do not need to hold any etheric currency beforehand. In order to implement this property in serenity, we allow the account address to be deduced from its initialization code in advance, using the formula SHA3 (creator + initcode)% 2**160. Here creator is the account that created the contract (default is the account with the address 0), and Initcode is the initialization code of the contract (the result of this code will be the code of the account contract, as in the present create). So you can make this initialization code in the local Mister, calculate its address, and then let the other person transfer to that address. Then once you want to make the first deal from this address, you can include the initialization code in the transaction, and it will be executed automatically and create the account (this logic implementation code is here) before the real transaction executes.


The abstraction of chunks
Another clean separation that will be implemented in Serenity is to completely separate chunks (just a bunch of deals), state (for example, the storage area of the contract, the code and the account balance) and the consensus layer. Consensus incentives are implemented within the contract, and if you want to motivate, the target of the consensus level (e.g. POW, bet) should be included in the deal that is destined for the consensus incentive management contract.


This should make it easier for you to replace Serenity in Casper code with other consensus algorithms-tendermint, honeybadgebft, subjective consensus, and even ordinary pow. We welcome the research in this direction and hope to be the most flexible.


Stored abstractions
At present, the "State" data of the digital currency development system is actually quite complex, including these parts:


Balance, code, nonce, and account storage area
Gas cap, difficulty, block height, timestamp
The hash value of the last 256 blocks
When executing block code, the trade index needs to be saved, the receipt tree (receipt tree, receipt is a concept in EVM) and the gas currently consumed.
These data structures exist in many places, including block state transfer functions, state trees, chunk size, and previous chunk headers. In serenity these will be greatly simplified: although many of the data will still exist, they will be transferred to a special contract; therefore, the only "state" will continue to exist in the form of a tree, mathematically as a mapping of the shape {address: {Key:value}}. The account will be a few trees, the account contract code will be stored in the primary key (key) as "" (Sstore can not be modified), the balance will exist in the special "Ethereum contract", and the serial number will be determined by each account how to save. Receipts will also be transferred to the contract store, and they will be stored in a "log contract" where the content is overwritten in each chunk.


This allows the state object in the code implementation to be greatly simplified. Now there is only one two-level trie left. Scalability aspects of the upgrade may require an increase of three trie (Shard ID, address, primary key), which is not yet determined, but even this complexity is much lower than now.


It is important to note that transferring the etheric currency into a contract management is not the whole of the etheric currency abstraction. In fact, a controversial view is that this is not a significant improvement over the status quo, as it is still retained in order to be compatible with the etheric currency opcode (call,balance with the value parameter, etc.). In a way, it's just a reorganization of data storage.


Plans for the future
In the second conceptual prototype, we plan to make the abstraction a step further. Current state transfer functions for block and transaction levels are still quite complex (e.g. update receipts, gas limits, trade indices, Block heights, State root nodes), and our goal is to create a "portal" object for trading to handle all of the additional "boilerplate logic" required for each of these transactions, as well as "block start" and " The entrance to the end of the block. The ultimate goal in theory is to find a protocol with only one entry point, so that the state transfer function only needs to send a message to the entry point that contains the chunk content data from the zero address. The purpose of this is to minimize the size of the consensus critical part of the client implementation (Consensus-critical client implementation) and push as much logic as possible into the digital currency development itself. So even in order to achieve our goal of trading speed and scalability, we need to adopt a radical development system that accepts hard forks and a certain amount of new complexity, as well as a way to ensure that the multi-client pattern of digital currency development can be sustained without significant additional development work and security audits.


In the long run, I intend to continue developing conceptual prototypes on Python, and the Casper team will work together to improve the efficiency of the Protocol and prove its security and correctness. At some point, this protocol will mature enough to deal with a publicly available form of test network, which may have real value, providing incentives for people to identify Casper vulnerabilities, as a true chain inevitably suffers. This is just the first step, but it's a very important step, and it's a sign that our research on proof of rights and deep abstraction has finally changed from talking to mathematical formulas and blog posts on whiteboards to working code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.