-
Notifications
You must be signed in to change notification settings - Fork 13
/
quadb.cpp
507 lines (384 loc) · 15.4 KB
/
quadb.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
#include <stdlib.h> // getenv
#include <unistd.h> // access, read
#include <string.h> // strerror
#include <errno.h> // strerror
#include <sys/stat.h> // mkdir
#include <sys/types.h> // mkdir
#include <iostream>
#include <string>
#include <random>
#include <docopt.h>
#include "quadrable.h"
#include "quadrable/transport.h"
#include "quadrable/debug.h"
using quadrable::quaderr;
static const char USAGE[] =
R"(
Usage:
quadb [options] init
quadb [options] put [--int] [--] <key> <val>
quadb [options] del [--int] [--] <key>
quadb [options] get [--int] [--] <key>
quadb [options] length
quadb [options] export [--sep=<sep>] [--int]
quadb [options] import [--sep=<sep>] [--int]
quadb [options] root
quadb [options] stats
quadb [options] status
quadb [options] diff <head> [--sep=<sep>]
quadb [options] patch [--sep=<sep>]
quadb [options] head
quadb [options] head rm [<head>]
quadb [options] checkout [<head>]
quadb [options] fork [<head>] [--from=<from>]
quadb [options] gc
quadb [options] exportProof [--format=(HashedKeys|FullKeys)] [--hex] [--dump] [--int] [--stdin] [--] [<keys>...]
quadb [options] importProof [--root=<root>] [--hex] [--dump]
quadb [options] mergeProof [--hex]
quadb [options] dumpTree
quadb [options] mineHash <prefix>
Options:
--db=<dir> Database directory (default $ENV{QUADB_DIR} || "./quadb-dir/")
--noTrackKeys Don't store keys in DB (default $ENV{QUADB_NOTRACKKEYS} || false)
--int Keys are in integer format
-h --help Show this screen.
--version Show version.
)";
static std::string slurpStdin() {
std::string output;
char buf[4096];
while (1) {
ssize_t res = ::read(0, buf, sizeof(buf));
if (res == 0) break;
else if (res < 0 && errno == EINTR) continue;
else if (res < 0) throw quaderr("error reading from stdin: ", strerror(errno));
output += std::string(buf, static_cast<size_t>(res));
}
return output;
}
void run(int argc, char **argv) {
std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc }, true, "quadb " QUADRABLE_VERSION);
std::string dbDir;
if (args["--db"]) {
dbDir = args["--db"].asString();
} else if (getenv("QUADB_DIR")) {
dbDir = std::string(getenv("QUADB_DIR"));
} else {
dbDir = "./quadb-dir";
}
dbDir += "/";
bool noTrackKeys = false;
if (args["--noTrackKeys"].asBool()) {
noTrackKeys = true;
} else if (getenv("QUADB_NOTRACKKEYS")) {
noTrackKeys = true;
}
if (access(dbDir.c_str(), F_OK)) {
if (args["init"].asBool()) {
if (mkdir(dbDir.c_str(), 0755)) throw quaderr("Unable to create directory '", dbDir, "': ", strerror(errno));
} else {
throw quaderr("Could not access directory '", dbDir, "': ", strerror(errno));
}
}
if (args["init"].asBool()) {
std::string dbFile = dbDir + "data.mdb";
if (access(dbFile.c_str(), F_OK)) {
std::cout << "quadb: init'ing directory: " << dbDir << std::endl;
} else {
std::cerr << "quadb: Directory '" << dbDir << "' already init'ed. Doing nothing." << std::endl;
}
}
lmdb::env lmdb_env = lmdb::env::create();
lmdb_env.set_max_dbs(64);
lmdb_env.set_mapsize(1UL * 1024UL * 1024UL * 1024UL * 1024UL);
lmdb_env.open(dbDir.c_str(), MDB_CREATE, 0664);
lmdb_env.reader_check();
quadrable::Quadrable db;
db.trackKeys = !noTrackKeys;
auto txn = lmdb::txn::begin(lmdb_env, nullptr, 0);
db.init(txn);
lmdb::dbi dbi_quadb_state = lmdb::dbi::open(txn, "quadrable_quadb_state", MDB_CREATE);
{
std::string_view v;
if (dbi_quadb_state.get(txn, "detachedHead", v)) {
db.checkout(lmdb::from_sv<uint64_t>(v));
} else if (dbi_quadb_state.get(txn, "currHead", v)) {
db.checkout(v);
} else {
db.checkout("master");
}
}
if (args["init"].asBool()) {
// Do nothing
} else if (args["dumpTree"].asBool()) {
quadrable::dumpDb(db, txn);
} else if (args["put"].asBool()) {
std::string k = args["<key>"].asString();
std::string v = args["<val>"].asString();
auto changes = db.change();
changes.put(k, v);
changes.apply(txn);
} else if (args["del"].asBool()) {
std::string k = args["<key>"].asString();
auto changes = db.change();
changes.del(k);
changes.apply(txn);
} else if (args["get"].asBool()) {
std::string k = args["<key>"].asString();
std::string_view v;
bool found = db.get(txn, k, v);
if (!found) throw quaderr("key not found in db");
std::cout << v << std::endl;
} else if (args["head"].asBool()) {
bool isDetachedHead = db.isDetachedHead();
std::string currHead;
if (!isDetachedHead) currHead = db.getHead();
if (args["rm"].asBool()) {
if (args["<head>"]) {
db.dbi_head.del(txn, args["<head>"].asString());
} else {
if (isDetachedHead) {
db.checkout();
} else {
db.dbi_head.del(txn, currHead);
}
}
} else {
struct HeadElem {
std::string head;
uint64_t nodeId;
};
std::vector<HeadElem> headElems;
std::string_view k, v;
auto cursor = lmdb::cursor::open(txn, db.dbi_head);
for (bool found = cursor.get(k, v, MDB_FIRST); found; found = cursor.get(k, v, MDB_NEXT)) {
headElems.emplace_back(HeadElem{ std::string(k), lmdb::from_sv<uint64_t>(v), });
}
std::sort(headElems.begin(), headElems.end(), [](auto &a, auto &b){
if (a.nodeId == b.nodeId) return a.head < b.head;
return a.nodeId > b.nodeId;
});
if (isDetachedHead) {
uint64_t nodeId = db.getHeadNodeId(txn);
std::cout << "D> [detached] : " << quadrable::renderNode(db, txn, nodeId) << "\n";
}
for (auto &e : headElems) {
if (!isDetachedHead && currHead == e.head) std::cout << "=> ";
else std::cout << " ";
std::cout << e.head << " : " << quadrable::renderNode(db, txn, e.nodeId) << "\n";
}
std::cout << std::flush;
}
} else if (args["export"].asBool()) {
std::string sep = ",";
if (args["--sep"]) sep = args["--sep"].asString();
db.walkTree(txn, [&](quadrable::Quadrable::ParsedNode &node, uint64_t depth){
if (!node.isLeaf()) return true;
std::string_view leafKey;
if (db.getLeafKey(txn, node.nodeId, leafKey)) {
std::cout << leafKey;
} else if (args["--int"].asBool()) {
std::cout << node.key().toInteger();
} else {
std::cout << quadrable::renderUnknown(node.leafKeyHash());
}
std::cout << sep;
if (node.nodeType == quadrable::NodeType::Leaf) std::cout << node.leafVal();
else std::cout << quadrable::renderUnknown(node.leafValHash());
std::cout << "\n";
return true;
});
std::cout << std::flush;
} else if (args["import"].asBool()) {
std::string sep = ",";
if (args["--sep"]) sep = args["--sep"].asString();
auto changes = db.change();
std::string line;
while (std::getline(std::cin, line)) {
size_t delimOffset = line.find(sep);
if (delimOffset == std::string::npos) throw quaderr("couldn't find separator in input line");
auto k = line.substr(0, delimOffset);
auto v = line.substr(delimOffset + sep.size());
if (args["--int"].asBool()) changes.put(quadrable::Key::fromInteger(std::stoi(k)), v);
else changes.put(k, v);
}
changes.apply(txn);
} else if (args["checkout"].asBool()) {
if (args["<head>"]) {
std::string newHead = args["<head>"].asString();
db.checkout(newHead);
dbi_quadb_state.put(txn, "currHead", newHead);
dbi_quadb_state.del(txn, "detachedHead");
} else {
db.checkout();
dbi_quadb_state.del(txn, "currHead");
}
} else if (args["fork"].asBool()) {
if (args["--from"]) db.checkout(args["--from"].asString());
if (args["<head>"]) {
std::string newHead = args["<head>"].asString();
db.fork(txn, newHead);
dbi_quadb_state.put(txn, "currHead", newHead);
dbi_quadb_state.del(txn, "detachedHead");
} else {
db.fork(txn);
dbi_quadb_state.del(txn, "currHead");
}
} else if (args["root"].asBool()) {
std::cout << to_hex(db.root(txn), true) << std::endl;
} else if (args["stats"].asBool()) {
quadrable::dumpStats(db, txn);
} else if (args["status"].asBool()) {
if (db.isDetachedHead()) {
std::cout << "Detached head" << std::endl;
} else {
std::cout << "Head: " << db.getHead() << std::endl;
}
uint64_t nodeId = db.getHeadNodeId(txn);
std::cout << "Root: " << quadrable::renderNode(db, txn, nodeId) << std::endl;
} else if (args["diff"].asBool()) {
std::string sep = ",";
if (args["--sep"]) sep = args["--sep"].asString();
uint64_t currNodeId = db.getHeadNodeId(txn);
uint64_t otherNodeId = db.getHeadNodeId(txn, args["<head>"].asString());
auto deltas = db.diff(txn, otherNodeId, currNodeId);
for (auto &delta : deltas) {
if (delta.deletion) std::cout << "-";
else std::cout << "+";
std::cout << (delta.key.size() ? delta.key : quadrable::renderUnknown(delta.keyHash));
std::cout << sep;
std::cout << delta.val << "\n";
}
std::cout << std::flush;
} else if (args["patch"].asBool()) {
std::string sep = ",";
if (args["--sep"]) sep = args["--sep"].asString();
auto changes = db.change();
std::string origLine;
while (std::getline(std::cin, origLine)) {
if (origLine.size() < 1) throw quaderr("empty line in patch");
if (origLine[0] == '#') continue;
std::string_view line(origLine.data() + 1, origLine.size() - 1);
size_t delimOffset = line.find(sep);
if (delimOffset == std::string::npos) throw quaderr("couldn't find separator in input line");
auto k = line.substr(0, delimOffset);
auto v = line.substr(delimOffset + sep.size());
if (origLine[0] == '+') changes.put(k, v);
else if (origLine[0] == '-') changes.del(k);
else throw quaderr("unexpected line in patch");
}
changes.apply(txn);
} else if (args["gc"].asBool()) {
quadrable::Quadrable::GarbageCollector gc(db);
gc.markAllHeads(txn);
if (db.isDetachedHead()) gc.markTree(txn, db.getHeadNodeId(txn));
auto stats = gc.sweep(txn);
std::cout << "Collected " << stats.garbage << "/" << stats.total << " nodes" << std::endl;
gc.deleteNodes(txn);
} else if (args["exportProof"].asBool()) {
quadrable::Proof proof;
std::vector<std::string> keysOrig;
if (args["--stdin"].asBool()) {
std::string line;
while (std::getline(std::cin, line)) {
keysOrig.push_back(line);
}
} else {
for (auto &key : args["<keys>"].asStringList()) {
keysOrig.push_back(key);
}
}
if (args["--int"].asBool()) {
std::vector<quadrable::Key> keys;
for (auto &key : keysOrig) {
keys.push_back(quadrable::Key::fromInteger(std::stoi(key)));
}
proof = db.exportProofRaw(txn, keys);
} else {
std::vector<std::string> keys;
for (auto &key : keysOrig) {
keys.push_back(key);
}
proof = db.exportProof(txn, keys);
}
std::string format = "HashedKeys";
if (args["--format"]) format = args["--format"].asString();
if (args["--dump"].asBool()) {
quadrable::dumpProof(proof);
} else {
std::string encoded;
if (format == "HashedKeys") {
encoded = quadrable::transport::encodeProof(proof, quadrable::transport::EncodingType::HashedKeys);
} else if (format == "FullKeys") {
encoded = quadrable::transport::encodeProof(proof, quadrable::transport::EncodingType::FullKeys);
} else {
throw quaderr("unknown proof format");
}
if (args["--hex"].asBool()) {
std::cout << to_hex(encoded, true) << std::endl;
} else {
std::cout << encoded;
}
}
} else if (args["importProof"].asBool()) {
std::string input = slurpStdin();
if (args["--hex"].asBool()) {
input.erase(std::remove_if(input.begin(), input.end(), ::isspace), input.end());
input = from_hex(input);
}
auto proof = quadrable::transport::decodeProof(input);
if (args["--dump"].asBool()) {
quadrable::dumpProof(proof);
} else {
if (args["--root"]) {
std::string origRoot = from_hex(args["--root"].asString());
db.importProof(txn, proof, origRoot);
} else {
auto node = db.importProof(txn, proof);
std::cout << "Imported UNAUTHENTICATED proof. Root: " << to_hex(node.nodeHash.sv(), true) << std::endl;
}
}
} else if (args["mergeProof"].asBool()) {
std::string input = slurpStdin();
if (args["--hex"].asBool()) {
input.erase(std::remove_if(input.begin(), input.end(), ::isspace), input.end());
input = from_hex(input);
}
auto proof = quadrable::transport::decodeProof(input);
db.mergeProof(txn, proof);
} else if (args["mineHash"].asBool()) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<uint64_t> distrib(1, 1000000000000);
std::string prefix = args["<prefix>"].asString();
uint64_t r;
while(1) {
r = distrib(gen);
auto h = quadrable::Key::hash(std::to_string(r));
size_t matched = 0;
for (size_t i = 0; i < prefix.size(); i++) {
bool bit = h.getBit(i);
if (!bit && prefix[i] == '0') matched++;
else if (bit && prefix[i] == '1') matched++;
else break;
}
if (matched == prefix.size()) {
std::cout << std::to_string(r) << " -> " << to_hex(h.sv()) << std::endl;
break;
}
}
}
if (db.isDetachedHead()) {
dbi_quadb_state.put(txn, "detachedHead", lmdb::to_sv<uint64_t>(db.getHeadNodeId(txn)));
}
txn.commit();
}
int main(int argc, char **argv) {
try {
run(argc, argv);
} catch (std::exception &e) {
std::cerr << "quadb error: " << e.what() << std::endl;
::exit(1);
}
return 0;
}