forked from qubic/qubic-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoracle_utils.cpp
More file actions
740 lines (679 loc) · 29 KB
/
oracle_utils.cpp
File metadata and controls
740 lines (679 loc) · 29 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
#include <cstdlib>
#include <cinttypes>
#include "core/src/network_messages/common_def.h"
#include "core/src/network_messages/oracles.h"
#include "qpi_adapter.h"
#include "oracle_utils.h"
#include "logger.h"
#include "utils.h"
#include "structs.h"
#include "connection.h"
#include "key_utils.h"
#include "wallet_utils.h"
void printGetOracleQueryHelpAndExit()
{
LOG("qubic-cli [...] -getoraclequery [QUERY_ID]\n");
LOG(" Print the oracle query, metadata, and reply if available.\n");
LOG("qubic-cli [...] -getoraclequery pending\n");
LOG(" Print the query IDs for all pending queries.\n");
LOG("qubic-cli [...] -getoraclequery pending+\n");
LOG(" Print the oracle query, metadata, and reply if available for each query ID received by pending.\n");
LOG("qubic-cli [...] -getoraclequery all [TICK]\n");
LOG(" Print the query IDs of all queries started in the given tick.\n");
LOG("qubic-cli [...] -getoraclequery all+ [TICK]\n");
LOG(" Print the oracle query, metadata, and reply if available for each query ID received by all.\n");
LOG("qubic-cli [...] -getoraclequery user [TICK]\n");
LOG(" Print the query IDs of user queries started in the given tick.\n");
LOG("qubic-cli [...] -getoraclequery user+ [TICK]\n");
LOG(" Print the oracle query, metadata, and reply if available for each query ID received by user.\n");
LOG("qubic-cli [...] -getoraclequery contract [TICK]\n");
LOG(" Print the query IDs of contract one-time queries started in the given tick.\n");
LOG("qubic-cli [...] -getoraclequery contract+ [TICK]\n");
LOG(" Print the oracle query, metadata, and reply if available for each query ID received by contract.\n");
LOG("qubic-cli [...] -getoraclequery subscription [TICK]\n");
LOG(" Print the query IDs of contract subscription queries started in the given tick.\n");
LOG("qubic-cli [...] -getoraclequery subscription+ [TICK]\n");
LOG(" Print the oracle query, metadata, and reply if available for each query ID received by subscription.\n");
LOG("qubic-cli [...] -getoraclequery stats\n");
LOG(" Print the oracle query statistics of the core node.\n");
LOG("qubic-cli [...] -getoraclequery revenue\n");
LOG(" Print the current oracle revenue points of all computors.\n");
exit(1);
}
void printMakeOracleUserQueryTransactionHelpAndExit()
{
LOG("qubic-cli [...] -queryoracle [INTERFACE] [QUERY_STRING] [TIMEOUT_IN_SECONDS]\n\n");
LOG(" Send an oracle user query transaction. [INTERFACE] and [QUERY_STRING] are mandatory parameters.\n");
LOG(" [TIMEOUT_IN_SECONDS] is optional (the default value is 60 seconds).\n\n");
LOG(" As [INTERFACE], you can currently chose one of following:\n");
for (uint32_t idx = 0; idx < OI::oracleInterfacesCount; ++idx)
LOG(" %s\n", oracleInterfaceToString(idx).c_str());
LOG("\n");
LOG(" The [QUERY_STRING] depends on the [INTERFACE]. Run the following to get help:\n");
LOG(" qubic-cli [...] queryoracle [INTERFACE]\n");
LOG(" For example:\n");
LOG(" qubic-cli [...] queryoracle price\n");
exit(1);
}
static std::vector<int64_t> receiveQueryIds(QCPtr qc, unsigned int reqType, long long reqTickOrId = 0)
{
struct {
RequestResponseHeader header;
RequestOracleData req;
} packet;
packet.header.setSize(sizeof(packet));
packet.header.randomizeDejavu();
packet.header.setType(RequestOracleData::type());
memset(&packet.req, 0, sizeof(packet.req));
packet.req.reqType = reqType;
packet.req.reqTickOrId = reqTickOrId;
qc->sendData((uint8_t*)&packet, packet.header.size());
std::vector<int64_t> queryIds;
uint8_t headerBuffer[sizeof(RequestResponseHeader)];
auto header = (const RequestResponseHeader*)headerBuffer;
int recvByte = qc->receiveData(headerBuffer, sizeof(RequestResponseHeader));
std::vector<uint8_t> payloadBuffer(sizeof(RespondOracleData) + 128 * sizeof(int64_t));
while (recvByte == sizeof(RequestResponseHeader))
{
if (header->dejavu() != packet.header.dejavu())
{
throw std::runtime_error("Unexpected dejavu!");
}
if (header->type() == RespondOracleData::type())
{
unsigned int payloadSize = header->size() - sizeof(RequestResponseHeader);
if (payloadSize > payloadBuffer.size())
{
payloadBuffer.resize(payloadSize);
}
recvByte = qc->receiveAllDataOrThrowException(payloadBuffer.data(), payloadSize);
auto resp = (RespondOracleData*)(payloadBuffer.data());
if (resp->resType == RespondOracleData::respondQueryIds)
{
long long idsNumBytes = payloadSize - sizeof(RespondOracleData);
if (idsNumBytes % 8 != 0)
{
throw std::runtime_error("Malformatted RespondOracleData::respondQueryIds message!");
}
else if (idsNumBytes > 0)
{
const uint8_t* queryIdBuffer = payloadBuffer.data() + sizeof(RespondOracleData);
queryIds.insert(queryIds.end(),
(int64_t*)queryIdBuffer, (int64_t*)(queryIdBuffer + idsNumBytes));
}
}
else if (resp->resType == RespondOracleData::respondTickRange)
{
if (payloadSize != sizeof(RespondOracleData) + sizeof(RespondOracleDataValidTickRange))
{
throw std::runtime_error("Malformatted RespondOracleData::respondTickRange message!");
}
const auto* tickRange = (RespondOracleDataValidTickRange*)(payloadBuffer.data() + sizeof(RespondOracleData));
if (reqTickOrId < tickRange->firstTick)
{
throw std::runtime_error("Data is not available, because tick is too old.");
}
else
{
throw std::runtime_error("Data is not available yet. You need to wait. Current tick is " + std::to_string(tickRange->currentTick));
}
}
}
else if (header->type() == END_RESPOND)
{
return queryIds;
}
else
{
throw std::runtime_error("Unexpected packet type!");
}
recvByte = qc->receiveData(headerBuffer, sizeof(RequestResponseHeader));
}
throw ConnectionTimeout();
}
static void receiveQueryInformation(QCPtr qc, int64_t queryId, RespondOracleDataQueryMetadata& metadata, std::vector<uint8_t>& query, std::vector<uint8_t>& reply)
{
// send request
struct {
RequestResponseHeader header;
RequestOracleData req;
} request;
request.header.setSize(sizeof(request));
request.header.randomizeDejavu();
request.header.setType(RequestOracleData::type());
memset(&request.req, 0, sizeof(request.req));
request.req.reqType = RequestOracleData::requestQueryAndResponse;
request.req.reqTickOrId = queryId;
qc->sendData((uint8_t*)&request, request.header.size());
// reset output
memset(&metadata, 0, sizeof(RespondOracleDataQueryMetadata));
query.clear();
reply.clear();
// prepare output buffers
uint8_t headerBuffer[sizeof(RequestResponseHeader)];
auto responseHeader = (const RequestResponseHeader*)headerBuffer;
std::vector<uint8_t> payloadBuffer(2048);
// receive query data
int recvHeaderBytes = qc->receiveData(headerBuffer, sizeof(RequestResponseHeader));
while (recvHeaderBytes == sizeof(RequestResponseHeader))
{
// get remaining part of the response
const unsigned int responsePayloadSize = responseHeader->size() - sizeof(RequestResponseHeader);
if (responsePayloadSize > payloadBuffer.size())
{
payloadBuffer.resize(responsePayloadSize);
}
qc->receiveAllDataOrThrowException(payloadBuffer.data(), responsePayloadSize);
// only process if dejavu matches (response is to current request, skip otherwise)
if (responseHeader->dejavu() == request.header.dejavu())
{
if (responseHeader->type() == RespondOracleData::type())
{
// Oracle data response
if (responsePayloadSize < sizeof(RespondOracleData))
{
throw std::runtime_error("Malformatted RespondOracleData reply");
}
auto respOracleData = (RespondOracleData*)payloadBuffer.data();
auto responseInnerPayload = payloadBuffer.data() + sizeof(RespondOracleData);
auto responseInnerPayloadSize = responsePayloadSize - sizeof(RespondOracleData);
if (respOracleData->resType == RespondOracleData::respondQueryMetadata
&& responsePayloadSize == sizeof(RespondOracleData) + sizeof(RespondOracleDataQueryMetadata))
{
// Query metadata
metadata = *(RespondOracleDataQueryMetadata*)(responseInnerPayload);
}
else if (respOracleData->resType == RespondOracleData::respondQueryData)
{
// Oracle query
query.insert(query.end(),
responseInnerPayload,
responseInnerPayload + responseInnerPayloadSize);
}
else if (respOracleData->resType == RespondOracleData::respondReplyData)
{
// Oracle reply
reply.insert(reply.end(),
responseInnerPayload,
responseInnerPayload + responseInnerPayloadSize);
}
else
{
throw std::runtime_error("Unexpected RespondOracleData message sub-type");
}
}
else if (responseHeader->type() == END_RESPOND)
{
// End of output packages for this request
if (metadata.queryId != queryId)
throw std::logic_error("Unknown query ID!");
else
break;
}
// try to get next message header
recvHeaderBytes = qc->receiveData(headerBuffer, sizeof(RequestResponseHeader));
}
}
if (recvHeaderBytes < sizeof(RequestResponseHeader))
{
throw std::logic_error("Error receiving message header.");
}
}
static const char* getOracleQueryTypeStr(uint8_t type)
{
switch (type)
{
case ORACLE_QUERY_TYPE_CONTRACT_QUERY:
return "contract one-time query";
case ORACLE_QUERY_TYPE_CONTRACT_SUBSCRIPTION:
return "contract subscription";
case ORACLE_QUERY_TYPE_USER_QUERY:
return "user query";
default:
return "unknown";
}
}
static const char* getOracleQueryStatusStr(uint8_t type)
{
switch (type)
{
case ORACLE_QUERY_STATUS_PENDING:
return "pending";
case ORACLE_QUERY_STATUS_COMMITTED:
return "committed";
case ORACLE_QUERY_STATUS_SUCCESS:
return "success";
case ORACLE_QUERY_STATUS_UNRESOLVABLE:
return "unresolvable";
case ORACLE_QUERY_STATUS_TIMEOUT:
return "timeout";
default:
return "unknown";
}
}
static std::string getOracleQueryStatusFlagsStr(uint16_t flags)
{
std::string str;
if (flags & ORACLE_FLAG_REPLY_RECEIVED)
str += "-> core node received valid reply from the oracle machine";
if (flags & ORACLE_FLAG_INVALID_ORACLE)
str += "\n\t- oracle machine reported that oracle (data source) in query was invalid";
if (flags & ORACLE_FLAG_ORACLE_UNAVAIL)
str += "\n\t- oracle machine reported that oracle (data source) isn't available at the moment";
if (flags & ORACLE_FLAG_INVALID_TIME)
str += "\n\t- oracle machine reported that time in query was invalid";
if (flags & ORACLE_FLAG_INVALID_PLACE)
str += "\n\t- oracle machine reported that place in query was invalid";
if (flags & ORACLE_FLAG_INVALID_ARG)
str += "\n\t- oracle machine reported that an argument in query was invalid";
if (flags & ORACLE_FLAG_BAD_SIZE_REPLY)
str += "\n\t- core node got reply of wrong size from the oracle machine";
if (flags & ORACLE_FLAG_OM_DISAGREE)
str += "\n\t- core node got different replies from oracle machine nodes";
if (flags & ORACLE_FLAG_BAD_SIZE_REVEAL)
str += "\n\t- weren't enough reply commit tx with the same digest before timeout (< 451)";
return str;
}
static void printQueryInformation(const RespondOracleDataQueryMetadata& metadata, const std::vector<uint8_t>& query, const std::vector<uint8_t>& reply)
{
LOG("Query ID: %" PRIi64 "\n", metadata.queryId);
LOG("Type: %s (%" PRIu8 ")\n", getOracleQueryTypeStr(metadata.type), metadata.type);
LOG("Status: %s (%" PRIu8 ")\n", getOracleQueryStatusStr(metadata.status), metadata.status);
LOG("Status Flags: %" PRIu16 " %s\n", metadata.statusFlags, getOracleQueryStatusFlagsStr(metadata.statusFlags).c_str());
LOG("Query Tick: %" PRIu32 "\n", metadata.queryTick);
char queryingIdentity[128] = { 0 };
getIdentityFromPublicKey(metadata.queryingEntity.m256i_u8, queryingIdentity, /*isLowerCase=*/false);
LOG("Querying Entity: %s\n", queryingIdentity);
LOG("Timeout: %s\n", toString(*(QPI::DateAndTime*)&metadata.timeout).c_str());
LOG("Interface Index: %" PRIu32 "\n", metadata.interfaceIndex);
if (metadata.type == ORACLE_QUERY_TYPE_CONTRACT_SUBSCRIPTION)
LOG("Subscription ID: %" PRIi32 "\n", metadata.subscriptionId);
if (metadata.status == ORACLE_QUERY_STATUS_SUCCESS)
{
LOG("Reveal Tick: %" PRIu32 "\n", metadata.revealTick);
}
else
{
LOG("Total Commits: %" PRIu16 "\n", metadata.totalCommits);
LOG("Agreeing Commits: %" PRIu16 "\n", metadata.agreeingCommits);
}
std::string queryStr = oracleQueryToString(metadata.interfaceIndex, query);
if (queryStr.find("error") != std::string::npos)
{
std::vector<char> hexQuery(2 * query.size() + 1, 0);
byteToHex(query.data(), hexQuery.data(), static_cast<int>(query.size()));
LOG("Query: %s %s\n", hexQuery.data(), queryStr.c_str());
}
else
{
LOG("Query: %s\n", queryStr.c_str());
}
if (reply.size() > 0)
{
std::string replyStr = oracleReplyToString(metadata.interfaceIndex, reply);
if (replyStr.find("error") != std::string::npos)
{
std::vector<char> hexReply(2 * reply.size() + 1, 0);
byteToHex(reply.data(), hexReply.data(), static_cast<int>(reply.size()));
LOG("Reply: %s %s\n", hexReply.data(), replyStr.c_str());
}
else
{
LOG("Reply: %s\n", replyStr.c_str());
}
}
}
static void receiveQueryStats(QCPtr& qc, RespondOracleDataQueryStatistics& stats)
{
struct {
RequestResponseHeader header;
RequestOracleData req;
} packet;
packet.header.setSize(sizeof(packet));
packet.header.randomizeDejavu();
packet.header.setType(RequestOracleData::type());
memset(&packet.req, 0, sizeof(packet.req));
packet.req.reqType = RequestOracleData::requestQueryStatistics;
qc->sendData((uint8_t*)&packet, packet.header.size());
constexpr unsigned long long responseSize = sizeof(RequestResponseHeader) + sizeof(RespondOracleData) + sizeof(RespondOracleDataQueryStatistics);
uint8_t buffer[responseSize];
int recvByte = qc->receiveData(buffer, responseSize);
if (recvByte != responseSize)
{
throw std::logic_error("Connection closed.");
}
const auto* header = (RequestResponseHeader*)buffer;
const auto* header2 = (RespondOracleData*)(buffer + sizeof(RequestResponseHeader));
if (header->type() != RespondOracleData::type() || header2->resType != RespondOracleData::respondQueryStatistics)
{
throw std::logic_error("Unexpected response message.");
}
const auto* receivedStats = (RespondOracleDataQueryStatistics*)(buffer + sizeof(RequestResponseHeader) + sizeof(RespondOracleData));
stats = *receivedStats;
}
static void printQueryStats(const RespondOracleDataQueryStatistics& stats)
{
const float revealPerSuccess = (stats.successfulCount) ? float(stats.revealTxCount) / stats.successfulCount : 0;
LOG("successful: % " PRIu64 " queries (takes %.3f ticks on average, %.1f reveal tx / success)\n", stats.successfulCount, float(stats.successAvgMilliTicksPerQuery) / 1000.0f, revealPerSuccess);
LOG("timeout: % " PRIu64 " queries in total (average timeout is %.3f ticks)\n", stats.timeoutCount, float(stats.timeoutAvgMilliTicksPerQuery) / 1000.0f);
LOG(" % " PRIu64 " queries before OM reply\n", stats.timeoutNoReplyCount);
LOG(" % " PRIu64 " queries before commit quorum\n", stats.timeoutNoCommitCount);
LOG(" % " PRIu64 " queries before reveal\n", stats.timeoutNoRevealCount);
LOG("unresolvable: % " PRIu64 " queries\n", stats.unresolvableCount);
LOG("pending: % " PRIu64 " queries in total\n", stats.pendingCount);
LOG(" % " PRIu64 " queries before OM reply (takes %.3f ticks on average)\n", stats.pendingOracleMachineCount, float(stats.oracleMachineReplyAvgMilliTicksPerQuery) / 1000.0f);
LOG(" % " PRIu64 " queries before commit quorum (takes %.3f ticks on average)\n", stats.pendingCommitCount, float(stats.commitAvgMilliTicksPerQuery) / 1000.0f);
LOG(" % " PRIu64 " queries before reveal / success\n", stats.pendingRevealCount);
if (stats.oracleMachineRepliesDisagreeCount > 0)
{
LOG("OM issues: % " PRIu64 " queries had OM replies that differ between OMs\n", stats.oracleMachineRepliesDisagreeCount);
}
}
static void receiveOracleRevenuePoints(QCPtr& qc, std::vector<uint64_t>& revenuePoints)
{
struct {
RequestResponseHeader header;
RequestOracleData req;
} packet;
packet.header.setSize(sizeof(packet));
packet.header.randomizeDejavu();
packet.header.setType(RequestOracleData::type());
memset(&packet.req, 0, sizeof(packet.req));
packet.req.reqType = RequestOracleData::requestOracleRevenuePoints;
qc->sendData((uint8_t*)&packet, packet.header.size());
constexpr unsigned long long responseSize = sizeof(RequestResponseHeader) + sizeof(RespondOracleData) + 8 * 676;
uint8_t buffer[responseSize];
int recvByte = qc->receiveData(buffer, responseSize);
if (recvByte != responseSize)
{
throw std::logic_error("Connection closed.");
}
const auto* header = (RequestResponseHeader*)buffer;
const auto* header2 = (RespondOracleData*)(buffer + sizeof(RequestResponseHeader));
if (header->type() != RespondOracleData::type() || header2->resType != RespondOracleData::respondOracleRevenuePoints)
{
throw std::logic_error("Unexpected response message.");
}
revenuePoints.resize(676);
memcpy(revenuePoints.data(), buffer + sizeof(RequestResponseHeader) + sizeof(RespondOracleData), 8 * 676);
}
static void printOracleRevenuePoints(const std::vector<uint64_t>& revenuePoints)
{
for (int i = 0; i < (int)revenuePoints.size(); ++i)
{
LOG("computor %d -> %" PRIu64 " oracle rev points\n", i, revenuePoints[i]);
}
}
static bool parseTick(const char* tickStr, long long& tickFrom, long long& tickTo)
{
char* writableTickStr = STRDUP(tickStr);
std::string part1 = strtok2string(writableTickStr, "-");
std::string part2 = strtok2string(NULL, "-");
std::string part3 = strtok2string(NULL, "-");
free(writableTickStr);
if (!part3.empty())
{
LOG("Failed to parse tick string \"%s\"! Does not follow syntax N1-N2!", tickStr);
return false;
}
bool okay = true;
try
{
tickFrom = std::stoll(part1);
if (tickFrom <= 0)
okay = false;
if (!part2.empty())
{
tickTo = std::stoll(part2);
if (tickTo <= 0)
okay = false;
}
else
tickTo = tickFrom;
}
catch (std::exception e)
{
okay = false;
}
if (!okay)
{
LOG("Failed to parse tick string \"%s\"! Tick must be a positive number N or range N1-N2!", tickStr);
}
return okay;
}
void processGetOracleQueryWithTick(const char* nodeIp, const int nodePort, unsigned int reqType, const char* reqParam, bool getAllDetails)
{
long long tickFrom = 0, tickTo = 0;
if (!parseTick(reqParam, tickFrom, tickTo))
return;
const long long tickCount = tickTo - tickFrom + 1;
if (tickCount < 1)
{
LOG("In range N1-N2, N2 should be greater than N2.");
return;
}
if (tickCount > 10000)
{
LOG("Range of ticks is too large. Skipped for node performance reasons.");
return;
}
// use longer 3 second timeout
unsigned long timeoutMilliseconds = 3000;
auto qc = make_qc(nodeIp, nodePort, timeoutMilliseconds);
for (long long tick = tickFrom; tick <= tickTo; ++tick)
{
std::vector<int64_t> recQueryIds = receiveQueryIds(qc, reqType, tick);
if (!getAllDetails)
{
LOG("Query IDs in tick %" PRIi64 ":\n", tick);
for (const int64_t& id : recQueryIds)
{
LOG("- %" PRIi64 "\n", id);
}
}
else
{
LOG("Number of query IDs in tick %" PRIi64 ": %d\n\n", tick, (int)recQueryIds.size());
RespondOracleDataQueryMetadata metadata;
std::vector<uint8_t> query, reply;
for (const int64_t& id : recQueryIds)
{
receiveQueryInformation(qc, id, metadata, query, reply);
if (metadata.queryId == 0)
{
LOG("Error getting query metadata! Stopping now.\n");
return;
}
printQueryInformation(metadata, query, reply);
LOG("\n");
}
}
}
}
void processGetOracleQuery(const char* nodeIp, const int nodePort, const char* requestType, const char* reqParam)
{
if (strcasecmp(requestType, "") == 0)
printGetOracleQueryHelpAndExit();
if (strcasecmp(requestType, "pending") == 0)
{
auto qc = make_qc(nodeIp, nodePort);
std::vector<int64_t> recQueryIds = receiveQueryIds(qc, RequestOracleData::requestPendingQueryIds);
LOG("Pending query ids:\n");
for (const int64_t& id : recQueryIds)
{
LOG("- %" PRIi64 "\n", id);
}
}
else if (strcasecmp(requestType, "pending+") == 0)
{
auto qc = make_qc(nodeIp, nodePort);
std::vector<int64_t> recQueryIds = receiveQueryIds(qc, RequestOracleData::requestPendingQueryIds);
LOG("Number of pending query IDs: %d\n\n", (int)recQueryIds.size());
RespondOracleDataQueryMetadata metadata;
std::vector<uint8_t> query, reply;
for (const int64_t& id : recQueryIds)
{
receiveQueryInformation(qc, id, metadata, query, reply);
printQueryInformation(metadata, query, reply);
LOG("\n");
}
}
else if (strcasecmp(requestType, "all") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestAllQueryIdsByTick, reqParam,
/*getAllDetails=*/false);
}
else if (strcasecmp(requestType, "all+") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestAllQueryIdsByTick, reqParam,
/*getAllDetails=*/true);
}
else if (strcasecmp(requestType, "user") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestUserQueryIdsByTick, reqParam,
/*getAllDetails=*/false);
}
else if (strcasecmp(requestType, "user+") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestUserQueryIdsByTick, reqParam,
/*getAllDetails=*/true);
}
else if (strcasecmp(requestType, "contract") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestContractDirectQueryIdsByTick, reqParam,
/*getAllDetails=*/false);
}
else if (strcasecmp(requestType, "contract+") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestContractDirectQueryIdsByTick, reqParam,
/*getAllDetails=*/true);
}
else if (strcasecmp(requestType, "subscription") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestContractSubscriptionQueryIdsByTick, reqParam,
/*getAllDetails=*/false);
}
else if (strcasecmp(requestType, "subscription+") == 0)
{
processGetOracleQueryWithTick(nodeIp, nodePort,
RequestOracleData::requestContractSubscriptionQueryIdsByTick, reqParam,
/*getAllDetails=*/true);
}
else if (strcasecmp(requestType, "stats") == 0)
{
auto qc = make_qc(nodeIp, nodePort);
RespondOracleDataQueryStatistics stats;
receiveQueryStats(qc, stats);
printQueryStats(stats);
}
else if (strcasecmp(requestType, "revenue") == 0)
{
auto qc = make_qc(nodeIp, nodePort);
std::vector<uint64_t> computorRevenuePoints;
receiveOracleRevenuePoints(qc, computorRevenuePoints);
printOracleRevenuePoints(computorRevenuePoints);
}
else
{
// no known command, try to interpret param string as query id (8-byte int64_t number)
int64_t queryId;
try
{
queryId = std::stoll(std::string(requestType));
}
catch (std::exception e)
{
LOG("Expected query ID (unsigned integer), found unknown command %s!\n", requestType);
return;
}
if (queryId <= 0)
{
LOG("Invalid query ID. Expected positive integer. Use commands such as \"user\" and \"contract\" to get a valid ID.\n");
return;
}
auto qc = make_qc(nodeIp, nodePort);
RespondOracleDataQueryMetadata metadata;
std::vector<uint8_t> query, reply;
receiveQueryInformation(qc, queryId, metadata, query, reply);
printQueryInformation(metadata, query, reply);
}
}
void makeOracleUserQueryTransaction(
const char* nodeIp, int nodePort, const char* seed,
const char* oracleInterfaceString,
const char* queryString,
const char* timeoutSecondsString,
uint32_t scheduledTickOffset)
{
if (strcasecmp(oracleInterfaceString, "") == 0)
printMakeOracleUserQueryTransactionHelpAndExit();
const uint32_t interfaceIndex = stringToOracleInterface(oracleInterfaceString);
if (interfaceIndex >= OI::oracleInterfacesCount)
{
LOG("Unknown oracle interface \"%s\"!\nSupported options are:\n", oracleInterfaceString);
for (uint32_t idx = 0; idx < OI::oracleInterfacesCount; ++idx)
LOG("\t%s\n", oracleInterfaceToString(idx).c_str());
return;
}
if (strcasecmp(queryString, "") == 0)
{
LOG("[QUERY_STRING] in %s oracle:\n", oracleInterfaceToString(interfaceIndex).c_str());
printOracleQueryParamHelp(interfaceIndex);
return;
}
std::vector<uint8_t> queryData = parseOracleQueryParams(interfaceIndex, queryString);
if (queryData.size() == 0)
{
LOG("Error parsing [QUERY_STRING] \"%s\".\n", queryString);
return;
}
uint64_t timeoutSeconds = 60;
if (strcasecmp(timeoutSecondsString, "") == 0)
{
LOG("No timeout specified. Using default timeout of 60 seconds.\n");
}
else
{
try
{
timeoutSeconds = std::stoull(timeoutSecondsString);
}
catch (...)
{
timeoutSeconds = 0;
}
if (timeoutSeconds == 0 || timeoutSeconds > 600)
{
LOG("Error: Invalid timeout! Please use a value between 1 and 600.\n");
return;
}
}
// get oracle query fee
OI::initOracleInterfaces();
int64_t fee = OI::getOracleQueryFeeFunc[interfaceIndex](queryData.data());
LOG("Fee for oracle query: %" PRIi64 "\n", fee);
// build tx input data
const int txInputSize = 8 + (int)queryData.size();
std::vector<uint8_t> txInputData(txInputSize);
*(uint32_t*)(txInputData.data()) = interfaceIndex;
*(uint32_t*)(txInputData.data() + 4) = (uint32_t)timeoutSeconds * 1000; // timeout in milliseconds
memcpy(txInputData.data() + 8, queryData.data(), queryData.size());
// send transaction
char destinationPublicKey[32] = {0};
uint32_t scheduledTick = 0;
makeCustomTransaction(nodeIp, nodePort, seed, destinationPublicKey,
10, // TODO: define tx types as enum in core and use here
fee, txInputSize, txInputData.data(), scheduledTickOffset, &scheduledTick);
// TODO: print command to check directly
LOG("\n\nYou may run the following command for checking the query:\n");
LOG("qubic-cli [...] -getoraclequery user+ %u\n", scheduledTick);
// TODO: add "my/my+ [TICK]" command that uses a future core command for filtering queries based on seed
// (send tick + 4 bytes of public key to core for filtering oracle IDs)
}