-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathmain.cpp
More file actions
6795 lines (6495 loc) · 287 KB
/
main.cpp
File metadata and controls
6795 lines (6495 loc) · 287 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
/*
This file is part of Octra Wallet (webcli).
Octra Wallet is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
Octra Wallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Octra Wallet. If not, see <http://www.gnu.org/licenses/>.
This program is released under the GPL with the additional exemption
that compiling, linking, and/or using OpenSSL is allowed.
You are free to remove this exemption from derived works.
Copyright 2025-2026 Octra Labs
2025-2026 David A.
2025-2026 Alex T.
2025-2026 Vadim S.
2025-2026 Julia L.
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cctype>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <mutex>
#include <thread>
#include <atomic>
#include <chrono>
#include <optional>
#include <unordered_map>
#ifdef _WIN32
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <signal.h>
#include <sys/resource.h>
#ifdef __linux__
#include <sys/prctl.h>
#endif
#endif
#include "lib/httplib.h"
#include "lib/json.hpp"
extern "C" {
#include "lib/tweetnacl.h"
}
#include "crypto_utils.hpp"
#include "sanitize.hpp"
#include "wallet.hpp"
#include "rpc_client.hpp"
#include "lib/circle_hfhe_receipt.hpp"
#include "lib/tx_builder.hpp"
#include "lib/pvac_bridge.hpp"
#include "lib/stealth.hpp"
#include "lib/txcache.hpp"
using json = nlohmann::json;
static octra::Wallet g_wallet;
static octra::RpcClient g_rpc;
static octra::PvacBridge g_pvac;
static std::mutex g_mtx;
static bool g_pvac_confirmed = false;
static bool g_pvac_ok = false;
static std::atomic<bool> g_wallet_loaded{false};
static std::string g_wallet_path = "data/wallet.oct";
static std::string g_pin;
static TxCache g_txcache;
static nlohmann::json g_fee_cache;
static double g_fee_cache_ts = 0.0;
static std::mutex g_fee_mtx;
struct HistoryRuntimeState {
double last_top_refresh_ts = 0.0;
json rejected = json::array();
int total = 0;
std::unordered_map<std::string, json> pages;
std::unordered_map<std::string, double> page_ts;
};
static std::unordered_map<std::string, HistoryRuntimeState> g_history_runtime;
static std::mutex g_history_runtime_mtx;
struct TokenHistoryRuntimeState {
double ts = 0.0;
json rows = json::array();
int incoming = 0;
int outgoing = 0;
};
static std::unordered_map<std::string, TokenHistoryRuntimeState> g_token_history_runtime;
static std::mutex g_token_history_runtime_mtx;
static std::unordered_map<std::string, std::vector<uint8_t>> g_pk_cache;
static std::mutex g_pk_mtx;
static std::optional<std::vector<uint8_t>> pk_cache_get(const std::string& addr) {
std::lock_guard<std::mutex> lk(g_pk_mtx);
auto it = g_pk_cache.find(addr);
if (it == g_pk_cache.end()) return std::nullopt;
return it->second;
}
static std::string current_public_rpc_url() {
if (g_wallet_loaded) return g_wallet.rpc_url;
const char* env_rpc = std::getenv("OCTRA_RPC_URL");
if (env_rpc && *env_rpc) return env_rpc;
return "http://127.0.0.1:8080";
}
struct RelayProxyResult {
bool ok = false;
int status = 0;
std::string body;
std::string error;
};
static std::string current_circle_relayer_url() {
const char* env_relayer = std::getenv("OCTRA_CIRCLE_RELAYER_URL");
if (env_relayer && *env_relayer) return env_relayer;
return "http://127.0.0.1:9494";
}
static RelayProxyResult relay_http_get(const std::string& path) {
httplib::Client cli(current_circle_relayer_url());
cli.set_connection_timeout(5, 0);
cli.set_read_timeout(30, 0);
auto r = cli.Get(path.c_str());
if (!r) return {false, 502, "", "relay unavailable"};
return {true, r->status, r->body, ""};
}
static RelayProxyResult relay_http_post(const std::string& path, const std::string& body) {
httplib::Client cli(current_circle_relayer_url());
cli.set_connection_timeout(5, 0);
cli.set_read_timeout(30, 0);
auto r = cli.Post(path.c_str(), body, "application/json");
if (!r) return {false, 502, "", "relay unavailable"};
return {true, r->status, r->body, ""};
}
static void pk_cache_put(const std::string& addr, const std::vector<uint8_t>& pk) {
if (pk.size() != 32) return;
std::lock_guard<std::mutex> lk(g_pk_mtx);
if (g_pk_cache.size() > 2048) g_pk_cache.clear();
g_pk_cache[addr] = pk;
}
static void pk_cache_erase(const std::string& addr) {
std::lock_guard<std::mutex> lk(g_pk_mtx);
g_pk_cache.erase(addr);
}
static void handle_signal(int) {
octra::secure_zero(g_wallet.sk, 64);
octra::secure_zero(g_wallet.pk, 32);
if (!g_pin.empty()) octra::secure_zero(&g_pin[0], g_pin.size());
#ifdef _WIN32
ExitProcess(0);
#else
_exit(0);
#endif
}
static double now_ts() {
auto d = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration<double>(d).count();
}
static json err_json(const std::string& msg) {
return {{"error", msg}};
}
static std::string lower_ascii(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
}
static bool starts_with(const std::string& s, const std::string& prefix) {
return s.rfind(prefix, 0) == 0;
}
static bool is_loopback_host(std::string host, int port) {
host = lower_ascii(host);
std::string suffix = ":" + std::to_string(port);
if (host.size() > suffix.size() &&
host.compare(host.size() - suffix.size(), suffix.size(), suffix) == 0) {
host.resize(host.size() - suffix.size());
}
return host == "127.0.0.1" || host == "localhost" || host == "[::1]";
}
static bool is_allowed_webcli_origin(const std::string& origin, int port) {
std::string o = lower_ascii(origin);
std::string suffix = ":" + std::to_string(port);
return o == "http://127.0.0.1" + suffix ||
o == "http://localhost" + suffix ||
o == "http://[::1]" + suffix;
}
static bool webcli_request_allowed(const httplib::Request& req, int port, std::string& reason) {
if (!starts_with(req.path, "/api/")) {
if (req.method != "GET" && req.method != "HEAD" && req.method != "OPTIONS") {
reason = "non-GET on non-api path";
return false;
}
return true;
}
std::string host = req.get_header_value("Host");
if (!host.empty() && !is_loopback_host(host, port)) {
reason = "non-loopback host";
return false;
}
std::string fetch_site = lower_ascii(req.get_header_value("Sec-Fetch-Site"));
if (!fetch_site.empty() && fetch_site != "same-origin" && fetch_site != "none") {
reason = "cross-site fetch";
return false;
}
std::string origin = req.get_header_value("Origin");
if (!origin.empty() && !is_allowed_webcli_origin(origin, port)) {
reason = "cross-origin request";
return false;
}
bool same_origin_fetch = !fetch_site.empty() && (fetch_site == "same-origin" || fetch_site == "none");
bool same_origin_header = !origin.empty() && is_allowed_webcli_origin(origin, port);
bool state_changing = req.method == "POST" || req.method == "PUT" || req.method == "DELETE";
if (state_changing && !same_origin_fetch && !same_origin_header) {
reason = "unverified origin on state-changing request";
return false;
}
return true;
}
static void set_same_origin_cors_if_needed(const httplib::Request& req,
httplib::Response& res,
int port) {
std::string origin = req.get_header_value("Origin");
if (!origin.empty() && is_allowed_webcli_origin(origin, port)) {
res.set_header("Access-Control-Allow-Origin", origin.c_str());
res.set_header("Vary", "Origin");
}
}
static bool is_valid_http_url(const std::string& url) {
bool https = url.rfind("https://", 0) == 0;
bool http = url.rfind("http://", 0) == 0;
if (!https && !http) return false;
std::string rest = url.substr(https ? 8 : 7);
if (rest.empty()) return false;
if (rest.find(' ') != std::string::npos || rest.find('\t') != std::string::npos) return false;
std::string host = rest.substr(0, rest.find('/'));
return !host.empty();
}
static bool tx_status_is_pending_like(const json& tx) {
const std::string status = tx.value("status", "pending");
return status.empty() || status == "pending";
}
static json history_tx_from_lookup(const json& lookup, const json& fallback) {
json tx = fallback;
tx["hash"] = lookup.value("tx_hash", fallback.value("hash", ""));
tx["from"] = lookup.value("from", fallback.value("from", ""));
tx["to_"] = lookup.value("to", lookup.value("to_", fallback.value("to_", fallback.value("to", ""))));
tx["amount_raw"] = lookup.value("amount_raw", lookup.value("amount", fallback.value("amount_raw", "0")));
tx["op_type"] = lookup.value("op_type", fallback.value("op_type", "standard"));
tx["status"] = lookup.value("status", fallback.value("status", "pending"));
double ts = fallback.value("timestamp", 0.0);
if (lookup.contains("timestamp") && lookup["timestamp"].is_number())
ts = lookup["timestamp"].get<double>();
else if (lookup.contains("rejected_at") && lookup["rejected_at"].is_number())
ts = lookup["rejected_at"].get<double>();
tx["timestamp"] = ts;
if (lookup.contains("message") && lookup["message"].is_string() && !lookup["message"].get<std::string>().empty())
tx["message"] = lookup["message"];
if (lookup.contains("encrypted_data") && lookup["encrypted_data"].is_string() && !lookup["encrypted_data"].get<std::string>().empty())
tx["encrypted_data"] = lookup["encrypted_data"];
if (lookup.contains("epoch"))
tx["epoch"] = lookup["epoch"];
else if (lookup.contains("epoch_id"))
tx["epoch"] = lookup["epoch_id"];
if (lookup.contains("block_height"))
tx["block_height"] = lookup["block_height"];
if (lookup.contains("error") && lookup["error"].is_object()) {
tx["reject_reason"] = lookup["error"].value("reason", "");
tx["reject_type"] = lookup["error"].value("type", "");
} else {
tx.erase("reject_reason");
tx.erase("reject_type");
}
return tx;
}
static bool reconcile_history_rows(const std::string& addr, json& txs) {
if (!txs.is_array() || txs.empty()) return false;
std::vector<std::string> methods;
std::vector<json> params_list;
std::vector<size_t> positions;
for (size_t i = 0; i < txs.size(); ++i) {
if (!txs[i].is_object() || !tx_status_is_pending_like(txs[i])) continue;
const std::string hash = txs[i].value("hash", "");
if (hash.empty()) continue;
methods.push_back("octra_transaction");
params_list.push_back(json::array({hash}));
positions.push_back(i);
}
if (methods.empty()) return false;
auto results = g_rpc.call_batch(methods, params_list, 10);
bool changed = false;
for (size_t i = 0; i < results.size() && i < positions.size(); ++i) {
if (!results[i].ok || !results[i].result.is_object()) continue;
const std::string status = results[i].result.value("status", "");
if (status.empty() || status == "pending") continue;
json updated = history_tx_from_lookup(results[i].result, txs[positions[i]]);
txs[positions[i]] = updated;
if (g_txcache.is_open()) g_txcache.store_tx(addr, updated);
changed = true;
}
return changed;
}
static HistoryRuntimeState history_runtime_get(const std::string& addr) {
std::lock_guard<std::mutex> lk(g_history_runtime_mtx);
auto it = g_history_runtime.find(addr);
if (it == g_history_runtime.end()) return {};
return it->second;
}
static void history_runtime_put(const std::string& addr, const HistoryRuntimeState& state) {
std::lock_guard<std::mutex> lk(g_history_runtime_mtx);
g_history_runtime[addr] = state;
}
static void history_runtime_clear(const std::string& addr) {
std::lock_guard<std::mutex> lk(g_history_runtime_mtx);
g_history_runtime.erase(addr);
}
static void history_runtime_clear_all() {
std::lock_guard<std::mutex> lk(g_history_runtime_mtx);
g_history_runtime.clear();
}
static std::optional<TokenHistoryRuntimeState> token_history_runtime_get(const std::string& addr) {
std::lock_guard<std::mutex> lk(g_token_history_runtime_mtx);
auto it = g_token_history_runtime.find(addr);
if (it == g_token_history_runtime.end()) return std::nullopt;
return it->second;
}
static void token_history_runtime_put(const std::string& addr, const TokenHistoryRuntimeState& state) {
std::lock_guard<std::mutex> lk(g_token_history_runtime_mtx);
g_token_history_runtime[addr] = state;
}
static void token_history_runtime_clear(const std::string& addr) {
std::lock_guard<std::mutex> lk(g_token_history_runtime_mtx);
g_token_history_runtime.erase(addr);
}
static void token_history_runtime_clear_all() {
std::lock_guard<std::mutex> lk(g_token_history_runtime_mtx);
g_token_history_runtime.clear();
}
static std::string parse_ou(const json& body, const std::string& fallback) {
std::string val = body.value("ou", "");
if (val.empty()) return fallback;
try {
long long v = std::stoll(val);
if (v > 0) return val;
} catch (...) {}
return fallback;
}
static bool is_octra_address(const std::string& addr) {
return addr.size() == 47 && addr.substr(0, 3) == "oct";
}
static constexpr size_t CIRCLE_ASSET_MAX_RAW_BYTES = 33554432;
static constexpr size_t CIRCLE_ASSET_MAX_B64_BYTES = ((CIRCLE_ASSET_MAX_RAW_BYTES + 2) / 3) * 4;
static size_t circle_asset_decoded_size_upper_bound(size_t wire_len) {
return ((wire_len + 3) / 4) * 3;
}
static int64_t circle_asset_ou_from_b64_len(size_t wire_len) {
const size_t raw_upper_bound = circle_asset_decoded_size_upper_bound(wire_len);
if (raw_upper_bound <= 4096) return 5000;
if (raw_upper_bound <= 16384) return 10000;
if (raw_upper_bound <= 32768) return 20000;
if (raw_upper_bound <= 131072) return 40000;
if (raw_upper_bound <= 524288) return 80000;
if (raw_upper_bound <= 2097152) return 160000;
if (raw_upper_bound <= 8388608) return 320000;
return 640000;
}
static const int64_t MAX_OCT_RAW = 1000000000LL * 1000000LL;
static int64_t parse_amount_raw(const json& body) {
std::string s;
if (body.contains("amount")) {
if (body["amount"].is_string()) s = body["amount"].get<std::string>();
else if (body["amount"].is_number()) {
s = body["amount"].dump();
}
else return -1;
} else return -1;
if (s.empty()) return -1;
size_t dot = s.find('.');
if (dot == std::string::npos) {
for (char c : s) if (c < '0' || c > '9') return -1;
int64_t v = std::stoll(s);
if (v > MAX_OCT_RAW / 1000000) return -1;
return v * 1000000;
}
std::string integer_part = s.substr(0, dot);
std::string frac_part = s.substr(dot + 1);
if (integer_part.empty() && frac_part.empty()) return -1;
for (char c : integer_part) if (c < '0' || c > '9') return -1;
for (char c : frac_part) if (c < '0' || c > '9') return -1;
if (frac_part.size() > 6) return -1;
while (frac_part.size() < 6) frac_part += '0';
int64_t ip = integer_part.empty() ? 0 : std::stoll(integer_part);
if (ip > MAX_OCT_RAW / 1000000) return -1;
int64_t fp = std::stoll(frac_part);
return ip * 1000000 + fp;
}
struct BalanceInfo {
int nonce;
std::string balance_raw;
};
static BalanceInfo get_nonce_balance() {
auto r = g_rpc.get_balance(g_wallet.addr);
if (!r.ok) return {0, "0"};
int nonce = r.result.value("pending_nonce", r.result.value("nonce", 0));
std::string raw = "0";
if (r.result.contains("balance_raw")) {
auto& v = r.result["balance_raw"];
raw = v.is_string() ? v.get<std::string>() : std::to_string(v.get<int64_t>());
} else if (r.result.contains("balance")) {
auto& v = r.result["balance"];
json tmp;
tmp["amount"] = v;
int64_t parsed = parse_amount_raw(tmp);
raw = std::to_string(parsed >= 0 ? parsed : 0);
}
auto pr = g_rpc.staging_view();
if (pr.ok && pr.result.contains("transactions")) {
for (auto& tx : pr.result["transactions"]) {
if (tx.value("from", "") == g_wallet.addr) {
int pn = tx.value("nonce", 0);
if (pn > nonce) nonce = pn;
}
}
}
return {nonce, raw};
}
static void sign_tx_fields(octra::Transaction& tx) {
std::string msg = octra::canonical_json(tx);
tx.signature = octra::ed25519_sign_detached(
reinterpret_cast<const uint8_t*>(msg.data()), msg.size(), g_wallet.sk);
tx.public_key = g_wallet.pub_b64;
}
static std::string sign_circle_read_request(const std::string& op,
const std::string& circle_id,
const std::string& subject = "") {
return octra::sign_circle_read_request(
op,
circle_id,
g_wallet.addr,
subject,
g_wallet.sk);
}
static std::string sign_circle_view_request(const std::string& circle_id,
const std::string& method,
const json& params,
bool include_storage) {
const std::string params_hash = octra::sha256_hex(params.dump());
const std::string subject =
method + "|" + params_hash + "|" + (include_storage ? "1" : "0");
return sign_circle_read_request("octra_circle_view", circle_id, subject);
}
static octra::RpcResult circle_info_auth_rpc(const std::string& circle_id) {
octra::RpcClient rpc(current_public_rpc_url());
return rpc.circle_info_auth(
circle_id,
g_wallet.addr,
g_wallet.pub_b64,
sign_circle_read_request("octra_circle_info", circle_id));
}
static octra::RpcResult circle_hfhe_policy_auth_rpc(const std::string& circle_id) {
octra::RpcClient rpc(current_public_rpc_url());
return rpc.circle_hfhe_policy_auth(
circle_id,
g_wallet.addr,
g_wallet.pub_b64,
sign_circle_read_request("octra_circle_hfhe_policy", circle_id));
}
static octra::RpcResult circle_key_policy_auth_rpc(const std::string& circle_id,
const std::string& key_id) {
octra::RpcClient rpc(current_public_rpc_url());
return rpc.circle_key_policy_auth(
circle_id,
key_id,
g_wallet.addr,
g_wallet.pub_b64,
sign_circle_read_request("octra_circle_key_policy", circle_id, key_id));
}
static octra::RpcResult circle_outbox_status_auth_rpc(const std::string& circle_id,
const std::string& intent_id) {
octra::RpcClient rpc(current_public_rpc_url());
return rpc.circle_outbox_status_auth(
circle_id,
intent_id,
g_wallet.addr,
g_wallet.pub_b64,
sign_circle_read_request("octra_circle_outbox_status", circle_id, intent_id));
}
static bool circle_string_list_contains(const json& values, const std::string& target) {
if (!values.is_array()) return false;
for (const auto& value : values) {
if (value.is_string() && value.get<std::string>() == target) {
return true;
}
}
return false;
}
static bool circle_hfhe_mode_allows(const std::string& mode,
const std::string& owner,
const std::string& caller,
const std::string& subject,
const std::vector<std::string>& active_relays) {
const bool caller_is_active_relay =
std::find(active_relays.begin(), active_relays.end(), caller) != active_relays.end();
if (mode == "deny") return false;
if (mode == "owner_only") return caller == owner;
if (mode == "caller_self") return caller == subject;
if (mode == "owner_or_caller") return caller == owner || caller == subject;
if (mode == "any_registered") return !caller.empty();
if (mode == "active_relay") return caller_is_active_relay;
if (mode == "owner_or_active_relay") return caller == owner || caller_is_active_relay;
return false;
}
static bool circle_hfhe_pk_allowed(const json& policy, const std::string& requested_addr) {
if (!policy.contains("pk_allowlist") || policy["pk_allowlist"].is_null()) {
return true;
}
return circle_string_list_contains(policy["pk_allowlist"], requested_addr);
}
static bool circle_key_policy_live(const std::string& circle_id,
const std::string& key_id,
std::string& error) {
auto r = circle_key_policy_auth_rpc(circle_id, key_id);
if (!r.ok) {
error = r.error.empty() ? "circle key policy read failed" : r.error;
return false;
}
if (!r.result.contains("live") || !r.result["live"].is_boolean()) {
error = "circle key policy live status unavailable";
return false;
}
if (!r.result["live"].get<bool>()) {
error = "circle key policy is not live";
return false;
}
return true;
}
static bool circle_hfhe_active_relays(const std::string& circle_id,
const std::string& intent_id,
std::vector<std::string>& active_relays,
std::string& error) {
auto status_r = circle_outbox_status_auth_rpc(circle_id, intent_id);
if (!status_r.ok) {
error = status_r.error.empty() ? "circle outbox status read failed" : status_r.error;
return false;
}
if (status_r.result.value("status", "") != "claimed") {
error = "circle outbox intent is not actively claimed";
return false;
}
if (!status_r.result.value("claim_ready", false)) {
error = "circle outbox intent relay quorum is not ready";
return false;
}
active_relays.clear();
const auto active_claims = status_r.result.value("active_claims", json::array());
for (const auto& claim : active_claims) {
if (claim.is_object()) {
const std::string relay_id = claim.value("relay_id", "");
if (!relay_id.empty()) {
active_relays.push_back(relay_id);
}
}
}
if (active_relays.empty()) {
error = "circle outbox active relays are unavailable";
return false;
}
return true;
}
static bool circle_hfhe_authorize(const std::string& circle_id,
const std::string& mode_key,
const std::string& requested_addr,
const std::string& key_id,
const std::string& intent_id,
std::string& error) {
auto info_r = circle_info_auth_rpc(circle_id);
if (!info_r.ok) {
error = info_r.error.empty() ? "circle info read failed" : info_r.error;
return false;
}
auto policy_r = circle_hfhe_policy_auth_rpc(circle_id);
if (!policy_r.ok) {
error = policy_r.error.empty() ? "circle hfhe policy read failed" : policy_r.error;
return false;
}
json policy = policy_r.result.value("policy", json::object());
if (mode_key == "load_pk_mode" && !circle_hfhe_pk_allowed(policy, requested_addr)) {
error = "requested pubkey address is not allowed by circle hfhe policy";
return false;
}
const std::string owner = info_r.result.value("owner", "");
const std::string default_mode =
mode_key == "load_pk_mode" ? "caller_self" : "owner_only";
const std::string mode = policy.value(mode_key, default_mode);
std::vector<std::string> active_relays;
if (mode == "active_relay" || mode == "owner_or_active_relay") {
if (intent_id.empty()) {
error = "intent_id required by circle hfhe relay-scoped policy";
return false;
}
if (!circle_hfhe_active_relays(circle_id, intent_id, active_relays, error)) {
return false;
}
}
const std::string subject =
mode_key == "load_pk_mode" ? requested_addr : g_wallet.addr;
if (!circle_hfhe_mode_allows(mode, owner, g_wallet.addr, subject, active_relays)) {
error = "circle hfhe policy denied this operation";
return false;
}
const bool require_live_key_policy = policy.value("require_live_key_policy", true);
if (require_live_key_policy) {
if (key_id.empty()) {
error = "key_id required by circle hfhe policy";
return false;
}
if (!circle_key_policy_live(circle_id, key_id, error)) {
return false;
}
}
return true;
}
static bool circle_decode_zero_proof(const std::string& encoded,
pvac_zero_proof& proof,
std::string& error) {
proof = nullptr;
if (encoded.rfind(octra::ZKZP_PREFIX, 0) != 0) {
error = "invalid zero proof prefix";
return false;
}
auto raw = octra::base64_decode(encoded.substr(std::strlen(octra::ZKZP_PREFIX)));
if (raw.empty()) {
error = "invalid zero proof encoding";
return false;
}
proof = pvac_deserialize_zero_proof(raw.data(), raw.size());
if (!proof) {
error = "invalid zero proof";
return false;
}
return true;
}
static bool circle_verify_zero_with_wallet(const std::string& ciphertext_b64,
const std::string& zero_proof_b64,
std::string& error) {
auto raw = octra::base64_decode(ciphertext_b64);
if (raw.empty()) {
error = "invalid ciphertext";
return false;
}
pvac_cipher ct = g_pvac.deserialize_cipher(raw.data(), raw.size());
if (!ct) {
error = "invalid ciphertext";
return false;
}
pvac_zero_proof proof = nullptr;
if (!circle_decode_zero_proof(zero_proof_b64, proof, error)) {
g_pvac.free_cipher(ct);
return false;
}
bool ok = pvac_verify_zero(g_pvac.pk(), ct, proof) != 0;
pvac_free_zero_proof(proof);
g_pvac.free_cipher(ct);
if (!ok) error = "zero proof verification failed";
return ok;
}
static bool circle_verify_bound_with_wallet(const std::string& ciphertext_b64,
const std::string& zero_proof_b64,
const std::string& amount_commitment_b64,
std::string& error) {
auto raw = octra::base64_decode(ciphertext_b64);
if (raw.empty()) {
error = "invalid ciphertext";
return false;
}
auto commitment = octra::base64_decode(amount_commitment_b64);
if (commitment.size() != 32) {
error = "invalid amount commitment";
return false;
}
pvac_cipher ct = g_pvac.deserialize_cipher(raw.data(), raw.size());
if (!ct) {
error = "invalid ciphertext";
return false;
}
pvac_zero_proof proof = nullptr;
if (!circle_decode_zero_proof(zero_proof_b64, proof, error)) {
g_pvac.free_cipher(ct);
return false;
}
bool ok = pvac_verify_zero_bound(g_pvac.pk(), ct, proof, commitment.data()) != 0;
pvac_free_zero_proof(proof);
g_pvac.free_cipher(ct);
if (!ok) error = "bound proof verification failed";
return ok;
}
static bool circle_verify_range_with_wallet(const std::string& ciphertext_b64,
const std::string& range_proof_b64,
std::string& error) {
if (ciphertext_b64.rfind(octra::HFHE_PREFIX, 0) != 0) {
error = "invalid ciphertext";
return false;
}
if (range_proof_b64.rfind(octra::RP_PREFIX, 0) != 0) {
error = "invalid range proof";
return false;
}
auto raw = octra::base64_decode(ciphertext_b64.substr(strlen(octra::HFHE_PREFIX)));
if (raw.empty()) {
error = "invalid ciphertext";
return false;
}
auto proof_raw = octra::base64_decode(range_proof_b64.substr(strlen(octra::RP_PREFIX)));
if (proof_raw.empty()) {
error = "invalid range proof";
return false;
}
pvac_cipher ct = g_pvac.deserialize_cipher(raw.data(), raw.size());
if (!ct) {
error = "invalid ciphertext";
return false;
}
bool ok = pvac_verify_range_any(g_pvac.pk(), ct, proof_raw.data(), proof_raw.size()) != 0;
g_pvac.free_cipher(ct);
if (!ok) error = "range proof verification failed";
return ok;
}
static std::string circle_hfhe_policy_hash(const json& policy) {
return octra::sha256_hex(policy.dump());
}
static std::string circle_hfhe_receipt_class_value(const json& policy) {
std::string receipt_class = policy.value("proof_receipt_class", "");
if (!receipt_class.empty()) {
return receipt_class;
}
if (policy.value("require_receipt_transport_binding", false)) {
return "transport_bound";
}
return "detached";
}
static bool circle_hfhe_receipt_required(const std::string& proof_kind) {
return proof_kind == "zero_receipt_v1" ||
proof_kind == "range_receipt_v1" ||
proof_kind == "bound_zero_receipt_v1";
}
static bool circle_hfhe_proof_requires_commitment(const std::string& proof_kind) {
return proof_kind == "bound_zero_v1" || proof_kind == "bound_zero_receipt_v1";
}
static bool circle_hfhe_proof_is_range(const std::string& proof_kind) {
return proof_kind == "range_v1" || proof_kind == "range_receipt_v1";
}
static bool circle_hfhe_receipt_transport_bound(const json& policy,
const std::string& intent_id,
std::string& error) {
const std::string receipt_class = circle_hfhe_receipt_class_value(policy);
if ((receipt_class == "transport_bound" || receipt_class == "relay_witnessed") &&
intent_id.empty()) {
error = "intent_id required by circle hfhe receipt binding policy";
return false;
}
return true;
}
static bool circle_hfhe_receipt_signer_allowed(const std::string& circle_id,
const json& policy,
const std::string& caller_addr,
const std::string& signer_addr,
const std::string& intent_id,
std::string& error) {
auto info_r = circle_info_auth_rpc(circle_id);
if (!info_r.ok) {
error = info_r.error.empty() ? "circle info read failed" : info_r.error;
return false;
}
const std::string owner = info_r.result.value("owner", "");
const std::string mode = policy.value("proof_receipt_signer_mode", "caller_self");
const std::string receipt_class = circle_hfhe_receipt_class_value(policy);
std::vector<std::string> active_relays;
if (mode == "active_relay" || mode == "owner_or_active_relay" ||
receipt_class == "relay_witnessed") {
if (intent_id.empty()) {
error = "intent_id required by circle hfhe receipt signer policy";
return false;
}
if (!circle_hfhe_active_relays(circle_id, intent_id, active_relays, error)) {
return false;
}
}
if (receipt_class == "relay_witnessed" &&
std::find(active_relays.begin(), active_relays.end(), signer_addr) == active_relays.end()) {
error = "circle hfhe receipt signer must be an active relay";
return false;
}
if (!circle_hfhe_mode_allows(mode, owner, signer_addr, caller_addr, active_relays)) {
error = "circle hfhe receipt signer is not allowed by policy";
return false;
}
return true;
}
static bool circle_hfhe_receipt_context(const std::string& circle_id,
const std::string& verb,
const std::string& caller_addr,
const std::string& key_id,
const std::string& intent_id,
const std::string& proof_kind,
const json& policy,
const std::string& ciphertext_b64,
const std::string& amount_commitment_b64,
octra::CircleHfheReceiptContext& ctx,
std::string& error) {
if (!circle_hfhe_receipt_transport_bound(policy, intent_id, error)) {
return false;
}
std::string ciphertext_hash = octra::circle_hfhe_hash_ciphertext(ciphertext_b64, error);
if (ciphertext_hash.empty()) {
return false;
}
std::string amount_commitment_hash;
if (!amount_commitment_b64.empty()) {
amount_commitment_hash = octra::circle_hfhe_hash_commitment(amount_commitment_b64, error);
if (amount_commitment_hash.empty()) {
return false;
}
}
ctx = {
circle_id,
caller_addr,
key_id,
intent_id,
verb,
proof_kind,
circle_hfhe_policy_hash(policy),
ciphertext_hash,
amount_commitment_hash
};
return true;
}
static bool circle_verify_proof_receipt(const std::string& circle_id,
const std::string& verb,
const std::string& caller_addr,
const std::string& key_id,
const std::string& intent_id,
const std::string& proof_kind,
const json& policy,
const std::string& ciphertext_b64,
const std::string& amount_commitment_b64,
const json& receipt,
std::string& error) {
octra::CircleHfheReceiptContext ctx;
if (!circle_hfhe_receipt_context(
circle_id,
verb,
caller_addr,
key_id,
intent_id,
proof_kind,
policy,
ciphertext_b64,
amount_commitment_b64,
ctx,
error)) {
return false;
}
if (!octra::verify_circle_hfhe_receipt_json(receipt, ctx, error)) {
return false;
}
return circle_hfhe_receipt_signer_allowed(
circle_id,
policy,
ctx.caller_addr,
receipt.value("signer_addr", ""),
ctx.intent_id,
error);
}
static json submit_tx(const octra::Transaction& tx) {
json j;
j["from"] = tx.from;
j["to_"] = tx.to_;
j["amount"] = tx.amount;
j["nonce"] = tx.nonce;
j["ou"] = tx.ou;
j["timestamp"] = tx.timestamp;
j["signature"] = tx.signature;
j["public_key"] = tx.public_key;
if (!tx.op_type.empty()) j["op_type"] = tx.op_type;
if (!tx.encrypted_data.empty()) j["encrypted_data"] = tx.encrypted_data;
if (!tx.message.empty()) j["message"] = tx.message;
auto r = g_rpc.submit_tx(j);
if (!r.ok) return err_json(r.error);
json res;
std::string tx_hash = r.result.value("tx_hash", "");
res["tx_hash"] = tx_hash;
if (!tx_hash.empty()) {
json cached;
cached["hash"] = tx_hash;
cached["from"] = tx.from;
cached["to_"] = tx.to_;
cached["amount_raw"] = tx.amount;
cached["op_type"] = tx.op_type.empty() ? "standard" : tx.op_type;
cached["status"] = "pending";
cached["timestamp"] = tx.timestamp;
if (!tx.encrypted_data.empty()) cached["encrypted_data"] = tx.encrypted_data;
if (!tx.message.empty()) cached["message"] = tx.message;
if (g_txcache.is_open()) {
bool known = g_txcache.has_tx(tx_hash);
g_txcache.store_tx(g_wallet.addr, cached);
if (!known) {
int cached_total = g_txcache.get_total(g_wallet.addr);
g_txcache.set_total(g_wallet.addr, cached_total + 1);
}
}
history_runtime_clear(g_wallet.addr);
token_history_runtime_clear(g_wallet.addr);