-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathoracle_utils.cpp
More file actions
1211 lines (1107 loc) · 47.9 KB
/
oracle_utils.cpp
File metadata and controls
1211 lines (1107 loc) · 47.9 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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#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"
#include "contracts.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, std::vector<uint16_t>& contractIndices)
{
// 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();
contractIndices.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 if (respOracleData->resType == RespondOracleData::respondNotifiedSubscriberContracts)
{
// Subscriber contract indices
contractIndices.insert(contractIndices.end(),
(uint16_t*)(responseInnerPayload),
(uint16_t*)(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 query";
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, const std::vector<uint16_t>& contractIndices)
{
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 (contractIndices.size() > 0)
{
LOG("Notified subscriber contracts:");
for (uint16_t contractIdx : contractIndices)
{
const char* name = getContractName(contractIdx, true);
if (name)
LOG(" %d=%s", (int)contractIdx, name);
else
LOG(" %d", (int)contractIdx);
}
LOG("\n");
}
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 < sizeof(RequestResponseHeader) + sizeof(RespondOracleData))
{
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.");
}
if (header->size() != responseSize)
{
LOG("WARNING: Unexpected response message size. Maybe the version of the core and qubic-cli do not match.\n");
}
memset(&stats, 0, sizeof(stats));
const auto* receivedStats = (RespondOracleDataQueryStatistics*)(buffer + sizeof(RequestResponseHeader) + sizeof(RespondOracleData));
unsigned int copySize = header->size() - sizeof(RequestResponseHeader) - sizeof(RespondOracleData);
if (sizeof(stats) < copySize)
copySize = sizeof(stats);
memcpy(&stats, receivedStats, copySize);
}
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);
LOG("total: % " PRIu64 " contract one-time queries\n", stats.contractQueries);
LOG(" % " PRIu64 " contract subscription queries\n", stats.subscriptionQueries);
LOG(" % " PRIu64 " user queries\n", stats.userQueries);
if (stats.oracleMachineRepliesDisagreeCount > 0)
{
LOG("OM issues: % " PRIu64 " queries had OM replies that differ between OMs\n", stats.oracleMachineRepliesDisagreeCount);
}
if (stats.wrongKnowledgeProofCount > 0)
{
LOG("Core issues: % " PRIu64 " commit tx had wrong knowledge proof\n", stats.wrongKnowledgeProofCount);
}
}
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;
std::vector<uint16_t> contractIndices;
for (const int64_t& id : recQueryIds)
{
receiveQueryInformation(qc, id, metadata, query, reply, contractIndices);
if (metadata.queryId == 0)
{
LOG("Error getting query metadata! Stopping now.\n");
return;
}
printQueryInformation(metadata, query, reply, contractIndices);
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;
std::vector<uint16_t> contractIndices;
for (const int64_t& id : recQueryIds)
{
receiveQueryInformation(qc, id, metadata, query, reply, contractIndices);
printQueryInformation(metadata, query, reply, contractIndices);
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;
std::vector<uint16_t> contractIndices;
receiveQueryInformation(qc, queryId, metadata, query, reply, contractIndices);
printQueryInformation(metadata, query, reply, contractIndices);
}
}
static void receiveSubscriptionInformation(QCPtr qc, int64_t subscriptionId, RespondOracleDataSubscription& subscription,
std::vector<uint8_t>& initialQuery, std::vector<RespondOracleDataSubscriber>& subscribers)
{
// 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::requestSubscription;
request.req.reqTickOrId = subscriptionId;
qc->sendData((uint8_t*)&request, request.header.size());
// reset output
memset(&subscription, 0, sizeof(subscription));
initialQuery.clear();
subscribers.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::respondSubscription
&& responsePayloadSize == sizeof(RespondOracleData) + sizeof(RespondOracleDataSubscription))
{
// Subscription
subscription = *(RespondOracleDataSubscription*)(responseInnerPayload);
}
else if (respOracleData->resType == RespondOracleData::respondQueryData)
{
// Initial oracle query
initialQuery.insert(initialQuery.end(),
responseInnerPayload,
responseInnerPayload + responseInnerPayloadSize);
}
else if (respOracleData->resType == RespondOracleData::respondSubscriber)
{
// Add subscriber
subscribers.push_back(*(RespondOracleDataSubscriber*)(responseInnerPayload));
}
else
{
throw std::runtime_error("Unexpected RespondOracleData message sub-type");
}
}
else if (responseHeader->type() == END_RESPOND)
{
// End of output packages for this request
if (subscription.subscriptionId != subscriptionId)
throw std::logic_error("Unknown subscription 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 void printSubscriptionInformation(RespondOracleDataSubscription& subscription,
std::vector<uint8_t>& initialQuery, std::vector<RespondOracleDataSubscriber>& subscribers)
{
LOG("Subscription ID: %" PRIi32 "\n", subscription.subscriptionId);
LOG("Interface Index: %" PRIu32 "\n", subscription.interfaceIndex);
std::string queryStr = oracleQueryToString(subscription.interfaceIndex, initialQuery);
if (queryStr.find("error") != std::string::npos)
{
std::vector<char> hexQuery(2 * initialQuery.size() + 1, 0);
byteToHex(initialQuery.data(), hexQuery.data(), static_cast<int>(initialQuery.size()));
LOG("Initial query: %s %s\n", hexQuery.data(), queryStr.c_str());
}
else
{
LOG("Initial query: %s\n", queryStr.c_str());
}
LOG("Generated queries: %" PRIu32 "\n", subscription.generatedQueriesCount);
LOG("Last pending query ID: %" PRIi64 "\n", subscription.lastPendingQueryId);
LOG("Last revealed query ID: %" PRIi64 "\n", subscription.lastRevealedQueryId);
LOG("Current subscriber contracts:\n");
for (const auto& subscriber : subscribers)
{
const char* name = getContractName(subscriber.contractIndex, true);
if (name)
LOG("\t- %d=%s", (int)subscriber.contractIndex, name);
else
LOG("\t- %d", (int)subscriber.contractIndex);
LOG(", period %d minute(s), next query %s\n", (int)subscriber.notificationPeriodMinutes, toString(*(QPI::DateAndTime*)&subscriber.nextQueryTimestamp).c_str());
}
}
static std::vector<int32_t> receiveSubscriptionIds(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<int32_t> subscriptionIds;
uint8_t headerBuffer[sizeof(RequestResponseHeader)];
auto header = (const RequestResponseHeader*)headerBuffer;
int recvByte = qc->receiveData(headerBuffer, sizeof(RequestResponseHeader));
std::vector<uint8_t> payloadBuffer(sizeof(RespondOracleData) + 256 * sizeof(int32_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::respondSubscriptionIds)
{
long long idsNumBytes = payloadSize - sizeof(RespondOracleData);
if (idsNumBytes % 4 != 0)
{
throw std::runtime_error("Malformatted RespondOracleData::respondSubscriptionIds message!");
}
else if (idsNumBytes > 0)
{
const uint8_t* subscriptionIdBuffer = payloadBuffer.data() + sizeof(RespondOracleData);
subscriptionIds.insert(subscriptionIds.end(),
(int32_t*)subscriptionIdBuffer, (int32_t*)(subscriptionIdBuffer + idsNumBytes));
}
}
}
else if (header->type() == END_RESPOND)
{
return subscriptionIds;
}
else
{
throw std::runtime_error("Unexpected packet type!");
}
recvByte = qc->receiveData(headerBuffer, sizeof(RequestResponseHeader));
}
throw ConnectionTimeout();
}
int32_t getSubscriptionIdFromString(const char* s)
{
int64_t subscriptionId = -1;
try
{
subscriptionId = std::stoull(s);
}
catch (...)
{
subscriptionId = -1;
}
if (subscriptionId < 0 || subscriptionId > 0x7fffffffll)
{
LOG("Error: Invalid subscription ID!\n");
return -1;
}
return (int32_t)subscriptionId;
}
void printGetOracleSubscriptionHelpAndExit()
{
LOG("qubic-cli [...] -getoraclesubscription [SUBSCRIPTION_ID]\n");
LOG(" Print information about a specific subsriptions, including subscribed contracts.\n");
LOG("qubic-cli [...] -getoraclesubscription active\n");
LOG(" Print the subscription IDs of all active subscriptions.\n");
LOG("qubic-cli [...] -getoraclesubscription active+\n");
LOG(" Print information about all active subscriptions.\n");
LOG("qubic-cli [...] -getoraclesubscription contract [CONTRACT_INDEX_OR_NAME]\n");
LOG(" Print the subscription IDs of all active subscriptions that the contract is subscribed to.\n");
LOG("qubic-cli [...] -getoraclesubscription contract+ [CONTRACT_INDEX_OR_NAME]\n");
LOG(" Print information about all active subscriptions that the contract is subscribed to.\n");
exit(1);
}
void processGetMultipleOracleSubscriptions(const char* nodeIp, const int nodePort, unsigned int reqType, const char* reqParam, bool getAllDetails)
{
auto qc = make_qc(nodeIp, nodePort);
int64_t param = 0;
if (reqType == RequestOracleData::requestActiveContractSubscriptions)
{
param = getContractIndex(reqParam);
}
std::vector<int32_t> subIds = receiveSubscriptionIds(qc, reqType, param);
if (!getAllDetails)
{
LOG("Subscription IDs:\n");
for (const int32_t& id : subIds)
{
LOG("- %" PRIi32 "\n", id);
}
}
else
{
LOG("Number of subscription IDs: %d\n\n", (int)subIds.size());
RespondOracleDataSubscription subscription;
std::vector<uint8_t> query;
std::vector<RespondOracleDataSubscriber> subscribers;
for (const int32_t& id : subIds)
{
receiveSubscriptionInformation(qc, id, subscription, query, subscribers);
if (subscription.lastPendingQueryId == 0)
{
LOG("Error getting subscription! Stopping now.\n");
return;
}
printSubscriptionInformation(subscription, query, subscribers);
LOG("\n");
}
}
}
void processGetOracleSubscription(const char* nodeIp, const int nodePort, const char* requestType, const char* reqParam)
{
if (strlen(requestType) == 0)
printGetOracleSubscriptionHelpAndExit();
if (strcasecmp(requestType, "active") == 0)
{
processGetMultipleOracleSubscriptions(nodeIp, nodePort,
RequestOracleData::requestActiveSubscriptions, reqParam,
/*getAllDetails=*/false);
}
else if (strcasecmp(requestType, "active+") == 0)
{
processGetMultipleOracleSubscriptions(nodeIp, nodePort,
RequestOracleData::requestActiveSubscriptions, reqParam,
/*getAllDetails=*/true);
}
else if (strcasecmp(requestType, "contract") == 0)
{
processGetMultipleOracleSubscriptions(nodeIp, nodePort,
RequestOracleData::requestActiveContractSubscriptions, reqParam,
/*getAllDetails=*/false);
}
else if (strcasecmp(requestType, "contract+") == 0)
{
processGetMultipleOracleSubscriptions(nodeIp, nodePort,
RequestOracleData::requestActiveContractSubscriptions, reqParam,
/*getAllDetails=*/true);
}
else