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
|
#include "../include/odhtdb/Database.hpp"
#include "../include/odhtdb/Group.hpp"
#include "../include/odhtdb/Encryption.hpp"
#include "../include/odhtdb/DhtKey.hpp"
#include "../include/odhtdb/bin2hex.hpp"
#include "../include/odhtdb/Log.hpp"
#include <boost/uuid/uuid_generators.hpp>
#include <opendht.h>
#include <sodium/randombytes.h>
#include <thread>
#include <chrono>
#include <sibs/SafeSerializer.hpp>
#include <sibs/SafeDeserializer.hpp>
#include <cassert>
#include <sys/time.h>
using namespace dht;
using namespace std;
using namespace chrono_literals;
static int databaseCount = 0;
// TODO: Verify time_t is always signed
static time_t timeOffset = 0; // Updated by comparing local time with ntp server
static odhtdb::u64 timeOffsetFraction = 0;
static thread *ntpThread = nullptr;
static bool timestampSynced = false;
const int OPENDHT_INFOHASH_LEN = 20;
namespace odhtdb
{
static boost::uuids::random_generator uuidGen;
const u16 DATABASE_CREATE_PACKET_STRUCTURE_VERSION = 1;
const u16 DATABASE_ADD_PACKET_STRUCTURE_VERSION = 1;
const u16 DATABASE_REQUEST_OLD_DATA_STRUCTURE_VERSION = 1;
const int NODE_PUT_RETRY_TIMES = 3;
static void nodePutWithRetry(dht::DhtRunner *node, const dht::InfoHash &infoHash, shared_ptr<dht::Value> value, int retryCounter = 0)
{
node->put(infoHash, value, [node, infoHash, value, retryCounter](bool ok)
{
if(!ok)
{
if(retryCounter < NODE_PUT_RETRY_TIMES)
{
Log::warn("Failed to execute node.put, retrying (%d/%d)", 1 + retryCounter, NODE_PUT_RETRY_TIMES);
nodePutWithRetry(node, infoHash, value, retryCounter + 1);
}
else
Log::error("Failed to execute node.put with %d retries, stopping...", NODE_PUT_RETRY_TIMES);
}
});
}
class RequestQuarantineException : public runtime_error
{
public:
RequestQuarantineException() : runtime_error("Request quarantine, will be processed later (can be real of fake request)") {}
};
OwnedByteArray combine(sibs::SafeSerializer &headerSerializer, const Encryption &encryptedData)
{
usize allocationSize = headerSerializer.getBuffer().size() + encryptedData.getNonce().size + encryptedData.getCipherText().size;
u8 *result = new u8[allocationSize];
memcpy(result, headerSerializer.getBuffer().data(), headerSerializer.getBuffer().size());
memcpy(result + headerSerializer.getBuffer().size(), encryptedData.getNonce().data, encryptedData.getNonce().size);
memcpy(result + headerSerializer.getBuffer().size() + encryptedData.getNonce().size, encryptedData.getCipherText().data, encryptedData.getCipherText().size);
return OwnedByteArray(result, allocationSize);
}
OwnedByteArray combine(const Signature::PublicKey &publicKey, const string &signedEncryptedData)
{
usize allocationSize = publicKey.getSize() + signedEncryptedData.size();
u8 *result = new u8[allocationSize];
memcpy(result, publicKey.getData(), publicKey.getSize());
memcpy(result + publicKey.getSize(), signedEncryptedData.data(), signedEncryptedData.size());
return OwnedByteArray(result, allocationSize);
}
DatabaseCreateResponse::DatabaseCreateResponse(std::shared_ptr<Signature::KeyPair> _nodeAdminKeyPair, std::shared_ptr<OwnedByteArray> _nodeAdminGroupId, shared_ptr<OwnedByteArray> _key, shared_ptr<Hash> _hash) :
nodeAdminKeyPair(_nodeAdminKeyPair),
nodeAdminGroupId(_nodeAdminGroupId),
key(_key),
hash(_hash)
{
}
const shared_ptr<Signature::KeyPair> DatabaseCreateResponse::getNodeAdminKeyPair() const
{
return nodeAdminKeyPair;
}
const shared_ptr<OwnedByteArray> DatabaseCreateResponse::getNodeAdminGroupId() const
{
return nodeAdminGroupId;
}
const shared_ptr<OwnedByteArray> DatabaseCreateResponse::getNodeEncryptionKey() const
{
return key;
}
const shared_ptr<Hash> DatabaseCreateResponse::getRequestHash() const
{
return hash;
}
Database::Database(const char *bootstrapNodeAddr, u16 port, const boost::filesystem::path &storageDir, DatabaseCallbackFuncs callbackFuncs) :
databaseStorage(this, storageDir),
onCreateNodeCallbackFunc(callbackFuncs.createNodeCallbackFunc),
onAddNodeCallbackFunc(callbackFuncs.addNodeCallbackFunc),
onAddUserCallbackFunc(callbackFuncs.addUserCallbackFunc),
shuttingDown(false)
{
node.run(port , {
/*.dht_config = */{
/*.node_config = */{
/*.node_id = */{},
/*.network = */0,
/*.is_bootstrap = */false,
/*.maintain_storage*/false
},
/*.id = */databaseStorage.getIdentity()
},
/*.threaded = */true,
/*.proxy_server = */"",
/*.push_node_id = */""
});
node.setStorageLimit(1024 * 1024 * 1); // 1 Megabyte
auto portStr = to_string(port);
node.bootstrap(bootstrapNodeAddr, portStr.c_str());
const auto &remoteNodes = databaseStorage.getRemoteNodes();
if(!remoteNodes.empty())
node.bootstrap(remoteNodes);
Log::debug("Connecting to bootstrap node (%s) and %u other known nodes that we have connected to previously with port %d", bootstrapNodeAddr, remoteNodes.size(), port);
// TODO: Make this work for multiple threads initializing database at same time
++databaseCount;
if(databaseCount == 1)
{
if(ntpThread)
delete ntpThread;
const int ntpFetchTimestampRetries = 5;
const int ntpFetchFailRetryCooldownSec = 60;
ntpThread = new thread([ntpFetchFailRetryCooldownSec]()
{
ntp::NtpClient ntpClient("pool.ntp.org", 10);
while(databaseCount > 0)
{
int fetchRetryCounter = 0;
while(fetchRetryCounter < ntpFetchTimestampRetries)
{
try
{
ntp::NtpTimestamp ntpTimestamp = ntpClient.getTimestamp();
struct timeval currentLocalTime;
gettimeofday(¤tLocalTime, NULL);
timeOffset = currentLocalTime.tv_sec - ntpTimestamp.seconds;
timeOffsetFraction = currentLocalTime.tv_usec - ntpTimestamp.fractions;
timestampSynced = true;
break;
}
catch(ntp::NtpClientException &e)
{
Log::warn("Failed to sync clock with ntp server, reason: %s. Try #%d", e.what(), fetchRetryCounter);
if(timestampSynced)
this_thread::sleep_for(3s);
}
++fetchRetryCounter;
}
if(fetchRetryCounter == ntpFetchTimestampRetries)
{
if(!timestampSynced)
{
string errMsg = "Failed to retrieve ntp timestamp after ";
errMsg += to_string(ntpFetchTimestampRetries);
errMsg += " retries, giving up";
throw ntp::NtpClientException(errMsg);
}
else
{
Log::warn("Failed to retrieve ntp timestamp after %d retries, retrying in %d seconds", ntpFetchTimestampRetries, ntpFetchFailRetryCooldownSec);
this_thread::sleep_for(chrono::seconds(ntpFetchFailRetryCooldownSec));
}
}
this_thread::sleep_for(60s);
}
});
ntpThread->detach();
}
remoteNodesSaveThread = thread([this]()
{
int saveIntervalMs = 5000; // 5 sec
const int sleepDurationMs = 200;
while(!shuttingDown)
{
for(int i = 0; i < saveIntervalMs / sleepDurationMs; ++i)
{
this_thread::sleep_for(chrono::milliseconds(sleepDurationMs));
if(shuttingDown)
return;
}
databaseStorage.setRemoteNodes(node.exportNodes());
saveIntervalMs = 30000; // 30 sec
}
});
}
Database::~Database()
{
// TODO: Make this work for multiple threads removing database object at same time
--databaseCount;
shuttingDown = true;
remoteNodesSaveThread.join();
node.join();
}
struct ActionGap
{
u64 start;
u64 range;
};
void Database::sendOldDataToPeer(const DatabaseNode nodeToSeed, const shared_ptr<InfoHash> requestResponseInfoHash, const shared_ptr<Value> value, usize valueOffset)
{
Log::debug("Request: Got request to send old data");
try
{
sibs::SafeDeserializer deserializer(value->data.data() + valueOffset, value->data.size() - valueOffset);
bool userWantsCreateNode = deserializer.extract<u8>() == 1;
DatabaseFetchOrder fetchOrder = deserializer.extract<DatabaseFetchOrder>();
if(userWantsCreateNode)
{
Log::debug("Request: Peer wants CreateNode");
databaseStorage.fetchNodeRaw(*nodeToSeed.getRequestHash(), [this, requestResponseInfoHash](const DataView rawData)
{
Log::debug("Request: Sent create packet to requesting peer");
shared_ptr<Value> value = make_shared<Value>((u8*)rawData.data, rawData.size);
nodePutWithRetry(&node, *requestResponseInfoHash, value);
});
}
vector<unique_ptr<u8[]>> userPublicKeys;
// TODO(Performance improvement): Sort actions by gap start and do a binary search to check if raw data is the packet the peer wants
DataViewMap<vector<ActionGap>> actionGaps;
while(!deserializer.empty())
{
unique_ptr<u8[]> userPublicKeyRaw(new u8[PUBLIC_KEY_NUM_BYTES]);
deserializer.extract(userPublicKeyRaw.get(), PUBLIC_KEY_NUM_BYTES);
u64 actionGapStart = deserializer.extract<u64>();
u64 actionGapRange = deserializer.extract<u64>();
DataView userPublicKey(userPublicKeyRaw.get(), PUBLIC_KEY_NUM_BYTES);
actionGaps[userPublicKey].push_back({ actionGapStart, actionGapRange });
userPublicKeys.emplace_back(move(userPublicKeyRaw));
}
if(actionGaps.empty())
Log::debug("No action gaps received, sending all data");
// TODO(Performance improvement): Instead of sending several packets, combine them into one
databaseStorage.fetchNodeAddDataRaw(*nodeToSeed.getRequestHash(), [this, requestResponseInfoHash, &actionGaps](const DataView rawData, const DataView creatorPublicKey, u64 actionCounter)
{
bool sendData = false;
auto actionGapsIt = actionGaps.find(creatorPublicKey);
if(actionGapsIt == actionGaps.end())
{
Log::debug("No action gap received for user %s, sending data", bin2hex((const char*)creatorPublicKey.data, creatorPublicKey.size).c_str());
sendData = true;
}
else
{
for(const auto &userActionGaps : actionGapsIt->second)
{
if(actionCounter >= userActionGaps.start && actionCounter <= userActionGaps.start + userActionGaps.range)
{
Log::debug("Node action counter %llu is requested by peer (%llu - %llu)", actionCounter, userActionGaps.start, userActionGaps.start + userActionGaps.range);
sendData = true;
break;
}
}
}
if(!sendData) return;
shared_ptr<Value> value = make_shared<Value>((u8*)rawData.data, rawData.size);
nodePutWithRetry(&node, *requestResponseInfoHash, value);
this_thread::sleep_for(chrono::milliseconds(50));
}, fetchOrder);
}
catch (std::exception &e)
{
Log::warn("Failed while serving peer, error: %s", e.what());
}
}
void Database::seed(const DatabaseNode &nodeToSeed, DatabaseFetchOrder fetchOrder)
{
if(seedInfoMap.find(*nodeToSeed.getRequestHash()) != seedInfoMap.end())
{
Log::warn("You are already seeding node %s, ignoring...", nodeToSeed.getRequestHash()->toString().c_str());
return;
}
DatabaseSeedInfo newSeedInfo;
// TODO: Use cached files and seed those. If none exists, request new files to seed.
// If nobody requests my cached files in a long time, request new files to seed and remove cached files
// (only if there are plenty of other seeders for the cached files. This could also cause race issue
// where all nodes with a cached file delete it at same time).
databaseStorage.setNodeDecryptionKey(*nodeToSeed.getRequestHash(), DataView(nodeToSeed.getNodeEncryptionKey()->data, nodeToSeed.getNodeEncryptionKey()->size));
Log::debug("Seeding key: %s", nodeToSeed.getRequestHash()->toString().c_str());
DhtKey dhtKey(*nodeToSeed.getRequestHash());
auto newDataListenerFuture = node.listen(dhtKey.getNewDataListenerKey(), [this, nodeToSeed](const shared_ptr<Value> value)
{
Log::debug("Seed: New data listener received data...");
const Hash requestHash(value->data.data(), value->data.size());
if(requestHash == *nodeToSeed.getRequestHash())
return true;
//return listenCreateData(value, requestHash, encryptionKey);
else
return listenAddData(value, requestHash, nodeToSeed.getRequestHash(), nodeToSeed.getNodeEncryptionKey());
});
newSeedInfo.newDataListenerFuture = make_shared<future<size_t>>(move(newDataListenerFuture));
u8 responseKey[OPENDHT_INFOHASH_LEN];
randombytes_buf(responseKey, OPENDHT_INFOHASH_LEN);
shared_ptr<InfoHash> responseKeyShared = make_shared<InfoHash>(responseKey, OPENDHT_INFOHASH_LEN);;
newSeedInfo.reponseKeyInfoHash = responseKeyShared;
// TODO: If this response key is spammed, generate a new one.
auto responseKeyFuture = node.listen(*responseKeyShared, [this, nodeToSeed](const shared_ptr<Value> value)
{
if(value->data.size() == OPENDHT_INFOHASH_LEN)
{
sibs::SafeDeserializer deserializer(value->data.data(), value->data.size());
InfoHash pingResponseKey;
deserializer.extract(pingResponseKey.data(), OPENDHT_INFOHASH_LEN);
shared_ptr<Value> responseValue = make_shared<Value>();
nodePutWithRetry(&node, pingResponseKey, responseValue);
return true;
}
const Hash requestHash(value->data.data(), value->data.size());
if(requestHash == *nodeToSeed.getRequestHash())
return listenCreateData(value, requestHash, nodeToSeed.getNodeEncryptionKey());
else
return listenAddData(value, requestHash, nodeToSeed.getRequestHash(), nodeToSeed.getNodeEncryptionKey());
});
newSeedInfo.responseKeyFuture = make_shared<future<size_t>>(move(responseKeyFuture));
// TODO:!!! Before listening on this key, we should check how many remote peers are also providing this data.
// This is to prevent too many peers from responding to a request to get old data.
auto requestOldDataListenerFuture = node.listen(dhtKey.getRequestOldDataKey(), [this, nodeToSeed, responseKeyShared](const shared_ptr<Value> value)
{
try
{
static_assert(HASH_LEN == OPENDHT_INFOHASH_LEN, "Wrong hashlen size, did it change with opendht upgrade?");
sibs::SafeDeserializer deserializer(value->data.data(), value->data.size());
u16 requestStructureVersion = deserializer.extract<u16>();
if(requestStructureVersion != DATABASE_REQUEST_OLD_DATA_STRUCTURE_VERSION)
{
Log::warn("Request: structure is version %d but we are at version %d, ignoring request", requestStructureVersion, DATABASE_REQUEST_OLD_DATA_STRUCTURE_VERSION);
return true;
}
shared_ptr<InfoHash> requestResponseInfoHash = make_shared<InfoHash>();
deserializer.extract(requestResponseInfoHash->data(), OPENDHT_INFOHASH_LEN);
if(*responseKeyShared == *requestResponseInfoHash)
{
Log::debug("Request: Ignorning request for old data from ourself");
return true;
}
else
Log::debug("Request: Got request from somebody else");
u8 pingResponseKey[OPENDHT_INFOHASH_LEN];
randombytes_buf(pingResponseKey, OPENDHT_INFOHASH_LEN);
InfoHash pingResponseKeyInfoHash(pingResponseKey, OPENDHT_INFOHASH_LEN);
usize valueOffset = value->data.size() - deserializer.getSize();
node.listen(pingResponseKeyInfoHash, [this, value, requestResponseInfoHash, nodeToSeed, valueOffset](const shared_ptr<Value> _)
{
sendOldDataToPeer(nodeToSeed, requestResponseInfoHash, value, valueOffset);
return false;
});
shared_ptr<Value> pingRequest = make_shared<Value>(pingResponseKey, OPENDHT_INFOHASH_LEN);
nodePutWithRetry(&node, *requestResponseInfoHash, pingRequest);
}
catch (std::exception &e)
{
Log::warn("Failed while serving peer, error: %s", e.what());
}
return true;
});
newSeedInfo.requestOldDataListenerFuture = make_shared<future<size_t>>(move(requestOldDataListenerFuture));
seedInfoMap[*nodeToSeed.getRequestHash()] = newSeedInfo;
sibs::SafeSerializer serializer;
serializer.add(DATABASE_REQUEST_OLD_DATA_STRUCTURE_VERSION);
serializer.add(responseKey, OPENDHT_INFOHASH_LEN);
bool iHaveCreateNode = databaseStorage.doesNodeExist(*nodeToSeed.getRequestHash());
serializer.add(iHaveCreateNode ? (u8)0 : (u8)1);
serializer.add(fetchOrder);
Signature::MapPublicKey<u64> userLatestActionCounter;
databaseStorage.fetchNodeUserActionGaps(*nodeToSeed.getRequestHash(), [&serializer, &userLatestActionCounter](const DataView userPublicKeyRaw, u64 actionGapStart, u64 actionGapRange)
{
serializer.add((const u8*)userPublicKeyRaw.data, PUBLIC_KEY_NUM_BYTES);
serializer.add(actionGapStart);
serializer.add(actionGapRange);
Signature::PublicKey userPublicKey((const char*)userPublicKeyRaw.data, userPublicKeyRaw.size);
userLatestActionCounter[userPublicKey] = std::max(userLatestActionCounter[userPublicKey], actionGapStart + actionGapRange);
});
databaseStorage.fetchNodeUserLatestActionCounter(*nodeToSeed.getRequestHash(), [&userLatestActionCounter](const DataView userPublicKeyRaw, u64 latestActionCounter)
{
Signature::PublicKey userPublicKey((const char*)userPublicKeyRaw.data, userPublicKeyRaw.size);
userLatestActionCounter[userPublicKey] = std::max(userLatestActionCounter[userPublicKey], latestActionCounter + 1);
});
for(auto userLatestActionCounterData : userLatestActionCounter)
{
// Public key
serializer.add((const u8*)userLatestActionCounterData.first.getData(), PUBLIC_KEY_NUM_BYTES);
// Latest action counter start
serializer.add(userLatestActionCounterData.second);
// Latest action counter range (infinite range, meaning we want all packets older than start (latest known packet by user))
serializer.add(~(u64)0ULL - userLatestActionCounterData.second);
}
Log::debug("Sending request for old data");
shared_ptr<Value> requestValue = make_shared<Value>(move(serializer.getBuffer()));
nodePutWithRetry(&node, dhtKey.getRequestOldDataKey(), requestValue);
}
void Database::stopSeeding(const Hash &nodeHash)
{
auto seedInfoIt = seedInfoMap.find(nodeHash);
if(seedInfoIt != seedInfoMap.end())
{
// TODO: Verify if doing get on listener future stalls program forever... Opendht documentation is not clear on this
DhtKey dhtKey(nodeHash);
node.cancelListen(dhtKey.getNewDataListenerKey(), seedInfoIt->second.newDataListenerFuture->get());
node.cancelListen(dhtKey.getRequestOldDataKey(), seedInfoIt->second.requestOldDataListenerFuture->get());
node.cancelListen(*seedInfoIt->second.reponseKeyInfoHash, seedInfoIt->second.responseKeyFuture->get());
seedInfoMap.erase(seedInfoIt);
}
}
void Database::loadNode(const Hash &nodeHash, DatabaseLoadOrder loadOrder)
{
databaseStorage.loadNode(nodeHash, loadOrder);
}
unique_ptr<DatabaseCreateResponse> Database::create()
{
shared_ptr<Signature::KeyPair> creatorKeyPair = make_shared<Signature::KeyPair>();
auto adminGroupId = uuidGen();
assert(adminGroupId.size() == GROUP_ID_LENGTH);
// Header
sibs::SafeSerializer serializer;
serializer.add(DATABASE_CREATE_PACKET_STRUCTURE_VERSION);
u64 timestampCombined = getSyncedTimestampUtc().getCombined();
serializer.add(timestampCombined);
serializer.add((u8*)creatorKeyPair->getPublicKey().getData(), PUBLIC_KEY_NUM_BYTES);
serializer.add(adminGroupId.data, adminGroupId.size());
try
{
unsigned char *encryptionKeyRaw = new unsigned char[ENCRYPTION_KEY_BYTE_SIZE];
Encryption::generateKey(encryptionKeyRaw);
shared_ptr<OwnedByteArray> encryptionKey = make_shared<OwnedByteArray>(encryptionKeyRaw, ENCRYPTION_KEY_BYTE_SIZE);
shared_ptr<Hash> hashRequestKey = make_shared<Hash>(serializer.getBuffer().data(), serializer.getBuffer().size());
databaseStorage.setNodeDecryptionKey(*hashRequestKey, DataView(encryptionKey->data, encryptionKey->size));
databaseStorage.createStorage(*hashRequestKey, creatorKeyPair->getPublicKey(), DataView(adminGroupId.data, adminGroupId.size()), timestampCombined, (const u8*)serializer.getBuffer().data(), serializer.getBuffer().size());
DhtKey dhtKey(*hashRequestKey);
shared_ptr<Value> createDataValue = make_shared<Value>(move(serializer.getBuffer()));
nodePutWithRetry(&node, dhtKey.getNewDataListenerKey(), createDataValue);
shared_ptr<OwnedByteArray> adminGroupIdResponse = make_shared<OwnedByteArray>(new u8[GROUP_ID_LENGTH], GROUP_ID_LENGTH);
memcpy(adminGroupIdResponse->data, adminGroupId.data, GROUP_ID_LENGTH);
return make_unique<DatabaseCreateResponse>(creatorKeyPair, adminGroupIdResponse, encryptionKey, hashRequestKey);
}
catch (EncryptionException &e)
{
throw DatabaseCreateException("Failed to encrypt data for 'create' request");
}
}
void Database::addData(const DatabaseNode &nodeInfo, const Signature::KeyPair &userToPerformActionWith, DataView dataToAdd)
{
sibs::SafeSerializer serializer;
serializer.add(DATABASE_ADD_PACKET_STRUCTURE_VERSION);
u64 timestampCombined = getSyncedTimestampUtc().getCombined();
serializer.add(timestampCombined);
serializer.add(DatabaseOperation::ADD_DATA);
u64 newActionCounter = databaseStorage.getUserActionCounter(*nodeInfo.getRequestHash(), userToPerformActionWith.getPublicKey()) + 1;
serializer.add(newActionCounter);
DataView encryptionKey(nodeInfo.getNodeEncryptionKey()->data, ENCRYPTION_KEY_BYTE_SIZE);
Encryption encryptedBody(dataToAdd, encryptionKey);
OwnedByteArray requestData = combine(serializer, encryptedBody);
string signedRequestData = userToPerformActionWith.getPrivateKey().sign(requestData.getView());
OwnedByteArray stagedAddObject = combine(userToPerformActionWith.getPublicKey(), signedRequestData);
Hash requestDataHash(stagedAddObject.data, stagedAddObject.size);
DataView encryptedDataView((char*)requestData.data + serializer.getBuffer().size(), requestData.size - serializer.getBuffer().size());
databaseStorage.appendStorage(*nodeInfo.getRequestHash(), requestDataHash, DatabaseOperation::ADD_DATA, newActionCounter, userToPerformActionWith.getPublicKey(), timestampCombined, (u8*)stagedAddObject.data, stagedAddObject.size, encryptedDataView);
DhtKey dhtKey(*nodeInfo.getRequestHash());
shared_ptr<Value> addDataValue = make_shared<Value>((u8*)stagedAddObject.data, stagedAddObject.size);
nodePutWithRetry(&node, dhtKey.getNewDataListenerKey(), addDataValue);
}
void Database::addUser(const DatabaseNode &nodeInfo, const Signature::KeyPair &userToPerformActionWith, const Signature::PublicKey &userToAddPublicKey, const DataView &groupToAddUserTo)
{
sibs::SafeSerializer serializer;
serializer.add(DATABASE_ADD_PACKET_STRUCTURE_VERSION);
u64 timestampCombined = getSyncedTimestampUtc().getCombined();
serializer.add(timestampCombined);
serializer.add(DatabaseOperation::ADD_USER);
u64 newActionCounter = databaseStorage.getUserActionCounter(*nodeInfo.getRequestHash(), userToPerformActionWith.getPublicKey()) + 1;
serializer.add(newActionCounter);
usize additionalDataOffset = serializer.getBuffer().size();
serializer.add((u8*)userToAddPublicKey.getData(), PUBLIC_KEY_NUM_BYTES);
serializer.add((uint8_t*)groupToAddUserTo.data, groupToAddUserTo.size);
auto padding = uuidGen();
assert(padding.size() == 16);
serializer.add(padding.data, padding.size());
DataView requestData { serializer.getBuffer().data(), serializer.getBuffer().size() };
string signedRequestData = userToPerformActionWith.getPrivateKey().sign(requestData);
OwnedByteArray stagedAddObject = combine(userToPerformActionWith.getPublicKey(), signedRequestData);
Hash requestDataHash(stagedAddObject.data, stagedAddObject.size);
DataView additionalDataView((void*)(static_cast<const char*>(requestData.data) + additionalDataOffset), requestData.size - additionalDataOffset);
databaseStorage.appendStorage(*nodeInfo.getRequestHash(), requestDataHash, DatabaseOperation::ADD_USER, newActionCounter, userToPerformActionWith.getPublicKey(), timestampCombined, (u8*)stagedAddObject.data, stagedAddObject.size, additionalDataView);
DhtKey dhtKey(*nodeInfo.getRequestHash());
shared_ptr<Value> addDataValue = make_shared<Value>((u8*)stagedAddObject.data, stagedAddObject.size);
nodePutWithRetry(&node, dhtKey.getNewDataListenerKey(), addDataValue);
}
ntp::NtpTimestamp Database::getSyncedTimestampUtc()
{
while(!timestampSynced)
{
this_thread::sleep_for(10ms);
}
struct timeval currentLocalTime;
gettimeofday(¤tLocalTime, NULL);
ntp::NtpTimestamp timestamp;
timestamp.seconds = currentLocalTime.tv_sec - timeOffset;
timestamp.fractions = currentLocalTime.tv_usec - timeOffsetFraction;
return timestamp;
}
void Database::deserializeCreateRequest(const shared_ptr<dht::Value> &value, const Hash &hash, const shared_ptr<OwnedByteArray> encryptionKey)
{
sibs::SafeDeserializer deserializer(value->data.data(), value->data.size());
u16 packetStructureVersion = deserializer.extract<u16>();
if(packetStructureVersion != DATABASE_CREATE_PACKET_STRUCTURE_VERSION)
{
string errMsg = "Received 'create' request with packet structure version ";
errMsg += to_string(packetStructureVersion);
errMsg += ", but our packet structure version is ";
errMsg += to_string(DATABASE_CREATE_PACKET_STRUCTURE_VERSION);
throw sibs::DeserializeException(errMsg);
}
u64 creationDate = deserializer.extract<u64>();
/* // TODO: This doesn't seem to work right now, fix it
auto currentTimestamp = getSyncedTimestampUtc();
if(creationDate > currentTimestamp.getCombined())
{
auto creationDateTimestamp = ntp::NtpTimestamp::fromCombined(creationDate);
string errMsg = "Packet is from the future. Packet creation time: ";
errMsg += to_string((double)creationDateTimestamp.seconds + creationDateTimestamp.getFractionAsSeconds());
errMsg += ", current time: ";
errMsg += to_string((double)currentTimestamp.seconds + currentTimestamp.getFractionAsSeconds());
throw sibs::DeserializeException(errMsg);
}
*/
char creatorPublicKeyRaw[PUBLIC_KEY_NUM_BYTES];
deserializer.extract((u8*)creatorPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
Signature::PublicKey userPublicKey(creatorPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
uint8_t adminGroupId[GROUP_ID_LENGTH];
deserializer.extract(adminGroupId, GROUP_ID_LENGTH);
databaseStorage.createStorage(hash, userPublicKey, DataView(adminGroupId, GROUP_ID_LENGTH), creationDate, value->data.data(), value->data.size());
}
void Database::deserializeAddRequest(const shared_ptr<dht::Value> &value, const Hash &requestDataHash, const std::shared_ptr<Hash> &nodeHash, const shared_ptr<OwnedByteArray> encryptionKey)
{
sibs::SafeDeserializer deserializer(value->data.data(), value->data.size());
char creatorPublicKeyRaw[PUBLIC_KEY_NUM_BYTES];
deserializer.extract((u8*)creatorPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
Signature::PublicKey creatorPublicKey(creatorPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
DataView signedData((void*)deserializer.getBuffer(), deserializer.getSize());
string unsignedData = creatorPublicKey.unsign(signedData);
sibs::SafeDeserializer deserializerUnsigned((u8*)unsignedData.data(), unsignedData.size());
u16 packetStructureVersion = deserializerUnsigned.extract<u16>();
if(packetStructureVersion != DATABASE_CREATE_PACKET_STRUCTURE_VERSION)
{
string errMsg = "Received 'create' request with packet structure version ";
errMsg += to_string(packetStructureVersion);
errMsg += ", but our packet structure version is ";
errMsg += to_string(DATABASE_CREATE_PACKET_STRUCTURE_VERSION);
throw sibs::DeserializeException(errMsg);
}
u64 creationDate = deserializerUnsigned.extract<u64>();
auto currentTimestamp = getSyncedTimestampUtc();
/* // TODO: This doesn't seem to work right now, fix it
if(creationDate > currentTimestamp.getCombined())
{
auto creationDateTimestamp = ntp::NtpTimestamp::fromCombined(creationDate);
string errMsg = "Packet is from the future. Packet creation time: ";
errMsg += to_string((double)creationDateTimestamp.seconds + creationDateTimestamp.getFractionAsSeconds());
errMsg += ", current time: ";
errMsg += to_string((double)currentTimestamp.seconds + currentTimestamp.getFractionAsSeconds());
throw sibs::DeserializeException(errMsg);
}
*/
DatabaseOperation operation = deserializerUnsigned.extract<DatabaseOperation>();
u64 newActionCounter = deserializerUnsigned.extract<u64>();
DataView additionalDataView((void*)deserializerUnsigned.getBuffer(), deserializerUnsigned.getSize());
databaseStorage.appendStorage(*nodeHash, requestDataHash, operation, newActionCounter, creatorPublicKey, creationDate, value->data.data(), value->data.size(), additionalDataView);
}
bool Database::listenCreateData(shared_ptr<dht::Value> value, const Hash &hash, const shared_ptr<OwnedByteArray> encryptionKey)
{
Log::debug("Got create data in node %s", hash.toString().c_str());
try
{
// This check is here to reduce processing, it doesn't matter much if the packet bypasses this,
// the database has constraint to deal with this in multi-threaded way
if(databaseStorage.doesNodeExist(hash))
throw DatabaseStorageAlreadyExists("Create request hash is equal to hash already in storage (duplicate data?)");
deserializeCreateRequest(value, hash, encryptionKey);
}
catch (exception &e)
{
Log::warn("Failed to deserialize 'create' request: %s", e.what());
}
return true;
}
bool Database::listenAddData(shared_ptr<dht::Value> value, const Hash &requestDataHash, const std::shared_ptr<Hash> nodeHash, const shared_ptr<OwnedByteArray> encryptionKey)
{
Log::debug("Got add data in node %s", nodeHash->toString().c_str());
try
{
// This check is here to reduce processing, it doesn't matter much if the packet bypasses this,
// the database has constraint to deal with this in multi-threaded way
if(databaseStorage.doesDataExist(requestDataHash))
throw DatabaseStorageAlreadyExists("Add data request hash is equal to hash already in storage (duplicate data?)");
deserializeAddRequest(value, requestDataHash, nodeHash, encryptionKey);
}
catch (RequestQuarantineException &e)
{
Log::warn("Request was put in quarantine, will be processed later");
}
catch (exception &e)
{
Log::warn("Failed to deserialize 'add' request: %s", e.what());
}
return true;
}
bool Database::doesStoredUserExist(const string &username) const
{
return databaseStorage.doesStoredUserExist(username);
}
void Database::storeUserWithoutNodes(const string &username, const string &password)
{
return databaseStorage.storeUserWithoutNodes(username, password);
}
void Database::storeNodeInfoForUserEncrypted(const DatabaseNode &nodeInfo, const string &username, const string &password, const Signature::KeyPair &keyPair)
{
return databaseStorage.storeNodeInfoForUserEncrypted(nodeInfo, username, password, keyPair);
}
MapHash<StoredNodeInfo> Database::getStoredNodeUserInfoDecrypted(const string &username, const string &password) const
{
return databaseStorage.getStoredNodeUserInfoDecrypted(username, password);
}
vector<OwnedByteArray> Database::getUserGroups(const Hash &nodeHash, const Signature::PublicKey &userPublicKey) const
{
return databaseStorage.getUserGroups(nodeHash, userPublicKey);
}
std::future<size_t> Database::receiveCustomMessage(const dht::InfoHash &receiveMessageKey, ReceiveCustomMessageCallbackFunc callbackFunc)
{
dht::InfoHash responseKey = receiveMessageKey;
++responseKey[0];
return node.listen(receiveMessageKey, [callbackFunc, this, responseKey](const shared_ptr<Value> value)
{
sibs::SafeSerializer serializer = callbackFunc(value->data.data(), value->data.size());
if(!serializer.getBuffer().empty())
{
shared_ptr<Value> responseValue = make_shared<Value>(move(serializer.getBuffer()));
nodePutWithRetry(&node, responseKey, responseValue);
}
return true;
});
}
void Database::sendCustomMessage(const dht::InfoHash &requestKey, vector<u8> &&data)
{
shared_ptr<Value> value = make_shared<Value>(move(data));
nodePutWithRetry(&node, requestKey, value);
}
std::future<size_t> Database::sendCustomMessage(const dht::InfoHash &requestKey, vector<u8> &&data, SendCustomMessageCallbackFunc callbackFunc)
{
dht::InfoHash responseKey = requestKey;
++responseKey[0];
auto listener = node.listen(responseKey, [callbackFunc](const shared_ptr<Value> value)
{
return callbackFunc(true, value->data.data(), value->data.size());
});
shared_ptr<Value> value = make_shared<Value>(move(data));
nodePutWithRetry(&node, requestKey, value);
return listener;
}
void Database::cancelNodeListener(const dht::InfoHash &infoHash, std::future<size_t> &nodeListener)
{
node.cancelListen(infoHash, nodeListener.get());
}
int Database::clearCache()
{
return databaseStorage.clearCache();
}
dht::InfoHash Database::getInfoHash(const void *data, usize size)
{
return dht::InfoHash::get((const u8*)data, size);
}
}
|