-
Notifications
You must be signed in to change notification settings - Fork 235
/
token_database.cpp
1338 lines (1102 loc) · 39.5 KB
/
token_database.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
/**
* @file
* @copyright defined in evt/LICENSE.txt
*/
#include <evt/chain/token_database.hpp>
#ifndef __cpp_lib_string_view
#define __cpp_lib_string_view
#endif
#include <deque>
#include <fstream>
#include <string_view>
#include <unordered_set>
#include <rocksdb/db.h>
#include <rocksdb/cache.h>
#include <rocksdb/options.h>
#include <rocksdb/filter_policy.h>
#include <rocksdb/slice_transform.h>
#include <rocksdb/statistics.h>
#include <rocksdb/table.h>
#include <fc/filesystem.hpp>
#include <fc/io/datastream.hpp>
#include <fc/io/raw.hpp>
#include <fc/crypto/city.hpp>
#include <evt/chain/config.hpp>
#include <evt/chain/exceptions.hpp>
#include <evt/chain/dense_hash.hpp>
namespace evt { namespace chain {
namespace __internal {
// Use only lower 48-bit address for some pointers.
/*
This optimization uses the fact that current X86-64 architecture only implement lower 48-bit virtual address.
The higher 16-bit can be used for storing other data.
*/
#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
#define SETPOINTER(type, p, x) (p = reinterpret_cast<type *>((reinterpret_cast<uintptr_t>(p) & static_cast<uintptr_t>(0xFFFF000000000000UL)) | reinterpret_cast<uintptr_t>(reinterpret_cast<const void*>(x))))
#define GETPOINTER(type, p) (reinterpret_cast<type *>(reinterpret_cast<uintptr_t>(p) & static_cast<uintptr_t>(0x0000FFFFFFFFFFFFUL)))
#else
#error EVT can only be compiled in X86-64 architecture
#endif
const char* kAssetsColumnFamilyName = "Assets";
const size_t kSymbolIdSize = sizeof(symbol_id_type);
const size_t kPublicKeySize = sizeof(fc::ecc::public_key_shim);
struct db_token_key : boost::noncopyable {
public:
db_token_key(const name128& prefix, const name128& key)
: prefix(prefix)
, key(key)
, slice((const char*)this, sizeof(name128) * 2) {}
const rocksdb::Slice&
as_slice() const {
return slice;
}
std::string
as_string() const {
return std::string((const char*)this, 16 + 16);
}
private:
name128 prefix;
name128 key;
rocksdb::Slice slice;
};
struct db_asset_key : boost::noncopyable {
public:
db_asset_key(const address& addr, symbol_id_type sym_id)
: slice((const char*)this, sizeof(buf)) {
memcpy(buf, &sym_id, kSymbolIdSize);
addr.to_bytes(buf + kSymbolIdSize, kPublicKeySize);
}
const rocksdb::Slice&
as_slice() const {
return slice;
}
std::string
as_string() const {
return std::string((const char*)this, sizeof(buf));
}
private:
char buf[kSymbolIdSize + kPublicKeySize];
rocksdb::Slice slice;
};
name128 action_key_prefixes[] = {
N128(.asset),
N128(.domain),
N128(.token),
N128(.group),
N128(.suspend),
N128(.lock),
N128(.fungible),
N128(.prodvote),
N128(.evtlink),
N128(.bonus),
N128(.bonus-slim),
N128(.bonus-psvdist)
};
static_assert(sizeof(action_key_prefixes) / sizeof(name128) == (int)token_type::max_value + 1);
struct key_hasher {
size_t
operator()(const std::string& key) const {
return fc::city_hash_size_t(key.data(), key.size());
}
};
using keys_hash_set = google::dense_hash_set<std::string, key_hasher, std::equal_to<std::string>, std::allocator<std::string>>;
struct flag {
public:
flag(uint8_t type, uint8_t exts) : type(type), exts(exts) {}
public:
char payload[6];
uint8_t type;
uint8_t exts;
};
enum action_type {
kRuntime = 0,
kPersist
};
enum data_type {
kTokenKey = 0,
kTokenFullKey,
kAssetKey,
kTokenKeys
};
// realtime action
// stored in memory
struct rt_action {
public:
rt_action(uint8_t token_type, uint8_t op, uint8_t data_type, void* data) {
assert(data_type < 8 && op < 8);
f.type = token_type;
f.exts = op;
f.exts |= (data_type << 4);
SETPOINTER(void, this->data, data);
}
token_type get_token_type() const { return (token_type)f.type; }
action_op get_action_op() const { return (action_op)(f.exts & 0xF); }
data_type get_data_type() const { return (data_type)(f.exts >> 4); }
public:
union {
flag f;
void* data;
};
};
struct rt_group {
const void* rb_snapshot;
small_vector<rt_action, 4> actions;
};
// persistent action
// stored in disk
struct pd_action {
uint16_t op;
uint16_t type;
std::string key;
std::string value;
};
struct pd_group {
int64_t seq; // used for persistent
std::vector<pd_action> actions;
};
struct sp_node {
public:
sp_node(uint8_t type) : f(type, 0) {}
public:
union {
flag f;
void* group;
};
};
struct savepoint {
public:
savepoint(int64_t seq, uint8_t type)
: seq(seq), node(type) {}
public:
int64_t seq;
sp_node node;
};
struct rt_token_key {
name128 key;
};
struct rt_token_fullkey {
name128 prefix;
name128 key;
};
struct rt_token_keys {
name128 prefix;
token_keys_t keys;
};
struct rt_asset_key {
char key[kSymbolIdSize + kPublicKeySize];
};
struct pd_header {
int dirty_flag;
};
} // namespace __internal
class token_database_impl {
public:
token_database_impl(token_database& self, const token_database::config& config);
public:
void open(int load_persistence = true);
void close(int persist = true);
public:
void put_token(token_type type, action_op op, const name128& prefix, const name128& key, const std::string_view& data);
void put_tokens(token_type type,
action_op op,
const name128& prefix,
token_keys_t&& keys,
const small_vector_base<std::string_view>& data);
void put_asset(const address& addr, const symbol_id_type sym_id, const std::string_view& data);
int exists_token(const name128& prefix, const name128& key) const;
int exists_asset(const address& addr, const symbol_id_type sym_id) const;
int read_token(const name128& prefix, const name128& key, std::string& out, bool no_throw = false) const;
int read_asset(const address& addr, const symbol_id_type sym_id, std::string& out, bool no_throw = false) const;
int read_tokens_range(const name128& prefix, int skip, const read_value_func& func) const;
int read_assets_range(const symbol_id_type sym_id, int skip, const read_value_func& func) const;
public:
void add_savepoint(int64_t seq);
void rollback_to_latest_savepoint();
void pop_savepoints(int64_t until);
void pop_back_savepoint();
void squash();
int64_t latest_savepoint_seq() const;
int64_t new_savepoint_session_seq() const;
size_t savepoints_size() const { return savepoints_.size(); }
void rollback_rt_group(__internal::rt_group*);
void rollback_pd_group(__internal::pd_group*);
int should_record() { return !savepoints_.empty(); }
void record(uint8_t action_type, uint8_t op, uint8_t data_type, void* data);
void free_savepoint(__internal::savepoint&);
void free_all_savepoints();
void persist_savepoints() const;
void load_savepoints();
void persist_savepoints(std::ostream&) const;
void load_savepoints(std::istream&);
void flush() const;
std::string get_db_path() const { return config_.db_path.to_native_ansi_path(); }
public:
token_database& self_;
token_database::config config_;
rocksdb::DB* db_;
rocksdb::ReadOptions read_opts_;
rocksdb::WriteOptions write_opts_;
rocksdb::ColumnFamilyHandle* tokens_handle_;
rocksdb::ColumnFamilyHandle* assets_handle_;
std::deque<__internal::savepoint> savepoints_;
};
token_database_impl::token_database_impl(token_database& self, const token_database::config& config)
: self_(self)
, config_(config)
, db_(nullptr)
, read_opts_()
, write_opts_()
, tokens_handle_(nullptr)
, assets_handle_(nullptr)
, savepoints_() {}
void
token_database_impl::open(int load_persistence) {
using namespace rocksdb;
using namespace __internal;
EVT_ASSERT(db_ == nullptr, token_database_exception, "Token database is already opened");
auto options = Options();
options.OptimizeUniversalStyleCompaction();
options.create_if_missing = true;
options.compression = CompressionType::kLZ4Compression;
options.bottommost_compression = CompressionType::kZSTD;
options.allow_concurrent_memtable_write = false;
options.prefix_extractor.reset(NewFixedPrefixTransform(sizeof(name128)));
options.memtable_factory.reset(NewHashSkipListRepFactory());
if(config_.enable_stats) {
options.statistics = rocksdb::CreateDBStatistics();
options.statistics->stats_level_ = StatsLevel::kExceptTimeForMutex;
}
auto assets_options = ColumnFamilyOptions(options);
if(config_.profile == storage_profile::disk) {
auto table_opts = BlockBasedTableOptions();
table_opts.index_type = BlockBasedTableOptions::kHashSearch;
table_opts.checksum = kxxHash64;
table_opts.format_version = 4;
table_opts.block_cache = NewLRUCache(config_.block_cache_size);
table_opts.filter_policy.reset(NewBloomFilterPolicy(10, false));
options.table_factory.reset(NewBlockBasedTableFactory(table_opts));
assets_options.prefix_extractor.reset(NewFixedPrefixTransform(kSymbolIdSize));
}
else if(config_.profile == storage_profile::memory) {
auto tokens_table_options = PlainTableOptions();
auto assets_table_options = PlainTableOptions();
tokens_table_options.user_key_len = sizeof(name128) + sizeof(name128);
assets_table_options.user_key_len = kPublicKeySize + kSymbolIdSize;
options.table_factory.reset(NewPlainTableFactory(tokens_table_options));
assets_options.table_factory.reset(NewPlainTableFactory(assets_table_options));
assets_options.prefix_extractor.reset(NewFixedPrefixTransform(kSymbolIdSize));
}
else {
EVT_THROW(token_database_exception, "Unknown token database profile");
}
read_opts_.total_order_seek = false;
read_opts_.prefix_same_as_start = true;
read_opts_.tailing = true;
if(!fc::exists(config_.db_path)) {
auto t = config_.db_path.to_native_ansi_path();
// create new database and open
fc::create_directories(config_.db_path);
auto status = DB::Open(options, config_.db_path.to_native_ansi_path(), &db_);
if(!status.ok()) {
EVT_THROW(token_database_rocksdb_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
status = db_->CreateColumnFamily(assets_options, kAssetsColumnFamilyName, &assets_handle_);
if(!status.ok()) {
EVT_THROW(token_database_rocksdb_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
if(load_persistence) {
load_savepoints();
}
return;
}
auto columns = std::vector<ColumnFamilyDescriptor>();
columns.emplace_back(kDefaultColumnFamilyName, options);
columns.emplace_back(kAssetsColumnFamilyName, assets_options);
auto handles = std::vector<ColumnFamilyHandle*>();
auto status = DB::Open(options, config_.db_path.to_native_ansi_path(), columns, &handles, &db_);
if(!status.ok()) {
EVT_THROW(token_database_rocksdb_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
assert(handles.size() == 2);
tokens_handle_ = handles[0];
assets_handle_ = handles[1];
if(load_persistence) {
load_savepoints();
}
}
void
token_database_impl::close(int persist) {
if(db_ != nullptr) {
if(persist) {
persist_savepoints();
}
if(!savepoints_.empty()) {
free_all_savepoints();
}
if(tokens_handle_ != nullptr) {
delete tokens_handle_;
tokens_handle_ = nullptr;
}
if(assets_handle_ != nullptr) {
delete assets_handle_;
assets_handle_ = nullptr;
}
delete db_;
db_ = nullptr;
}
}
void
token_database_impl::put_token(token_type type, action_op op, const name128& prefix, const name128& key, const std::string_view& data) {
using namespace __internal;
auto dbkey = db_token_key(prefix, key);
auto status = db_->Put(write_opts_, dbkey.as_slice(), data);
if(!status.ok()) {
FC_THROW_EXCEPTION(fc::unrecoverable_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
if(should_record()) {
void* data;
// for `token` action, needs to record both prefix and key, prefix refers to the domain
// for `non-token` action, prefix is not necessary which can be inferred by the `type`
if(type != token_type::token) {
assert(prefix == action_key_prefixes[(int)type]);
auto data = (rt_token_key*)malloc(sizeof(rt_token_key));
data->key = key;
record((int)type, (int)op, (int)kTokenKey, data);
}
else {
auto data = (rt_token_fullkey*)malloc(sizeof(rt_token_fullkey));
data->prefix = prefix;
data->key = key;
record((int)type, (int)op, (int)kTokenFullKey, data);
}
}
}
void
token_database_impl::put_tokens(token_type type,
action_op op,
const name128& prefix,
token_keys_t&& keys,
const small_vector_base<std::string_view>& data){
using namespace __internal;
assert(keys.size() == data.size());
for(auto i = 0u; i < keys.size(); i++) {
auto dbkey = db_token_key(prefix, keys[i]);
auto status = db_->Put(write_opts_, dbkey.as_slice(), data[i]);
if(!status.ok()) {
FC_THROW_EXCEPTION(fc::unrecoverable_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
}
if(should_record()) {
auto data = (rt_token_keys*)malloc(sizeof(rt_token_keys));
data->prefix = prefix;
new(&data->keys) token_keys_t(std::move(keys));
record((int)type, (int)op, (int)kTokenKeys, data);
}
}
void
token_database_impl::put_asset(const address& addr, const symbol_id_type sym_id, const std::string_view& data) {
using namespace __internal;
auto dbkey = db_asset_key(addr, sym_id);
auto& slice = dbkey.as_slice();
auto status = db_->Put(write_opts_, assets_handle_, slice, data);
if(!status.ok()) {
FC_THROW_EXCEPTION(fc::unrecoverable_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
if(should_record()) {
auto act = (rt_asset_key*)malloc(sizeof(rt_asset_key));
memcpy(act->key, slice.data(), slice.size());
record((int)token_type::asset, (int)action_op::put, (int)kAssetKey, act);
}
}
int
token_database_impl::exists_token(const name128& prefix, const name128& key) const {
using namespace __internal;
auto dbkey = db_token_key(prefix, key);
auto value = std::string();
auto status = db_->Get(read_opts_, dbkey.as_slice(), &value);
return status.ok();
}
int
token_database_impl::exists_asset(const address& addr, const symbol_id_type sym_id) const {
using namespace __internal;
auto dbkey = db_asset_key(addr, sym_id);
auto value = std::string();
auto status = db_->Get(read_opts_, assets_handle_, dbkey.as_slice(), &value);
return status.ok();
}
int
token_database_impl::read_token(const name128& prefix, const name128& key, std::string& out, bool no_throw) const {
using namespace __internal;
auto dbkey = db_token_key(prefix, key);
auto status = db_->Get(read_opts_, dbkey.as_slice(), &out);
if(!status.ok()) {
if(!status.IsNotFound()) {
FC_THROW_EXCEPTION(fc::unrecoverable_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
if(!no_throw) {
EVT_THROW(unknown_token_database_key, "Cannot find key: ${k} with prefix: ${p}", ("k",key)("p",prefix));
}
return false;
}
return true;
}
int
token_database_impl::read_asset(const address& addr, const symbol_id_type sym_id, std::string& out, bool no_throw) const {
using namespace __internal;
auto key = db_asset_key(addr, sym_id);
auto value = std::string();
auto status = db_->Get(read_opts_, assets_handle_, key.as_slice(), &out);
if(!status.ok()) {
if(!status.IsNotFound()) {
FC_THROW_EXCEPTION(fc::unrecoverable_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
if(!no_throw) {
EVT_THROW2(unknown_token_database_key, "There's no balance of fungible with sym id: {} in address: {}", sym_id, addr);
}
return false;
}
return true;
}
int
token_database_impl::read_tokens_range(const name128& prefix, int skip, const read_value_func& func) const {
using namespace __internal;
auto it = db_->NewIterator(read_opts_);
auto key = rocksdb::Slice((char*)&prefix, sizeof(prefix));
auto i = 0;
auto count = 0;
it->Seek(key);
while(it->Valid()) {
if(i++ < skip) {
it->Next();
continue;
}
count++;
auto value = it->value().ToString();
auto key = it->key();
key.remove_prefix(sizeof(prefix));
if(!func(key.ToStringView(), std::move(value))) {
delete it;
return count;
}
it->Next();
}
delete it;
return count;
}
int
token_database_impl::read_assets_range(const symbol_id_type sym_id, int skip, const read_value_func& func) const {
using namespace __internal;
auto it = db_->NewIterator(read_opts_, assets_handle_);
auto key = rocksdb::Slice((char*)&sym_id, sizeof(sym_id));
auto count = 0;
auto i = 0;
it->Seek(key);
while(it->Valid()) {
if(i++ < skip) {
it->Next();
continue;
}
count++;
auto value = it->value().ToString();
auto key = it->key();
key.remove_prefix(sizeof(sym_id));
if(!func(key.ToStringView(), std::move(value))) {
delete it;
return count;
}
it->Next();
}
delete it;
return count;
}
void
token_database_impl::add_savepoint(int64_t seq) {
using namespace __internal;
if(!savepoints_.empty()) {
auto& b = savepoints_.back();
if(b.seq >= seq) {
EVT_THROW(token_database_seq_not_valid, "Seq is not valid, prev: ${prev}, curr: ${curr}",
("prev", b.seq)("curr", seq));
}
}
savepoints_.emplace_back(savepoint(seq, kRuntime));
auto rt = new rt_group { .rb_snapshot = (const void*)db_->GetSnapshot(), .actions = {} };
SETPOINTER(void, savepoints_.back().node.group, rt);
}
void
token_database_impl::free_savepoint(__internal::savepoint& sp) {
using namespace __internal;
auto n = sp.node;
switch(n.f.type) {
case kRuntime: {
auto rt = GETPOINTER(rt_group, n.group);
for(auto& act : rt->actions) {
switch(act.get_data_type()) {
case kTokenKey:
case kTokenFullKey:
case kAssetKey: {
free(GETPOINTER(void, act.data));
break;
}
case kTokenKeys: {
auto p = GETPOINTER(rt_token_keys, act.data);
//need to call dtor of keys manually
p->keys.~token_keys_t();
free(p);
break;
}
} // switch
}
db_->ReleaseSnapshot((const rocksdb::Snapshot*)rt->rb_snapshot);
delete rt;
break;
}
case kPersist: {
auto pd = GETPOINTER(pd_group, n.group);
delete pd;
break;
}
} // switch
}
void
token_database_impl::free_all_savepoints() {
for(auto& sp : savepoints_) {
free_savepoint(sp);
}
savepoints_.clear();
}
void
token_database_impl::pop_savepoints(int64_t until) {
while(!savepoints_.empty() && savepoints_.front().seq < until) {
auto it = std::move(savepoints_.front());
savepoints_.pop_front();
free_savepoint(it);
}
}
void
token_database_impl::pop_back_savepoint() {
EVT_ASSERT(!savepoints_.empty(), token_database_no_savepoint, "There's no savepoints anymore");
auto it = std::move(savepoints_.back());
savepoints_.pop_back();
free_savepoint(it);
}
void
token_database_impl::squash() {
using namespace __internal;
EVT_ASSERT(savepoints_.size() >= 2, token_database_squash_exception, "Squash needs at least two savepoints.");
auto n = savepoints_.back().node;
EVT_ASSERT(n.f.type == kRuntime, token_database_squash_exception, "Squash needs two realtime savepoints.");
savepoints_.pop_back();
auto n2 = savepoints_.back().node;
EVT_ASSERT(n2.f.type == kRuntime, token_database_squash_exception, "Squash needs two realtime savepoints.");
auto rt1 = GETPOINTER(rt_group, n.group);
auto rt2 = GETPOINTER(rt_group, n2.group);
// add all actions from rt1 into end of rt2
rt2->actions.insert(rt2->actions.cend(), rt1->actions.cbegin(), rt1->actions.cend());
// just release rt1's snapshot
db_->ReleaseSnapshot((const rocksdb::Snapshot*)rt1->rb_snapshot);
delete rt1;
}
int64_t
token_database_impl::latest_savepoint_seq() const {
EVT_ASSERT(!savepoints_.empty(), token_database_no_savepoint, "There's no savepoints anymore");
return savepoints_.back().seq;
}
int64_t
token_database_impl::new_savepoint_session_seq() const {
int64_t seq = 1;
if(!savepoints_.empty()) {
seq = savepoints_.back().seq + 1;
}
return seq;
}
void
token_database_impl::record(uint8_t action_type, uint8_t op, uint8_t data_type, void* data) {
using namespace __internal;
if(!should_record()) {
return;
}
auto n = savepoints_.back().node;
assert(n.f.type == kRuntime);
GETPOINTER(rt_group, n.group)->actions.emplace_back(rt_action(action_type, op, data_type, data));
}
namespace __internal {
std::string
get_sp_key(const rt_action& act) {
switch(act.get_data_type()) {
case kTokenKey: {
auto data = GETPOINTER(rt_token_key, act.data);
return db_token_key(action_key_prefixes[act.f.type], data->key).as_string();
}
case kTokenFullKey: {
auto data = GETPOINTER(rt_token_fullkey, act.data);
return db_token_key(data->prefix, data->key).as_string();
}
case kAssetKey: {
auto data = GETPOINTER(rt_asset_key, act.data);
return std::string(data->key, sizeof(data->key));
}
case kTokenKeys: {
assert(false);
}
} // switch
return std::string();
}
} // namespace __internal
void
token_database_impl::rollback_rt_group(__internal::rt_group* rt) {
using namespace __internal;
if(rt->actions.empty()) {
db_->ReleaseSnapshot((const rocksdb::Snapshot*)rt->rb_snapshot);
return;
}
auto snapshot_read_opts_ = read_opts_;
snapshot_read_opts_.snapshot = (const rocksdb::Snapshot*)rt->rb_snapshot;
auto key_set = keys_hash_set();
auto batch = rocksdb::WriteBatch();
key_set.set_empty_key(std::string());
for(auto it = rt->actions.begin(); it < rt->actions.end(); it++) {
auto data = GETPOINTER(void, it->data);
auto fn = [&](auto& key, auto type, auto op) {
switch(op) {
case action_op::add: {
assert(key_set.find(key) == key_set.cend());
batch.Delete(key);
self_.remove_token_value(key);
// insert key into key set
key_set.emplace(std::move(key));
break;
}
case action_op::update: {
// only update operation need to check if key is already processed
if(key_set.find(key) != key_set.cend()) {
break;
}
auto old_value = std::string();
auto status = db_->Get(snapshot_read_opts_, key, &old_value);
if(!status.ok()) {
FC_THROW_EXCEPTION(fc::unrecoverable_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
batch.Put(key, old_value);
self_.rollback_token_value(key);
// insert key into key set
key_set.emplace(std::move(key));
break;
}
case action_op::put: {
// only update operation need to check if key is already processed
if(key_set.find(key) != key_set.cend()) {
break;
}
// Asset type only has put op
auto handle = (type == token_type::asset) ? assets_handle_ : tokens_handle_;
auto old_value = std::string();
auto status = db_->Get(snapshot_read_opts_, handle, key, &old_value);
// key may not existed in latest snapshot, remove it
if(!status.ok()) {
if(status.code() != rocksdb::Status::kNotFound) {
FC_THROW_EXCEPTION(fc::unrecoverable_exception, "Rocksdb internal error: ${err}", ("err", status.getState()));
}
batch.Delete(handle, key);
if(handle == tokens_handle_) {
self_.remove_token_value(key);
}
}
else {
batch.Put(handle, key, old_value);
if(handle == tokens_handle_) {
self_.rollback_token_value(key);
}
}
// insert key into key set
key_set.emplace(std::move(key));
break;
}
} // switch
};
auto op = it->get_action_op();
auto data_type = it->get_data_type();
auto type = it->get_token_type();
switch(data_type) {
case kTokenKey:
case kTokenFullKey:
case kAssetKey: {
auto key = get_sp_key(*it);
fn(key, type, op);
break;
}
case kTokenKeys: {
auto keys = (rt_token_keys*)data;
auto& prefix = keys->prefix;
for(auto& k : keys->keys) {
auto key = db_token_key(prefix, k).as_string();
fn(key, type, op);
}
//need to call dtor of keys manually
keys->keys.~token_keys_t();
break;
}
} // switch
free(data);
} // for
auto sync_write_opts = write_opts_;
sync_write_opts.sync = true;
db_->Write(sync_write_opts, &batch);
db_->ReleaseSnapshot((const rocksdb::Snapshot*)rt->rb_snapshot);
}
void
token_database_impl::rollback_pd_group(__internal::pd_group* pd) {
using namespace __internal;
if(pd->actions.empty()) {
return;
}
// keyset is not required here,
// because it has done during creating persist savepoint
// cache rollback is also no need here
// because cache cannot have persist value objects
auto batch = rocksdb::WriteBatch();
for(auto it = pd->actions.begin(); it < pd->actions.end(); it++) {
switch((action_op)it->op) {
case action_op::add: {
assert(it->value.empty());
batch.Delete(it->key);
break;
}
case action_op::update: {
assert(!it->value.empty());
batch.Put(it->key, it->value);
break;
}
case action_op::put: {
// Asset type only has put op
auto handle = (it->type == (int)token_type::asset) ? assets_handle_ : tokens_handle_;
if(it->value.empty()) {
batch.Delete(handle, it->key);
}
else {
batch.Put(handle, it->key, it->value);
}
break;
}
} // switch
}
auto sync_write_opts = write_opts_;
sync_write_opts.sync = true;
db_->Write(sync_write_opts, &batch);
}
void
token_database_impl::rollback_to_latest_savepoint() {
using namespace __internal;
EVT_ASSERT(!savepoints_.empty(), token_database_no_savepoint, "There's no savepoints anymore");
auto n = savepoints_.back().node;
switch(n.f.type) {
case kRuntime: {
auto rt = GETPOINTER(rt_group, n.group);
rollback_rt_group(rt);
delete rt;
break;
}
case kPersist: {
auto pd = GETPOINTER(pd_group, n.group);
rollback_pd_group(pd);
delete pd;
break;
}
} // switch
savepoints_.pop_back();
}
void
token_database_impl::persist_savepoints() const {
try {
auto filename = config_.db_path / config::token_database_persisit_filename;
if(fc::exists(filename)) {
fc::remove(filename);
}
auto fs = std::fstream();
fs.exceptions(std::fstream::failbit | std::fstream::badbit);
fs.open(filename.to_native_ansi_path(), (std::ios::out | std::ios::binary));
persist_savepoints(fs);
fs.flush();
fs.close();
}
EVT_CAPTURE_AND_RETHROW(token_database_persist_exception);
}
void
token_database_impl::load_savepoints() {
auto filename = config_.db_path / config::token_database_persisit_filename;
if(!fc::exists(filename)) {
wlog("No savepoints log in token database");
return;
}
auto fs = std::fstream();
fs.exceptions(std::fstream::failbit | std::fstream::badbit);
fs.open(filename.to_native_ansi_path(), (std::ios::in | std::ios::binary));