forked from monero-project/monero
-
Notifications
You must be signed in to change notification settings - Fork 116
/
oxen_name_system.cpp
2875 lines (2536 loc) · 114 KB
/
oxen_name_system.cpp
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 "oxen_name_system.h"
#include <oxenc/base32z.h>
#include <oxenc/base64.h>
#include <oxenc/hex.h>
#include <sqlite3.h>
#include <algorithm>
#include <bitset>
#include <iterator>
#include <variant>
#include <vector>
#include "common/fs-format.h"
#include "common/hex.h"
#include "common/oxen.h"
#include "common/string_util.h"
#include "crypto/hash.h"
#include "cryptonote_basic/cryptonote_basic.h"
#include "cryptonote_basic/cryptonote_basic_impl.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_basic/tx_extra.h"
#include "cryptonote_config.h"
#include "cryptonote_core/blockchain.h"
#include "oxen_economy.h"
extern "C" {
#include <sodium/crypto_aead_xchacha20poly1305.h>
#include <sodium/crypto_generichash.h>
#include <sodium/crypto_generichash_blake2b.h>
#include <sodium/crypto_pwhash.h>
#include <sodium/crypto_secretbox.h>
#include <sodium/crypto_sign.h>
#include <sodium/randombytes.h>
}
using cryptonote::hf;
namespace ons {
namespace log = oxen::log;
static auto logcat = log::Cat("ons");
enum struct ons_sql_type {
save_owner,
save_setting,
save_mapping,
pruning,
get_sentinel_start,
get_mapping,
get_mappings,
get_mappings_by_owner,
get_mappings_by_owners,
get_mapping_counts,
get_owner,
get_setting,
get_sentinel_end,
internal_cmd,
};
enum struct ons_db_setting_column {
id,
top_height,
top_hash,
version,
};
enum struct owner_record_column {
id,
address,
};
enum struct mapping_record_column {
id,
type,
name_hash,
encrypted_value,
txid,
owner_id,
backup_owner_id,
update_height,
expiration_height,
_count,
};
static constexpr unsigned char OLD_ENCRYPTION_NONCE[crypto_secretbox_NONCEBYTES] = {};
std::pair<std::basic_string_view<unsigned char>, std::basic_string_view<unsigned char>>
ons::mapping_value::value_nonce(mapping_type type) const {
std::pair<std::basic_string_view<unsigned char>, std::basic_string_view<unsigned char>> result;
auto& [head, tail] = result;
head = {buffer.data(), len};
if ((type == mapping_type::session &&
len != SESSION_PUBLIC_KEY_BINARY_LENGTH + crypto_aead_xchacha20poly1305_ietf_ABYTES +
crypto_aead_xchacha20poly1305_ietf_NPUBBYTES) ||
len < crypto_aead_xchacha20poly1305_ietf_NPUBBYTES /* shouldn't occur, but just in case */)
tail = {OLD_ENCRYPTION_NONCE, sizeof(OLD_ENCRYPTION_NONCE)};
else {
tail = head.substr(len - crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
head.remove_suffix(crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
}
return result;
}
std::string ons::mapping_value::to_readable_value(
cryptonote::network_type nettype, ons::mapping_type type) const {
std::string result;
if (is_lokinet_type(type)) {
result = oxenc::to_base32z(to_view()) + ".loki";
} else if (type == ons::mapping_type::wallet) {
std::optional<cryptonote::address_parse_info> addr = get_wallet_address_info();
if (addr) {
result = cryptonote::get_account_address_as_str(
nettype, (*addr).is_subaddress, (*addr).address);
} else {
result = oxenc::to_hex(to_view());
}
} else {
result = oxenc::to_hex(to_view());
}
return result;
}
namespace {
std::string ons_extra_string(
cryptonote::network_type nettype, cryptonote::tx_extra_oxen_name_system const& data) {
std::string extra = "ONS Extra={";
auto append = std::back_inserter(extra);
if (data.is_buying())
fmt::format_to(
append,
"owner={}, backup_owner={}",
data.owner.to_string(nettype),
(data.backup_owner ? data.backup_owner.to_string(nettype) : "(none)"));
else if (data.is_renewing())
extra += "renewal";
else
fmt::format_to(append, "signature={}", tools::type_to_hex(data.signature.data));
fmt::format_to(append, ", type={}, name_hash={}}}", data.type, data.name_hash);
return extra;
}
/// Clears any existing bindings
bool clear_bindings(sql_compiled_statement& s) {
return SQLITE_OK == sqlite3_clear_bindings(s.statement);
}
/// Resets
bool reset(sql_compiled_statement& s) {
return SQLITE_OK == sqlite3_reset(s.statement);
}
int step(sql_compiled_statement& s) {
return sqlite3_step(s.statement);
}
/// `bind()` binds a particular parameter to a statement by index. The bind type is inferred
/// from the argument.
// Small (<=32 bits) integers
template <typename T, std::enable_if_t<std::is_integral_v<T> && (sizeof(T) <= 4), int> = 0>
bool bind(sql_compiled_statement& s, int index, const T& val) {
return SQLITE_OK == sqlite3_bind_int(s.statement, index, val);
}
// Big (>32 bits) integers
template <typename T, std::enable_if_t<std::is_integral_v<T> && (sizeof(T) > 4), int> = 0>
bool bind(sql_compiled_statement& s, int index, const T& val) {
return SQLITE_OK == sqlite3_bind_int64(s.statement, index, val);
}
// Floats/doubles
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
bool bind(sql_compiled_statement& s, int index, const T& val) {
return SQLITE_OK == sqlite3_bind_double(s.statement, index, val);
}
// Binds null
bool bind(sql_compiled_statement& s, int index, std::nullptr_t) {
return SQLITE_OK == sqlite3_bind_null(s.statement, index);
}
// Binds a std::optional<T>: binds a T if set, otherwise binds a NULL
template <typename T>
bool bind(sql_compiled_statement& s, int index, const std::optional<T>& val) {
if (val)
return bind(s, index, *val);
return bind(s, index, nullptr);
}
// text, from a referenced string (which must be kept alive)
bool bind(sql_compiled_statement& s, int index, std::string_view text) {
return SQLITE_OK ==
sqlite3_bind_text(s.statement, index, text.data(), text.size(), nullptr /*dtor*/);
}
/* Currently unused; comment out until needed to avoid a compiler warning
// text, from a temporary std::string; ownership of the string data is transferred to sqlite3
bool bind(sql_compiled_statement& s, int index, std::string&& text)
{
// Assume ownership and let sqlite3 destroy when finished
auto local_text = new std::string{std::move(text)};
if (SQLITE_OK == sqlite3_bind_text(s.statement, index, local_text->data(), local_text->size(),
[](void* local) { delete reinterpret_cast<std::string*>(local); }))
return true;
delete local_text;
return false;
}
*/
// Simple decorator around a string_view so that you can pass a blob into `bind` by wrapping it
// with a `blob_view` such as:
//
// bind(s, 123, blob_view{data, size});
// auto data = get<blob_view>(s, 2);
//
struct blob_view {
std::string_view data;
/// Constructor that simply forwards anything to the `data` (string_view) member constructor
template <typename... T>
explicit blob_view(T&&... args) : data{std::forward<T>(args)...} {}
blob_view(const unsigned char* data, size_t size) :
blob_view{reinterpret_cast<const char*>(data), size} {}
};
// Binds a blob wrapped in a blob_view decorator
bool bind(sql_compiled_statement& s, int index, blob_view blob) {
return SQLITE_OK ==
sqlite3_bind_blob(
s.statement, index, blob.data.data(), blob.data.size(), nullptr /*dtor*/);
}
// Binds a variant of bindable types; calls one of the above according to the contained type
template <typename... T>
bool bind(sql_compiled_statement& s, int index, const std::variant<T...>& v) {
return var::visit([&](const auto& val) { return ons::bind(s, index, val); }, v);
}
template <typename T>
constexpr bool is_int_enum_impl() {
if constexpr (std::is_enum_v<T>)
return std::is_same_v<std::underlying_type_t<T>, int>;
else
return false;
}
template <typename T>
constexpr bool is_int_enum = is_int_enum_impl<T>();
// Binds, but gives index as an enum class
template <typename T, typename I, std::enable_if_t<is_int_enum<I>, int> = 0>
bool bind(sql_compiled_statement& s, I index, T&& val) {
return ons::bind(s, static_cast<int>(index), std::forward<T>(val));
}
template <int... I, typename... T>
bool bind_all_impl(sql_compiled_statement& s, std::integer_sequence<int, I...>, T&&... args) {
clear_bindings(s);
for (bool r : {ons::bind(s, I + 1, std::forward<T>(args))...})
if (!r)
return false;
return true;
}
// Full statement binding; this lets you do something like:
//
// bind_all(st, 1, "hi", 123);
//
// which is equivalent to:
//
// clear_bindings(st);
// st.bind(st, 1, 1);
// st.bind(st, 2, "hi");
// st.bind(st, 3, 123);
//
// (Binding of blobs through this interface is not supported).
template <typename... T>
bool bind_all(sql_compiled_statement& s, T&&... args) {
return bind_all_impl(
s, std::make_integer_sequence<int, sizeof...(T)>{}, std::forward<T>(args)...);
}
// Full statement binding from a container of bind()-able values; clears existing bindings, then
// binds the contained values.
template <typename Container>
bool bind_container(sql_compiled_statement& s, const Container& c) {
clear_bindings(s);
int bind_pos = 1;
for (const auto& v : c)
if (!ons::bind(s, bind_pos++, v))
return false;
return true;
}
/// Retrieve a type from an executed statement.
// Small (<=32 bits) integers
template <typename T, std::enable_if_t<std::is_integral_v<T> && (sizeof(T) <= 32), int> = 0>
T get(sql_compiled_statement& s, int index) {
return static_cast<T>(sqlite3_column_int(s.statement, index));
}
// Big (>32 bits) integers
template <typename T, std::enable_if_t<std::is_integral_v<T> && (sizeof(T) > 32), int> = 0>
T get(sql_compiled_statement& s, int index) {
return static_cast<T>(sqlite3_column_int64(s.statement, index));
}
// Floats/doubles
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
T get(sql_compiled_statement& s, int index) {
return static_cast<T>(sqlite3_column_double(s.statement, index));
}
// text, via a string_view pointing at the text data
template <typename T, std::enable_if_t<std::is_same_v<T, std::string_view>, int> = 0>
std::string_view get(sql_compiled_statement& s, int index) {
return {reinterpret_cast<const char*>(sqlite3_column_text(s.statement, index)),
static_cast<size_t>(sqlite3_column_bytes(s.statement, index))};
}
// text, copied into a std::string
template <typename T, std::enable_if_t<std::is_same_v<T, std::string>, int> = 0>
std::string get(sql_compiled_statement& s, int index) {
return {reinterpret_cast<const char*>(sqlite3_column_text(s.statement, index)),
static_cast<size_t>(sqlite3_column_bytes(s.statement, index))};
}
// blob_view pointing at the blob data
template <typename T, std::enable_if_t<std::is_same_v<T, blob_view>, int> = 0>
blob_view get(sql_compiled_statement& s, int index) {
return blob_view{
reinterpret_cast<const char*>(sqlite3_column_blob(s.statement, index)),
static_cast<size_t>(sqlite3_column_bytes(s.statement, index))};
}
template <typename T>
constexpr bool is_optional = false;
template <typename T>
constexpr bool is_optional<std::optional<T>> = true;
// Gets a potentially null value; returns a std::nullopt if the column contains NULL, otherwise
// return a value via get<T>(...).
template <typename T, std::enable_if_t<is_optional<T>, int> = 0>
T get(sql_compiled_statement& s, int index) {
if (sqlite3_column_type(s.statement, index) == SQLITE_NULL)
return std::nullopt;
return get<typename T::value_type>(s, index);
}
// Forwards to any of the above, but takes an enum class instead of an int
template <typename T, typename I, std::enable_if_t<is_int_enum<I>, int> = 0>
T get(sql_compiled_statement& s, I index) {
return get<T>(s, static_cast<int>(index));
}
// Wrapper around get that assigns to the given reference.
// get(st, 3, myvar);
// is equivalent to:
// myvar = get<decltype(myvar)>(st, 3)
template <typename T, typename I>
void get(sql_compiled_statement& s, I index, T& val) {
val = get<T>(s, index);
}
template <typename I>
bool sql_copy_blob(sql_compiled_statement& statement, I column, void* dest, size_t dest_size) {
auto blob = get<blob_view>(statement, column);
if (blob.data.size() != dest_size) {
log::warning(
logcat,
"Unexpected blob size={}, in ONS DB does not match expected size={}",
blob.data.size(),
dest_size);
assert(blob.data.size() == dest_size);
return false;
}
std::memcpy(dest, blob.data.data(), blob.data.size());
return true;
}
mapping_record sql_get_mapping_from_statement(sql_compiled_statement& statement) {
mapping_record result = {};
auto type_int = get<uint16_t>(statement, mapping_record_column::type);
if (type_int >= tools::enum_count<mapping_type>)
return result;
result.type = static_cast<mapping_type>(type_int);
get(statement, mapping_record_column::id, result.id);
get(statement, mapping_record_column::update_height, result.update_height);
get(statement, mapping_record_column::expiration_height, result.expiration_height);
get(statement, mapping_record_column::owner_id, result.owner_id);
get(statement, mapping_record_column::backup_owner_id, result.backup_owner_id);
// Copy encrypted_value
{
auto value = get<std::string_view>(statement, mapping_record_column::encrypted_value);
if (value.size() > result.encrypted_value.buffer.size()) {
log::error(
logcat,
"Unexpected encrypted value blob with size={}, in ONS db larger than the "
"available size={}",
value.size(),
result.encrypted_value.buffer.size());
return result;
}
result.encrypted_value.len = value.size();
result.encrypted_value.encrypted = true;
std::memcpy(&result.encrypted_value.buffer[0], value.data(), value.size());
}
// Copy name hash
{
auto value = get<std::string_view>(statement, mapping_record_column::name_hash);
result.name_hash.append(value.data(), value.size());
}
if (!sql_copy_blob(
statement, mapping_record_column::txid, result.txid.data(), result.txid.size()))
return result;
int owner_column = tools::enum_count<mapping_record_column>;
if (!sql_copy_blob(statement, owner_column, &result.owner, sizeof(result.owner)))
return result;
if (result.backup_owner_id > 0) {
if (!sql_copy_blob(
statement,
owner_column + 1,
&result.backup_owner,
sizeof(result.backup_owner)))
return result;
}
result.loaded = true;
return result;
}
bool sql_run_statement(ons_sql_type type, sql_compiled_statement& statement, void* context) {
assert(statement);
bool data_loaded = false;
bool result = false;
for (bool infinite_loop = true; infinite_loop;) {
int step_result = step(statement);
switch (step_result) {
case SQLITE_ROW: {
switch (type) {
default:
log::error(
logcat,
"Unhandled ons type enum with value: {}, in: {}",
(int)type,
__func__);
break;
case ons_sql_type::internal_cmd: break;
case ons_sql_type::get_owner: {
auto* entry = reinterpret_cast<owner_record*>(context);
get(statement, owner_record_column::id, entry->id);
if (!sql_copy_blob(
statement,
owner_record_column::address,
&entry->address,
sizeof(entry->address)))
return false;
data_loaded = true;
} break;
case ons_sql_type::get_setting: {
auto* entry = reinterpret_cast<settings_record*>(context);
get(statement, ons_db_setting_column::top_height, entry->top_height);
if (!sql_copy_blob(
statement,
ons_db_setting_column::top_hash,
entry->top_hash.data(),
entry->top_hash.size()))
return false;
get(statement, ons_db_setting_column::version, entry->version);
data_loaded = true;
} break;
case ons_sql_type::get_mappings_by_owners: [[fallthrough]];
case ons_sql_type::get_mappings_by_owner: [[fallthrough]];
case ons_sql_type::get_mappings: [[fallthrough]];
case ons_sql_type::get_mapping: {
if (mapping_record tmp_entry =
sql_get_mapping_from_statement(statement)) {
data_loaded = true;
if (type == ons_sql_type::get_mapping)
*static_cast<mapping_record*>(context) = std::move(tmp_entry);
else
static_cast<std::vector<mapping_record>*>(context)->push_back(
std::move(tmp_entry));
}
} break;
case ons_sql_type::get_mapping_counts: {
auto& counts = *static_cast<std::map<mapping_type, int>*>(context);
std::underlying_type_t<mapping_type> type_val;
int count;
get(statement, 0, type_val);
get(statement, 1, count);
counts.emplace(static_cast<mapping_type>(type_val), count);
data_loaded = true;
}
}
} break;
case SQLITE_BUSY: break;
case SQLITE_DONE: {
infinite_loop = false;
result = (type > ons_sql_type::get_sentinel_start &&
type < ons_sql_type::get_sentinel_end)
? data_loaded
: true;
break;
}
default: {
log::info(
logcat,
"Failed to execute statement: {}, reason: {}",
sqlite3_sql(statement.statement),
sqlite3_errstr(step_result));
infinite_loop = false;
break;
}
}
}
reset(statement);
clear_bindings(statement);
return result;
}
/// Does a clear_bindings, bind_all, and then sql_run_statement. First three arguments go to
/// sql_run_statement, the rest go to bind_all(statement, ...) (which does the clear_bindings).
template <typename... T>
bool bind_and_run(
ons_sql_type type, sql_compiled_statement& statement, void* context, T&&... bind_args) {
bind_all(statement, std::forward<T>(bind_args)...);
return sql_run_statement(type, statement, context);
}
} // end anonymous namespace
using namespace std::literals;
using stringtypemap = std::pair<std::string_view, mapping_type>;
static constexpr std::array ons_str_type_mappings = {
stringtypemap{"5"sv, mapping_type::lokinet_10years},
stringtypemap{"4"sv, mapping_type::lokinet_5years},
stringtypemap{"3"sv, mapping_type::lokinet_2years},
stringtypemap{"2"sv, mapping_type::lokinet},
stringtypemap{"1"sv, mapping_type::wallet},
stringtypemap{"0"sv, mapping_type::session},
stringtypemap{"session"sv, mapping_type::session},
stringtypemap{"wallet"sv, mapping_type::wallet},
stringtypemap{"lokinet"sv, mapping_type::lokinet},
stringtypemap{"lokinet_2years"sv, mapping_type::lokinet_2years},
stringtypemap{"lokinet_5years"sv, mapping_type::lokinet_5years},
stringtypemap{"lokinet_10years"sv, mapping_type::lokinet_10years}};
std::optional<mapping_type> parse_ons_type(std::string input) {
// Lower-case the input:
for (auto& c : input)
if (c >= 'A' && c <= 'Z')
c += ('A' - 'a');
for (const auto& [str, map] : ons_str_type_mappings)
if (str == input)
return map;
return std::nullopt;
}
using inttypemap = std::pair<uint16_t, mapping_type>;
static constexpr std::array ons_int_type_mappings = {
inttypemap{5, mapping_type::lokinet_10years},
inttypemap{4, mapping_type::lokinet_5years},
inttypemap{3, mapping_type::lokinet_2years},
inttypemap{2, mapping_type::lokinet},
inttypemap{1, mapping_type::wallet},
inttypemap{0, mapping_type::session}};
std::optional<mapping_type> parse_ons_type(uint16_t input) {
for (const auto& [inttype, map] : ons_int_type_mappings)
if (inttype == input)
return map;
return std::nullopt;
}
bool mapping_record::active(uint64_t blockchain_height) const {
if (!loaded)
return false;
return !expiration_height || blockchain_height <= *expiration_height;
}
bool sql_compiled_statement::compile(std::string_view query, bool optimise_for_multiple_usage) {
sqlite3_stmt* st;
#if SQLITE_VERSION_NUMBER >= 3020000
int prepare_result = sqlite3_prepare_v3(
nsdb.db,
query.data(),
query.size(),
optimise_for_multiple_usage ? SQLITE_PREPARE_PERSISTENT : 0,
&st,
nullptr /*pzTail*/);
#else
int prepare_result =
sqlite3_prepare_v2(nsdb.db, query.data(), query.size(), &st, nullptr /*pzTail*/);
#endif
if (prepare_result != SQLITE_OK) {
log::error(
logcat,
"Can not compile SQL statement:\n{}\nReason: {}",
query,
sqlite3_errstr(prepare_result));
return false;
}
sqlite3_finalize(statement);
statement = st;
return true;
}
sql_compiled_statement& sql_compiled_statement::operator=(sql_compiled_statement&& from) {
sqlite3_finalize(statement);
statement = from.statement;
from.statement = nullptr;
return *this;
}
sql_compiled_statement::~sql_compiled_statement() {
sqlite3_finalize(statement);
}
sqlite3* init_oxen_name_system(const fs::path& file_path, bool read_only) {
sqlite3* result = nullptr;
int sql_init = sqlite3_initialize();
if (sql_init != SQLITE_OK) {
log::error(logcat, "Failed to initialize sqlite3: {}", sqlite3_errstr(sql_init));
return nullptr;
}
int const flags = read_only ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
int sql_open = sqlite3_open_v2(file_path.u8string().c_str(), &result, flags, nullptr);
if (sql_open != SQLITE_OK) {
log::error(
logcat,
"Failed to open ONS db at: {}, reason: {}",
file_path,
sqlite3_errstr(sql_open));
return nullptr;
}
/*
(DB) Changes are appended into a separate WAL (Write Ahead Logging) file.
A COMMIT occurs when a special record indicating a commit is appended to
the WAL. Thus a COMMIT can happen without ever writing to the original
database, which allows readers to continue operating from the original
unaltered database while changes are simultaneously being committed into the
WAL. Multiple transactions can be appended to the end of a single WAL file.
*/
int exec = sqlite3_exec(result, "PRAGMA journal_mode = WAL", nullptr, nullptr, nullptr);
if (exec != SQLITE_OK) {
log::error(logcat, "Failed to set journal mode to WAL: {}", sqlite3_errstr(exec));
return nullptr;
}
/*
In WAL mode when synchronous is NORMAL (1), the WAL file is synchronized
before each checkpoint and the database file is synchronized after each
completed checkpoint and the WAL file header is synchronized when a WAL file
begins to be reused after a checkpoint, but no sync operations occur during
most transactions.
*/
exec = sqlite3_exec(result, "PRAGMA synchronous = NORMAL", nullptr, nullptr, nullptr);
if (exec != SQLITE_OK) {
log::error(logcat, "Failed to set synchronous mode to NORMAL: {}", sqlite3_errstr(exec));
return nullptr;
}
return result;
}
std::vector<mapping_type> all_mapping_types(hf hf_version) {
std::vector<mapping_type> result;
result.reserve(2);
if (hf_version >= hf::hf15_ons)
result.push_back(mapping_type::session);
if (hf_version >= hf::hf16_pulse)
result.push_back(mapping_type::lokinet);
if (hf_version >= hf::hf18)
result.push_back(mapping_type::wallet);
return result;
}
std::optional<uint64_t> expiry_blocks(cryptonote::network_type nettype, mapping_type type) {
std::optional<uint64_t> result;
if (is_lokinet_type(type)) {
// For testnet we shorten 1-, 2-, and 5-year renewals to 1/2/5 days with 1-day renewal, but
// leave 10 years alone to allow long-term registrations on testnet.
const bool testnet_short = nettype == cryptonote::network_type::TESTNET &&
type != mapping_type::lokinet_10years;
result = cryptonote::BLOCKS_PER_DAY * REGISTRATION_YEAR_DAYS *
(type == mapping_type::lokinet ? 1
: type == mapping_type::lokinet_2years ? 2
: type == mapping_type::lokinet_5years ? 5
: type == mapping_type::lokinet_10years ? 10
: 0);
assert(result && *result);
if (testnet_short)
*result /= REGISTRATION_YEAR_DAYS;
else if (nettype == cryptonote::network_type::FAKECHAIN) // For fakenet testing we shorten
// 1/2/5/10 years to 2/4/10/20
// blocks
*result /= (cryptonote::BLOCKS_PER_DAY * REGISTRATION_YEAR_DAYS / 2);
}
return result;
}
static void append_owner(std::string& buffer, const ons::generic_owner* owner) {
if (owner) {
buffer += static_cast<char>(owner->type);
buffer += owner->type == ons::generic_owner_sig_type::ed25519
? tools::view_guts(owner->ed25519)
: tools::view_guts(owner->wallet.address);
}
}
std::string tx_extra_signature(
std::string_view value,
ons::generic_owner const* owner,
ons::generic_owner const* backup_owner,
crypto::hash const& prev_txid) {
static_assert(
sizeof(crypto::hash) == crypto_generichash_BYTES,
"Using libsodium generichash for signature hash, require we fit into crypto::hash");
if (value.size() > mapping_value::BUFFER_SIZE) {
log::error(
logcat,
"Unexpected value len={} greater than the expected capacity={}",
value.size(),
mapping_value::BUFFER_SIZE);
return ""s;
}
std::string result;
result.reserve(
mapping_value::BUFFER_SIZE + sizeof(*owner) + sizeof(*backup_owner) +
sizeof(prev_txid));
result += value;
append_owner(result, owner);
append_owner(result, backup_owner);
result += tools::view_guts(prev_txid);
return result;
}
ons::generic_signature make_ed25519_signature(
crypto::hash const& hash, crypto::ed25519_secret_key const& skey) {
ons::generic_signature result = {};
result.type = ons::generic_owner_sig_type::ed25519;
crypto_sign_detached(result.ed25519.data(), NULL, hash.data(), hash.size(), skey.data());
return result;
}
ons::generic_owner make_monero_owner(
cryptonote::account_public_address const& owner, bool is_subaddress) {
ons::generic_owner result = {};
result.type = ons::generic_owner_sig_type::monero;
result.wallet.address = owner;
result.wallet.is_subaddress = is_subaddress;
return result;
}
ons::generic_owner make_ed25519_owner(crypto::ed25519_public_key const& pkey) {
ons::generic_owner result = {};
result.type = ons::generic_owner_sig_type::ed25519;
result.ed25519 = pkey;
return result;
}
bool parse_owner_to_generic_owner(
cryptonote::network_type nettype,
std::string_view owner,
generic_owner& result,
std::string* reason) {
cryptonote::address_parse_info parsed_addr;
crypto::ed25519_public_key ed_owner;
if (cryptonote::get_account_address_from_str(parsed_addr, nettype, owner)) {
result = ons::make_monero_owner(parsed_addr.address, parsed_addr.is_subaddress);
} else if (owner.size() == 2 * ed_owner.size() && oxenc::is_hex(owner)) {
oxenc::from_hex(owner.begin(), owner.end(), ed_owner.data());
result = ons::make_ed25519_owner(ed_owner);
} else {
if (reason) {
char const* type_heuristic = (owner.size() == sizeof(crypto::ed25519_public_key) * 2)
? "ED25519 Key"
: "Wallet address";
*reason = type_heuristic;
*reason += " provided could not be parsed owner=";
*reason += owner;
}
return false;
}
return true;
}
// Returns true if the character is numeric, *lower-case* a-z, or any of the template char values.
template <char... Extra>
static constexpr bool char_is_alphanum_or(char c) {
bool result = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (... || (c == Extra));
return result;
}
// Same as above with no extra char values.
static constexpr bool char_is_alphanum(char c) {
return char_is_alphanum_or<>(c);
}
template <typename... T>
static bool check_condition(
bool condition, std::string* reason, std::string_view format, T&&... args) {
if (condition && reason)
*reason = fmt::format(format, std::forward<T>(args)...);
return condition;
}
bool validate_ons_name(mapping_type type, std::string name, std::string* reason) {
bool const is_lokinet = is_lokinet_type(type);
size_t max_name_len = 0;
if (is_lokinet)
max_name_len = name.find('-') != std::string::npos ? LOKINET_DOMAIN_NAME_MAX
: LOKINET_DOMAIN_NAME_MAX_NOHYPHEN;
else if (type == mapping_type::session)
max_name_len = ons::SESSION_DISPLAY_NAME_MAX;
else if (type == mapping_type::wallet)
max_name_len = ons::WALLET_NAME_MAX;
else {
if (reason)
*reason =
"ONS type={} specifies unhandled mapping type in name validation"_format(type);
return false;
}
// NOTE: Validate name length
name = tools::lowercase_ascii_string(name);
if (check_condition(
(name.empty() || name.size() > max_name_len),
reason,
"ONS type={} specifies mapping from name->value where the name's length={} is 0 or "
"exceeds the maximum length={}, given name={}",
type,
name.size(),
max_name_len,
name))
return false;
std::string_view name_view{name}; // Will chop this down as we validate each part
// NOTE: Validate domain specific requirements
if (is_lokinet) {
// LOKINET
// Domain has to start with an alphanumeric, and can have (alphanumeric or hyphens) in
// between, the character before the suffix <char>'.loki' must be alphanumeric followed by
// the suffix '.loki' It's *approximately* this regex, but there are some extra restrictions
// below
// ^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.loki$
// Reserved names:
// - localhost.loki has special meaning within lokinet (it is always a CNAME to the local
// address)
// - loki.loki and snode.loki are prohibited in case someone added .loki or .snode as search
// domains (in which case the user looking up "foo.loki" would try end up trying to
// resolve "foo.loki.loki").
for (auto& reserved : {"localhost.loki"sv, "loki.loki"sv, "snode.loki"sv})
if (check_condition(
name == reserved,
reason,
"ONS type={} specifies mapping from name->value using protocol reserved "
"name={}",
type,
name))
return false;
auto constexpr SHORTEST_DOMAIN = "a.loki"sv;
if (check_condition(
name.size() < SHORTEST_DOMAIN.size(),
reason,
"ONS type={} specifies mapping from name->value where the name is shorter than "
"the shortest possible name={}, given name={}",
type,
SHORTEST_DOMAIN,
name))
return false;
// Must end with .loki
auto constexpr SUFFIX = ".loki"sv;
if (check_condition(
!tools::ends_with(name_view, SUFFIX),
reason,
"ONS type={} specifies mapping from name->value where the name does not end "
"with the domain .loki, name={}",
type,
name))
return false;
name_view.remove_suffix(SUFFIX.size());
// All domains containing '--' as 3rd/4th letter are reserved except for xn-- punycode
// domains
if (check_condition(
name_view.size() >= 4 && name_view.substr(2, 2) == "--"sv &&
!tools::starts_with(name_view, "xn--"sv),
reason,
"ONS type={} specifies reserved name `?\?--*.loki': {}",
type,
name))
return false;
// Must start with alphanumeric
if (check_condition(
!char_is_alphanum(name_view.front()),
reason,
"ONS type={} specifies mapping from name->value where the name does not start "
"with an alphanumeric character, name={}",
type,
name))
return false;
name_view.remove_prefix(1);
if (!name_view.empty()) {
// Character preceding .loki must be alphanumeric
if (check_condition(
!char_is_alphanum(name_view.back()),
reason,
"ONS type={} specifies mapping from name->value where the character "
"preceding the .loki is not alphanumeric, char={}, name={}",
type,
name_view.back(),
name))
return false;
name_view.remove_suffix(1);
}
// Inbetween start and preceding suffix, (alphanumeric or hyphen) characters permitted
if (check_condition(
!std::all_of(name_view.begin(), name_view.end(), char_is_alphanum_or<'-'>),
reason,
"ONS type={} specifies mapping from name->value where the domain name contains "
"more than the permitted alphanumeric or hyphen characters, name={}",
type,
name))
return false;
} else if (type == mapping_type::session || type == mapping_type::wallet) {
// SESSION & WALLET
// Name has to start with a (alphanumeric or underscore), and can have (alphanumeric,
// hyphens or underscores) in between and must end with a (alphanumeric or underscore)
// ^[a-z0-9_]([a-z0-9-_]*[a-z0-9_])?$
// Must start with (alphanumeric or underscore)
if (check_condition(
!char_is_alphanum_or<'_'>(name_view.front()),
reason,
"ONS type={} specifies mapping from name->value where the name does not start "
"with an alphanumeric or underscore character, name={}",
type,
name))
return false;
name_view.remove_prefix(1);
if (!name_view.empty()) {
// Must NOT end with a hyphen '-'
if (check_condition(
!char_is_alphanum_or<'_'>(name_view.back()),
reason,
"ONS type={} specifies mapping from name->value where the last character "
"is a hyphen '-' which is disallowed, name={}",
type,
name))
return false;
name_view.remove_suffix(1);
}
// Inbetween start and preceding suffix, (alphanumeric, hyphen or underscore) characters
// permitted
if (check_condition(
!std::all_of(name_view.begin(), name_view.end(), char_is_alphanum_or<'-', '_'>),