In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to realize the intelligent contract for solidity language development". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
A simple smart contract
In Solidity, an intelligent contract consists of a set of code (functions of the contract) and data (the status of the contract). The smart contract is located at a special address on the ethernet block chain. The uint storedData*;* line declares a state variable named storedData with a type of uint (256bits unsigned integer). You can think of it as a storage unit in a database, just like managing a database, which can be queried and modified by calling functions. In Ethernet Square, usually only the owner of the contract can do this. In this example, the functions set and get are used to modify and query the value of the variable, respectively.
Like many other languages, when accessing state variables, you do not need to add this. Such a prefix.
The contract does not do much (limited to the infrastructure of Ethernet Fong), just allowing anyone to store a number. And anyone in the world can access this number, without a (reliable) way to protect your published numbers. Anyone can call the set method to set a different number to overwrite the number you publish. But your numbers will remain in the history of the blockchain. Later we will learn how to add an access restriction so that only you can modify this number.
Let's start with a very basic example. Don't worry that you don't know anything yet. We'll learn more details step by step.
Example of Storagecontract SimpleStorage {uint storedData; function set (uint x) {storedData = x;} function get () constant returns (uint retVal) {return storedData;}} token
The next contract will implement a cryptocurrency in the simplest form. Taking money from the air is no longer a magic trick, and of course only the person who created the contract can do it (it's easy to use other currency issuance models, but with differences in details). And anyone can send money to others without registering a user name and password, as long as there is a pair of public and private keys of Ethernet Fong.
Note
This is not a good example for an online solidity environment. Try this example if you use an online solidity environment. When the function is called, the address of the from cannot be changed. So you can only play the role of a seignior. you can mint money and give it to others, not others. This online solidity environment will be improved in the future.
The contract Coin {/ / keyword "public" enables variables to be accessed from outside the contract. The address public minter; mapping (address = > uint) public balances;// event allows light clients to respond to changes efficiently. Event Sent (address from, address to, uint amount); / / the code for this constructor is only run when the contract is created. Function Coin () {minter = msg.sender;} function mint (address receiver, uint amount) {if (msg.sender! = minter) return; balances [receiver] + = amount;} function send (address receiver, uint amount) {if (balances [msg.sender]
< amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; Sent(msg.sender, receiver, amount); }} 这个合约引入了一些新的概念,让我们一个一个来看一下。 address public minter; 这行代码声明了一个可公开访问的状态变量,类型为address。address类型的值大小为160 bits,不支持任何算术操作。适用于存储合约的地址或其他人的公私钥。public关键字会自动为其修饰的状态变量生成访问函数。没有public关键字的变量将无法被其他合约访问。另外只有本合约内的代码才能写入。自动生成的函数如下: function minter() returns (address) { return minter; } 当然我们自己增加一个这样的访问函数是行不通的。编译器会报错,指出这个函数与一个状态变量重名。 下一行代码 mapping (address =>Uint) public balances; creates a state variable for public, but its type is more complex. This type maps some address to unsigned integers. Mapping can be thought of as a hash table, and the value corresponding to each possible key is virtually initialized to all 0. 0. This analogy is not very rigorous, and for a mapping, it is impossible to get a linked list containing all its key or value. So we have to remember for ourselves what we have added to mapping. A better way is to maintain such a linked list, or to use other more advanced data types. Or use mapping only in scenarios that are not affected by this defect, as in this example. In this example, the access function generated by the public keyword will be more complex, and the code is roughly as follows:
Function balances (address _ account) returns (uint balance) {return balances [_ account];}
We can easily query the balance of a particular account through this function.
Event Sent (address from, address to, uint value); this line declares an "event". Triggered by the last line of code of the send function. The client (server-side applications also apply) can listen to these events triggered by the blockchain with very low overhead. When the event is triggered, the listener will receive the from,to,value parameter values at the same time, which can be easily used to track the transaction. To listen for this event, you can use the following code:
Coin.Sent () .watch ({},', function (error, result) {if (! error) {console.log ("Coin transfer:" + result.args.amount + "coins were sent from" + result.args.from + "to" + result.args.to + ".") Console.log ("Balances now:\ n" + "Sender:" + Coin.balances.call (result.args.from) + "Receiver:" + Coin.balances.call (result.args.to));}}
Notice how the automatically generated balances function is called on the client side.
Here is a special function, Coin. It is a constructor that runs when the contract is created and cannot be called afterwards. It permanently stores the address of the contract creator. Msg (as well as tx and block) is a magical global variable that contains attributes that belong to the blockchain that can be accessed by contract code. Msg.sender always holds the address of the external caller of the current function.
Finally, the functions that are really called by the user or other contract to complete the function of this contract are mint and send. If someone other than the contract creator calls mint, nothing happens. Send can be called by anyone (with a certain number of tokens) to send some coins to others. Note that when you send some tokens to an address through the contract, you won't see anything if you query that address in the blockchain browser. The balance change caused by sending the token is only stored in the data store of the token contract. Through the event, we can easily create a "blockchain browser" that can track your new currency transactions and balances.
Block chain foundation
For programmers, the concept of blockchain is not difficult to understand. Because some of the most difficult things to understand (mining, hashing, elliptic curve encryption, peer-to-peer networks, etc.) are just to provide a range of features and guarantees. You just need to accept these existing features and you don't need to care about the underlying technology. Just like if you just want to use Amazon's AWS, you don't need to know how it works inside.
Transaction / transaction
Blockchain is a globally shared, transactional database. This means that everyone involved in the network can read the records. If you want to modify something in this database, you must create a transaction and get confirmation from everyone else. The word transaction means that the changes you want to make (if you want to change both values at the same time) can only be fully implemented or not at all.
In addition, when your transaction is applied to this database, other transactions cannot modify the database.
For example, imagine a table that lists the balances of all accounts in an electronic currency. When a transfer request from one account to another occurs, the transactional nature of the database ensures that the amount deducted from one account is added to another. If for some reason it is impossible to increase the amount to the target account, there will be no change in the amount of the source account.
In addition, a transaction is cryptographically signed by the sender (creator). This measure intuitively adds access protection to specific modifications to the database. In the case of electronic money, a simple check ensures that only the holder of the account key can transfer money out of the account.
block
A major problem to be solved by the blockchain is known in Bitcoin as a "two-flower attack". What happens when there are two transactions on the Internet that run out of money in one account? A conflict?
The simple answer is that you don't need to care about it. These transactions are sorted and packaged into "blocks" and then executed and distributed by all participating nodes. If two deals conflict with each other, the lower-ranked deal will be rejected and removed from the block.
These blocks are arranged in a linear sequence according to time. This is the origin of the word "blockchain". Blocks are added to the chain at fairly regular intervals. For Tai Tai Fong, the interval is about 17 seconds.
As part of the "sequential selection mechanism" (often referred to as "mining"), a block chain may be rolled back from time to time. But this only happens at the end of the chain. The more blocks involved in the rollback, the less likely it is to occur. So your deal may be rolled back or even removed from the blockchain. But the longer you wait, the less likely it is to happen.
Ethernet Square Virtual Machine Overview
The Ethernet Square Virtual Machine (EVM) is the operating environment for intelligent contracts in Ethernet Square. Not only is it sandboxed, it is actually completely isolated, meaning that code running inside the EVM cannot touch the network, file system, or other processes. Even smart contracts have limited access to other smart contracts.
Account
There are two types of accounts in Tai Fong, which share the same address space. External accounts, which are controlled by public-private key pairs (human). Contract accounts, which are controlled by the code stored in the account.
The address of the external account is determined by the public key, and the address of the contract account is determined when the contract is created (this address is calculated from the address of the contract creator and the number of transactions sent out by that address, which is also known as "nonce").
Apart from the fact that contract accounts store codes and external accounts do not, these two types of accounts are the same for EVM.
Each account has a persistent storage in the form of key-value. Among them, key and value are both 256 bits long and are called storage.
In addition, each account has an etheric balance (in "Wei"), which can be changed by sending it transactions with Ethernet coins.
Trade
A transaction is a message sent from one account to another (it may be the same account or zero account, see below). Transactions can contain binary data (payload) and Ethernet coins.
If the target account contains a code, the code is executed, and payload is the input data.
If the target account is a zero account (account address is 0), the transaction will create a new contract. As mentioned above, the contract address is not a zero address, but is calculated from the address of the contract creator and the number of transactions issued by that address (known as nonce). The payload that creates the contract transaction is executed as EVM bytecode. The output of the execution is permanently stored as a contract code. This means that in order to create a contract, you don't need to send the real contract code to the contract, but send the code that returns the real code.
Gas
A certain amount of gas,gas is charged for each transaction on Ethernet Square in order to limit the amount of work required to execute the transaction and to pay for it. When EVM executes a transaction, the gas is gradually consumed according to specific rules.
The gas price (etheric currency meter) is set by the transaction creator, and the transaction fee required to send the account in advance is gas price * gas amount. If there is any gas left at the end of the execution, the gas will be returned to the sending account.
No matter where it is executed, once the gas is exhausted (for example, reduced to a negative value), an out-of-gas exception will be triggered. All state changes made by the current calling frame will be rolled back.
Storage, main memory and stack
Each account has an area of persistent memory called storage. It is in the form of key-value,key and value with a length of 256bits. In the contract, the storage of the account cannot be traversed. Compared with the other two, the read operation of storage is relatively expensive, and the modification of storage is more serious. A contract can only read and write to its own storage.
The second area of memory is called main memory. Each time the contract executes a message call, there is a new piece of main memory that has been cleared. Main memory can be addressed at a byte granularity, but the read and write granularity is 32 bytes (256 bits). The cost of operating main memory increases as it grows (square level).
EVM is not a register-based virtual machine but a stack-based virtual machine. So all calculations are performed in an area called a stack. The stack has a maximum of 1024 elements, each with 256 bits. Access to the stack is limited to its top by allowing one of the top 16 elements to be copied to the top of the stack, or swapping the top element of the stack with one of the following 16 elements. All other operations can only take the top two (or one, or more, depending on the specific operation) elements and press the results on the top of the stack. Of course, you can put the elements on the stack into storage or main memory. However, you cannot access only the element of the specified depth on the stack, and all elements above the specified depth must be removed from the stack before that.
Instruction set
EVM's instruction set is deliberately kept to a minimum to avoid incorrect implementations that could lead to consensus problems as much as possible. All instructions are for operations of the basic data type 256 bits. Have common arithmetic, bit, logic and comparison operations. Conditional and unconditional jumps can also be achieved. In addition, the contract can access the relevant attributes of the current block, such as its number and timestamp.
Message call
A contract can invoke another contract through a message call or send etheric currency to a non-contract account. Message calls are very similar to transactions in that they both have a source, a target, a data payload, ethernet, gas, and return data. In fact, each transaction can be thought of as a top-level message call, which in turn produces more message calls.
A contract can determine the allocation of the remaining gas. For example, how much gas is used for internal message calls, or how much gas is expected to be retained. If an out-of-gas exception (or other exception) occurs during an internal message call, the contract is notified and an error code is pressed on the stack. In this case, the gas of the internal message call is exhausted. In solidity, the contract that initiates the call in this case triggers a human exception by default. This exception prints out the call stack. As mentioned earlier, the invoked contract (as well as the contract that initiated the call) will have new main memory and be able to access the payload of the call. The call payload is stored in a separate area called calldata. After the call execution is completed, the returned data will be stored in a piece of memory pre-allocated by the caller.
The number of call layers is limited to 1024, so for more complex operations, we should use loops instead of recursion.
Code calls and libraries
There is a special type of message call called callcode. It is almost exactly the same as a message call, except that the code loaded from the target address will run in the context of the contract that initiated the call.
This means that a contract can dynamically load code from another address at run time. The storage, the current address and the balance all point to the contract that initiated the call, and only the code is obtained from the called address.
This allows Solidity to implement "libraries". Reusable library code can be applied to the storage of a contract and can be used to implement complex data structures.
Journal
At the block level, a special indexable data structure can be used to store data. This feature is called logging, and Solidity uses it to implement events. Log data cannot be accessed after the contract is created, but it can be accessed efficiently from outside the blockchain. Because some of the log data is stored in the Bloom filter (Bloom filter), we can search the logs efficiently and safely, so those network nodes (light clients) that do not download the entire blockchain can also find these logs.
Create
Contracts can even create other contracts with a special instruction (rather than simply making a call to zero address). A call to create a contract differs from a normal message call in that the result of the execution of the payload data is treated as code, and the caller / creator gets the address of the new contract on the stack.
Self-destruction
The contract code is removed from the block chain only if the contract at an address performs a self-destruct operation. The remaining etheric coins on the contract address are sent to the specified destination, and then its storage and code are removed.
Note that even if the code for a contract does not contain self-destruct instructions, this can still be done through code calls (callcode).
If you want to learn DApp development efficiently, you can visit the most popular online interactive tutorials offered by Huizhi.com:
An introduction to Ethernet Square DApp for beginners in blockchain
Practice of e-commerce application development in eTaifang with blockchain + IPFS+Node.js+MongoDB+Express decentralization
This is the end of the content of "how to realize the Intelligent contract for solidity language Development". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.