Brain in new VAT 2021-11-24 15:24:29 阅读数:550
Blockchain Oracle (Oracle) It is a third-party decentralized data service , It can provide off chain data for smart contracts and blockchains . The Oracle is closing 、 The deterministic blockchain system has built a bridge between the real world .
Blockchain development tutorial link : The etheric fang | The currency | EOS | Tendermint | Hyperledger Fabric | Omni/USDT | Ripple | Tron
The main problem of blockchain Oracle is , It is not part of the blockchain consensus mechanism , Therefore, there is no basic security guarantee provided by the public infrastructure of the blockchain .Chainlink Is the current industry standard , Provides a robust solution .
Cosmos Is to build multi asset 、PoS An excellent open source framework for consensus custom blockchain . Every Cosmos The program is running in PoS Consensus engine Tendermint Core above .
Custom blockchain means Cosmos There is no virtual machine blockchain paradigm like Ethereum , That is, use the state machine to run the smart contract , Although you can also use Ethermint Let the custom blockchain support smart contracts .
Chainlink At present, it is widely used in Ethereum smart contract , The whole process is as follows :
From this description , We can see clearly that , Smart contract is the key to the whole process . Your smart contract does not work with any offline API Or resource communication - Only interact with another smart contract .
that , be based on cosmos Custom blockchain , Without a smart contract , How to realize the Oracle ? To be honest, I'm not sure . The only similar project I know , yes Kava Blockchain is in its system Integrated Chainlink Price prediction machine . They use a white list of Oracle machines that can publish price data on the chain . When Kava When platform users want price data , They can query the saved
All price data or the middle price of all prices published by the Oracle .
as far as I am concerned ,Chainlink Also trying to build a module , Complete similar functions .
For a short time I had to think about it , I came up with two solutions . I believe there is a better way to solve this technical problem , So please feel free to make the comments section of this article a brainstorming Creative Center .
One solution is , The Oracle operator creates a wallet on the custom blockchain . then , It USES WebSocket To listen for transactions involving that address . When it records such transactions , Just perform some off chain operations , Once that is done , Send the transaction to the source address of the previous transaction .
It will allow Oracle requests to be started on demand , The Oracle will be able to perform any work —— Not just publishing price data .
at present , It can take advantage of Chainlink The Oracle is complete . Oracle operators can register wallets on the blockchain , And use
External starter and External adapter Provide services .
The second more reliable option is to Cosmos Create a Oracle blockchain on , This will serve as Chainlink Nodes and Cosmos Communication points between ecosystems . It will Chainlink All of the API Exposed to use Cosmos In every blockchain built . We can even build a security mechanism in the Oracle blockchain , To verify the integrity of data outside the chain .
That sounds right Cosmos This is a very valuable thing for the ecosystem , So how to achieve ?
The Oracle blockchain uses the first solution proposed above , This means that the Oracle will use WebSockets Subscriptions from other Cosmos Transaction events on the blockchain from the Oracle blockchain . These events contain information , Allow the Oracle node to determine what it must do . After successful execution , Submit a transaction from the Oracle blockchain to the client blockchain .
Recently launched Inter chain communication protocol (IBC) Make the above scheme feasible . in short ,IBC It's a permit Cosmos End to end between blockchains 、 Reliable and proven communication protocols . whatever Cosmos All blockchains can execute the protocol of communication with the Oracle blockchain .
obviously , I will not implement this second solution in this article , Because it requires a lot of planning 、 Architecture and programming , And it will make you lose interest in reading . however , In the long run , I do plan to make this a reality , therefore , If you're interested , Please pay attention to my updates or keep in touch with me .
We will implement the first solution in the following paragraphs : Create a Cosmos Blockchain , And use Chainlink Get random quotes from the Internet .
In order to maintain the reasonable length of this article , We will write the code as concise as possible . However, there are still quite a lot of steps and code to complete . I know it's complicated , But it will be worth it .
We have to :
Now it's time to roll up your sleeves , Put on your hard hat and go to work !
I implemented a blockchain with minimal functionality , Used for Oracle quotation request and quotation creation . below , I'll show you the basics of how to start from scratch , But it won't explain how to build the entire sample application , Because this is not the focus of this article .
If you want to start the code directly , You can click on the here see GitHub Warehouse :
Let's start creating Cosmos Blockchain . The easiest way is to use starport Tools , You can GitHub install .
Turn on the terminal to run :
starport app github.com/lajosdeme/linktest
The above command will create a file named "linktest" Of cosmos Applications . You can enter linktest Folder and run starport serve
To generate and run the blockchain . The running results are similar to the following :
At present, this blockchain does not have many functions . Basically , All it does is run Tendermint Consensus engine , And provide minimal functionality , Trade between addresses . We are going to implement the business logic .
Output from the terminal above , You can see , We can port 26657 And tendermint Interaction . The consensus engine will emit different events , We can go through WebSocket Subscribe to them . Let's use the command line and postman Explain how this works , Then we can continue to achieve Chainlink External starter .
open Postman, And then click File ->New -> WebSocket request . Enter... At the top ws://localhost:25657 And click Connect. Now? , Let's subscribe to all trading Events . Paste the following information in the message field , And then click Send:
{
“jsonrpc”: “2.0”,
“method”: “subscribe”,
“id”: 0,
“params”: {
“query”:”tm.event = ‘Tx’”
}
}
this is it . We use it WebSocket Connect to the consensus engine . Now it's time to use a deal to test that everything is normal . Here are the commands we need :
linktestd tx bank send <SENDER_ADDRESS> <RECIPIENT_ADDRESS> <AMOUNT>
for example , For me , After the actual parameters are brought in, it is like this :
linktestd tx bank send \
cosmos1fztn5xte9c0gqfhjrf5a8vuqz9d2p6wf90ez72 \
cosmos1f0g0m92f6s405vww6n0kgjwcqfxyf8fjnzyuff \
10token
Let's go back to Postman Where? , There we can see that the transaction has been recorded . Our external sponsors will do the same , And trigger the operation of the Oracle node .
External starter Is to make Chainlink Nodes are secret weapons unrelated to blockchain , That is, any blockchain can be used .
The external initiator allows the job to be started in the node according to some external conditions . Create and add external initiators to Chainlink The ability of nodes
Cross chain compatibility is realized . - Chainlink file
Although you can follow the code , But if you also want to be able to run and test the code , Should be set locally or in the cloud Chainlink node . To set the local node , Please follow This tutorial perform . Once you have your own node , open .env file , And make sure it includes the following , To disable Ethereum and enable external initiators :
ETH_CHAIN_ID=0
ETH_DISABLED=true
FEATURE_EXTERNAL_INITIATORS=true
Now it's time to log in to the node's administrator settings , To add a sponsor :
chainlink admin login
Now you can register it :
chainlink initiators create linktest http://localhost:6688/jobs
This will create a file named linktest And use the default endpoint to access Chainlink Initiator of node job . The output will be like this :
Copy and save these values , Because we need them below .
Now use the command chainlink node start
Start your Chainlink node , And go to the browser http://localhost:6688. Log in and select... In the top navigation bar "Bridges". And then click "New Bridge", Enter a name ( My is link-ea) and URL(http://localhost:3000). You can temporarily set the minimum payment and confirmation amount to 0. Finally, click "Create Bridge".
An external adapter is added to the by creating a bridge type Chainlink In nodes . The bridge defines the task name and web address of the external adapter . When received, it's not
When the task type of one of the core adapters , The node will search for the bridge type with that name , Use bridge for external adapter . - Chainlink file
Now go to... In the top bar "Jobs", choice "New Job", And paste this into "Job Spec" in :
{
“name”: “LINK-EA”,
“initiators”: [
{
“type”: “external”,
“params”: {
“name”: “linktest”,
“body”: {
“endpoint”: “random”
}
}
}
],
“tasks”: [
{
“type”: “link-ea”
}
]
}
This tells Chainlink, We want to run the work , By the name of linktest Triggered by an external initiator , And should call link-ea Bridge . After creating the job , If you turn it on , You will see... Under the name ID. We still need that ID.
The last thing we need to do is set up a local... For our external adapter Postgres database . If you don't know how to do this , You can refer to Chainlink Related explanations in the node tutorial .
Now? , We can create actual external initiators . It's just a simple WebSocket The server , You can build it in any programming language , But I will be there. Go Build it in , Because I really like the language .
First , Create a file called "external-initiator" Project , And define a in the project root .env file . Now? , We need to add the saved values to the file :
EI_DATABASEURL=<external initiator postgres db url>
EI_CHAINLINKURL=localhost:6688
EI_IC_ACCESSKEY=<ACCESSKEY saved above>
EI_IC_SECRET=<SECRET saved above>
EI_CI_ACCESSKEY=<OUTGOINGTOKEN saved above>
EI_CI_SECRET=<OUTGOINGSECRET saved above>
JOB_ID=<Chainlink Job ID>
Now let's see WebSocket Client code :
package main
import (
"encoding/json"
"log"
"os"
"github.com/gorilla/websocket"
)
type WebSocket struct {
Endpoint string
}
type wsConn struct {
connection *websocket.Conn
open bool
}
func (ws WebSocket) Connect() wsConn {
c, _, err := websocket.DefaultDialer.Dial(ws.Endpoint, nil)
if err != nil {
log.Fatal("Error dialing: ", err)
}
con := wsConn{
connection: c,
open: true,
}
return con
}
func (con wsConn) Subscribe(message string) {
defer con.connection.Close()
interrupt := make(chan os.Signal, 1)
done := make(chan struct{})
err := con.connection.WriteMessage(websocket.TextMessage, []byte(message))
if err != nil {
con.open = false
log.Fatal("Error subscibing to tx: ", err)
}
go func() {
defer close(done)
for {
_, message, err := con.connection.ReadMessage()
if err != nil {
log.Println("Read error: ", err)
}
var txRes TxResult
json.Unmarshal([]byte(message), &txRes)
var requesterAddr, event string
txRes.convert(&requesterAddr, &event)
if event == "RequestQuote" {
startJob(requesterAddr)
}
}
}()
for {
select {
case <-done:
return
case <-interrupt:
log.Println("Interrupting")
err := con.connection.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
con.open = false
if err != nil {
log.Println("Close error:", err)
return
}
return
}
}
}
This does most of the work for external sponsors . There are other documents , So you should see Warehouse code , To establish the overall concept .
ad locum , We have a WebSocket structure , It saves access termination points , One more wsConn structure , For connection .
We are WebSocket There is a definition of Connect Method , Its function is to establish a connection .
We are wsConn It defines subscribe Method , Used to subscribe to trading Events . When it records an event , Will get the address of the requester and check whether the event type is RequestQuote. We only need this type of event . then , It calls startJob Method , This will trigger Chainlink The work of the Oracle .
Now we have a functional blockchain , And is successfully connecting the oracle to it . Great work ! Let's move on !
The external adapter can use our Oracle to call any external API The key to . We will be in JavaScript Build adapters in , Because on the one hand , This is almost the standard method ( Although you can use it equally easily Go or Python). On the other hand , In the future, we will hope to sign and broadcast transactions to our blockchain ,Cosmos It can automatically generate the required JavaScript Code .
The external adapter is Chainlink How to implement custom computing and professional API Simple integration of . The external adapter is Chainlink Node
The core through its API With simple JSON Specification of services for communication . – Chainlink file
First, create a folder link-ea And implement npm init
. We will use some packages , So let's install :
Remember I told you the mnemonic word to save the address generated when running the blockchain for the first time ? Now we need one of them . Create a .env file , And copy MNEMONIC and ORACLE_ADDRESS. If you don't save it , Just use starport serve --reset-once
Generate a new account .
Now it's time to generate code that interacts with the blockchain . Run the following command in the blockchain folder :
starport serve --rebuild-proto-once
After that , You should see that ./vue/src/store The path is named generated Folder . This contains the generated code . We only need some of these files , Some minor changes must also be made , In order to work properly in our application . The complete code can be viewed here
Once we have this , You can set up the signature and broadcast transaction API:
const {DirectSecp256k1HdWallet} = require('@cosmjs/proto-signing')
const {assertIsBroadcastTxSuccess} = require('@cosmjs/stargate')
const {MsgCreateQuote} = require('../cosmos/tx')
const { txClient } = require('../cosmos/client')
require('dotenv').config()
class LinkAPI {
constructor() {
this.main = {
//Create, sign and broadcast a quote tx
signAndBroadcast: async (oracle, requester, quote) => {
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC);
const client = await txClient(wallet)
const msg = MsgCreateQuote.fromJSON({
creator: oracle,
requester: requester,
oracle: oracle,
text: quote
})
const msgAny = client.msgCreateQuote(msg)
const result = await client.signAndBroadcast([msgAny])
assertIsBroadcastTxSuccess(result)
console.log("Result: ", result)
}
}
}
}
module.exports = LinkAPI
on top , We need something :
We create one with singAndBroadcast Methods and main Attribute API class . our API Currently only this function is included , But this design can be easily updated in the future .
signAndBroadcast Methods include Oracle address 、 The account address and quotation text of the request for quotation . It uses our mnemonics ( Stored in a file ) Create a wallet , And use the wallet to create a transaction client (txClient). then , We use what we introduced earlier MsgCreateQuote Object's fromJSON Method , And passed in to txClient Method of creating message . Then we call signAndBroadcast Broadcast news , And use assertIsBroadcastTxSuccess To check that everything is going well .
besides , We have two important documents ( I won't paste their code here ). One is called index.js, It defines a createRequest function , From our external sponsors will be verified API Subject of request , And generate a third party API request .
The other is app.js, It is responsible for starting our server and calling it. createRequest.
We've basically finished ! It's time to see if everything you do is right . Let's start all the processes one by one :
Now submit a request for quotation :
linktestd tx linktest request-quote \
cosmos1g7gw9jet6czu2m854v0ce3n3us8g8wyjkmdm3n \
--from alice
Replace... With your own Oracle address cosmos1g...
That's ok , And send it from any account you like . ad locum , I use one of the accounts created by default as the requester , The other is used as a Oracle .
Now? , You should observe the log in each terminal window , See what their processes are doing .
When it's all done , You can use linktest q linktest list-quote
Query quotation . You should see the first random quotation of your oracle on the chain .
Link to the original text :Chainlink docking Cosmos Blockchain — Huizhi. Com
版权声明:本文为[Brain in new VAT]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2021/11/20211108231834010Z.html