-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
313 lines (255 loc) · 8.36 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package main
import (
"context"
"encoding/json"
"flag"
"log"
"math/big"
"os"
"strings"
"code.vegaprotocol.io/oracles-relay/coinbase"
"code.vegaprotocol.io/oracles-relay/openoracle"
"code.vegaprotocol.io/vega/commands"
vgcrypto "code.vegaprotocol.io/vega/libs/crypto"
apipb "code.vegaprotocol.io/vega/protos/vega/api/v1"
commandspb "code.vegaprotocol.io/vega/protos/vega/commands/v1"
walletpb "code.vegaprotocol.io/vega/protos/vega/wallet/v1"
wcommands "code.vegaprotocol.io/vega/wallet/commands"
"code.vegaprotocol.io/vega/wallet/wallet"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/ethereum/go-ethereum/crypto"
"github.com/jeremyletang/vega_openoracle_demo/prices"
"github.com/pelletier/go-toml"
)
type Config struct {
NodeAddr string `toml:"node_addr"`
WalletMnemonic string `toml:"wallet_mnemonic"`
EthereumPrivateKey string `toml:"ethereum_private_key"`
// The coinbase config is not mandatory
// if nil, we do not start the worker
Coinbase *coinbase.Config `toml:"coinbase"`
}
var flags = struct {
Config string
Coinbase bool
Local bool
Price string
Timestamp uint64
Asset string
}{}
func init() {
flag.StringVar(&flags.Config, "config", "config.toml", "The configuration of the oracle relay")
flag.BoolVar(&flags.Coinbase, "coinbase", false, "Use coinbase data")
flag.BoolVar(&flags.Local, "local", false, "Use command line specified data")
flag.StringVar(&flags.Price, "price", "", "The price to encode (optional)")
flag.StringVar(&flags.Asset, "asset", "", "The asset name (optional)")
flag.Uint64Var(&flags.Timestamp, "timestamp", 0, "The timestamp at which to publish the data")
}
func main() {
flag.Parse()
if flags.Coinbase && flags.Local {
log.Fatalf("cannot use both flags coinbase and local")
}
// load our configuration
config, err := loadConfig(flags.Config)
if err != nil {
log.Fatalf("unable to read configuration: %v", err)
}
// validate common config
if len(config.EthereumPrivateKey) <= 0 {
log.Fatalf("missing ethereum private key")
}
if len(config.NodeAddr) <= 0 {
log.Fatalf("missing node address")
}
if len(config.WalletMnemonic) <= 0 {
log.Fatalf("missing wallet mnemonic")
}
if flags.Coinbase {
runCoinbaseExample(*config)
return
}
runLocalExample(*config)
}
func runLocalExample(config Config) {
if len(flags.Price) <= 0 {
log.Fatalf("missing price")
}
price, _ := big.NewInt(0).SetString(flags.Price, 10)
if price == nil {
log.Fatalf("invalid price: %v", flags.Price)
}
if len(flags.Asset) <= 0 {
log.Fatalf("missing asset")
}
if flags.Timestamp == 0 {
log.Fatalf("missing timestamp")
}
p, err := prices.New(
config.WalletMnemonic,
config.EthereumPrivateKey,
config.NodeAddr,
)
if err != nil {
log.Fatalf("could not instanties prices: %v", err)
}
err = p.Send(
flags.Timestamp,
[]openoracle.OraclePrice{
{
Asset: flags.Asset,
Timestamp: flags.Timestamp,
Price: flags.Price,
},
},
)
if err != nil {
log.Fatalf("could not send the prices: %v", err)
}
}
func runCoinbaseExample(config Config) {
if config.Coinbase == nil {
log.Fatalf("missing coinbase config")
}
cb := coinbase.New(*config.Coinbase)
bytes, err := cb.Pull()
if err != nil {
log.Fatalf("could not load coinbase open oracle: %v", err)
}
log.Printf("receive open oracle data%v\n", string(bytes))
res, err := openoracle.Unmarshal(bytes)
if err != nil {
log.Fatalf("unable to unmarshal coinbase open oracle data")
}
sendToVegaNetwork(config, res)
}
// Send Prices will use the configured ethereum from the configuration to
// bundle the new prices, and sign the open oracles bundle.
// then the bundle is sent ot the vega network
func SendPrices(config Config, timestamp uint64, newPrices []openoracle.OraclePrice) {
// buidling the private from configuration
privKey, err := crypto.HexToECDSA(strings.TrimPrefix(config.EthereumPrivateKey, "0x"))
if err != nil {
log.Fatalf("invalid private key")
}
// make the open oracle payload
req := openoracle.OracleRequest{
Timestamp: timestamp,
Prices: newPrices,
}
// this uses the private keys to sign the bundle,
// return the OpenOracleRequest type, which is later
// marshall to json and sent to vega
res, err := req.IntoOpenOracle(privKey)
if err != nil {
log.Fatalf("unable to build open oracle payload: %v", err)
}
log.Printf("encode open oracle message %#v\n", res)
log.Printf("verifying the payload")
// verify the validaty of the signatures for conveniences
address, prices, err := openoracle.Verify(*res)
if err != nil {
log.Fatalf("enable to verify open oracle payload: %v", err)
}
log.Printf("recovered ethereum address from the signatures: %v", address)
log.Printf("recovered prices: %#v", prices)
// send the transaction to the vega network
sendToVegaNetwork(config, res)
}
func sendToVegaNetwork(config Config, res *openoracle.OracleResponse) {
// marshall the open oracle payload to json
bytes, err := json.Marshal(res)
if err != nil {
log.Fatalf("could not marshal transaction to json: %v", err)
}
// package the vega transaction input data
cmd := &commandspb.OracleDataSubmission{
Source: commandspb.OracleDataSubmission_ORACLE_SOURCE_OPEN_ORACLE,
Payload: bytes,
}
// open a grpc client connection with the vega node,
// this will be used to:
// - pull the network latest block and chain ID (required to package the transaction
// - send the transaction
conn, err := grpc.Dial(config.NodeAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("could not open connection with vega node: %v", err)
}
clt := apipb.NewCoreServiceClient(conn)
// Bundle our OracleDataSubmission command
tx := bundleTransaction(config, cmd, clt)
log.Printf("packaged transaction: %#v\n", tx)
// Submit it to the vega network
sres, err := clt.SubmitTransaction(context.Background(), &apipb.SubmitTransactionRequest{
Tx: tx,
Type: apipb.SubmitTransactionRequest_TYPE_SYNC,
})
if err != nil {
log.Fatalf("could not submit transaction: %v", err)
}
log.Printf("transaction result: success(%v), hash(%v), err(%v)", sres.Success, sres.TxHash, sres.Data)
}
// this use the client and command to bundle a new transaction to the network
func bundleTransaction(config Config, cmd *commandspb.OracleDataSubmission, clt apipb.CoreServiceClient) *commandspb.Transaction {
// instantiate a wallet from the mnemonic set in the configuration
w, err := wallet.ImportHDWallet("oracleProvider", config.WalletMnemonic, wallet.Version2)
if err != nil {
log.Fatalf("could not import wallet: %v", err)
}
// generate the first key from the wallet.
firstKey, err := w.GenerateKeyPair(nil)
if err != nil {
log.Fatalf("could not generate first key: %v", err)
}
// pull the block data from the netowkr, use to sign the transaction and build the pow challenge
lastBlockData, err := clt.LastBlockHeight(context.Background(), &apipb.LastBlockHeightRequest{})
if err != nil {
log.Fatalf("could not get last block height: %v", err)
}
// marshal the input data to be injected in the transaction
marshaledInputData, err := wcommands.ToMarshaledInputData(
&walletpb.SubmitTransactionRequest{
PubKey: firstKey.PublicKey(),
Command: &walletpb.SubmitTransactionRequest_OracleDataSubmission{
OracleDataSubmission: cmd,
},
},
lastBlockData.Height,
)
if err != nil {
log.Fatalf("could not marshal the input data: %v", err)
}
// Sign the transaction
signature, err := w.SignTx(firstKey.PublicKey(), commands.BundleInputDataForSigning(marshaledInputData, lastBlockData.ChainId))
if err != nil {
log.Fatalf("could not sign the transaction: %v", err)
}
tx := commands.NewTransaction(firstKey.PublicKey(), marshaledInputData, &commandspb.Signature{
Value: signature.Value,
Algo: signature.Algo,
Version: signature.Version,
})
// Generate the proof of work for the transaction.
txID := vgcrypto.RandomHash()
powNonce, _, err := vgcrypto.PoW(lastBlockData.Hash, txID, uint(lastBlockData.SpamPowDifficulty), lastBlockData.SpamPowHashFunction)
if err != nil {
log.Fatalf("could not compute the proof-of-work: %v", err)
}
tx.Pow = &commandspb.ProofOfWork{
Nonce: powNonce,
Tid: txID,
}
return tx
}
func loadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
config := Config{}
if err := toml.Unmarshal(data, &config); err != nil {
return nil, err
}
return &config, nil
}