In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
What this article shares with you is about the realization principle of blockchain in Oracle. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
1. Why do intelligent contracts need predictor / Oracle?
The logic performed in a smart contract cannot perform anything outside the blockchain, for example, it cannot access web services on the Internet. The only way for external data to enter a smart contract is to place it in a transaction and trigger an update of the blockchain status by sending a new transaction to the system.
Try to think about what would happen if the smart contract could access an external API to obtain data during execution.
If you deploy this contract today, API may return the following data:
{"foo": "bar"}
But when you redeploy tomorrow, API may return new data, such as:
{"foo": "baz"}
It is conceivable that if someone synchronizes the etherfang block chain one month later, the intelligent contract will be executed, but the response data of API is different from that of a month ago, which will cause the new synchronization block chain state to be different from the previously existing node state.
This is no longer a completely self-defined blockchain. Go through the same synchronization process, but my block chain is different from yours!
Let's put it another way: given a set of blocks, a node must be able to reproduce the final state of the block chain from scratch without the need for an Internet connection.
So what does this mean for developers of smart contracts? Oralce (prophecy machine), developers must build a prophecy machine to realize the interaction between intelligent contracts and the outside world.
2. How to implement a simple prediction machine / Oracle?
Now let's create a simple prophecy machine / Oracle to pass external weather data into the smart contract:
On the lowest blockchain platform, we need to deploy a smart contract that has a method updateWeather () to update the weather status, which can only be called from the address in the contract whitelist. The updateWeather method takes the weather data as a parameter, triggers a Taifang contract event and takes the weather data as a parameter of the event, so that the JavaScript application can subscribe to the event and get asynchronous notification.
At the same time, we will create two nodejs processes, one of which is the prophecy machine / Oracle, whose implementation logic is to periodically poll the third-party weather API to obtain weather data, and then submit the weather data to the smart contract for historical audit.
Another nodejs process is responsible for subscribing to weather events for smart contracts and then outputting event parameters on the console. As mentioned earlier, weather events are triggered whenever the prophecy machine / Oracle calls the contract's updateWeather () method.
It should be pointed out that in order to understand the core implementation ideas of the prophecy machine, the following code is simplified and eliminates the necessary error handling, so it is not applicable to the production environment.
The source code is here:
Prophecy machine contract-https://github.com/decentorganization/weather-oracle-contract
Oracle service-https://github.com/decentorganization/weather-oracle-service
Next, we will explain in detail the implementation of this simple prophecy machine.
3. Realization of intelligent contract of prophecy machine.
The smart contract has a public oracleAddress state variable that represents the account address of the updateWeather method that allows the smart contract to be called, which we assign in the constructor:
Contract WeatherOracle {address public oracleAddress; constructor (address _ oracleAddress) public {oracleAddress = _ oracleAddress;} / /.}
Next we will define the weather event, which will be triggered when the weatherUpdate () call succeeds. Also for simplicity, let's simply attach a string parameter that represents the temperature to this event.
Event WeatherUpdate (string temperature)
Finally, we will implement the updateWeather () method. Its visibility is public, which means that this method can be called externally:
Function updateWeather (string temperature) public {require (msg.sender = = oracleAddress); emit WeatherUpdate (temperature);}
Notice the require statement. This method is allowed to continue only if the calling address (msg.sender) is the same as the whitelist address (oracleAddress), otherwise the transaction will be rolled back.
All right, it's that simple.
4. Prophecy machine service
Our oracle machine is a simple nodejs service. It uses the request library to call the external weather API, parse the API's response, construct and submit the transaction to the smart contract, then wait a while, repeat the above work, and so on.
Starting with accessing API, let's put the address of API in an environment variable to avoid modifying the source code when switching between development / production environments:
Const options = {uri: process.env.WEATHER_URL, json: true}; const start = () = > {request (options) .then (parseData) .then (updateWeather) .then (restart) .catch (error);}
The following code is used to parse the response result of API:
Const parseData = (body) = > {return new Promise ((resolve, reject) = > {const temperature = body.main.temp.toString (); resolve ({temperature});});}
All you need to do now is to construct an Ethernet square transaction that calls the updateWeather () method of the smart contract. Note that account () is an asynchronous method that loads an ethernet account, and contract is a js object that contains the deployment address and ABI interface data of the previously deployed WeatherOracle smart contract. These functions related to smart contracts come from the famous web3 development package:)
Const updateWeather = ({temperature}) = > {return new Promise ((resolve, reject) = > {account () .then (account = > {contract.updateWeather (temperature, {from: account}, (err, res) = > {resolve (res);}
Finally, we just need to restart the process after the specified timeout. The wait () function will be resolved after the specified timeout.
Const restart = () = > {wait (process.env.TIMEOUT) .then (start);}
Got it! The above code implements a simple service that fetches data from API and then enters a smart contract.
Note:
When we construct the ethersquare transaction, we use {from:account} to specify the calling account, and the account to which account points needs to have some etheric currency to pay the transaction fee.
We use environment variables to configure a private key to instantiate the account object. This private key must be the private key corresponding to the whitelist address passed in when deploying the WeatherOracle smart contract.
5. Services for the utilization of weather events
This is another simple nodejs service. Similarly, contract is a js object that contains the deployment address and ABI information of the contract. Calling WeatherUpdate and passing in a callback is all the code for us to subscribe to weather events:
Const consume = () = > {contract.WeatherUpdate ((error, result) = > {console.log ("NEW WEATHER DATA EVENT ON SMART CONTRACT"); console.log ("BLOCK NUMBER:"); console.log ("" + result.blockNumber) console.log ("WEATHER DATA:"); console.log (result.args); console.log ("\ n");}
When the service runs, as the transaction is successfully chained, it will periodically output data to the console:
NEW WEATHER DATA EVENT ON SMART CONTRACTBLOCK NUMBER: 3424586WEATHER DATA: {temperature: '74.75'} these are the principles of the implementation of the block chain in Oracle. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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
@ WebServlet (name = "httpServletDemo", urlPatterns = "/ httpServletDemo", initParams = {
© 2024 shulou.com SLNews company. All rights reserved.