aboutsummaryrefslogtreecommitdiff
path: root/src/Database.cpp
blob: e3b9f3d9066128cf45d6212b351c211b67179b8d (plain)
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
#include "../include/Database.hpp"
#include "../include/Group.hpp"
#include "../include/LocalUser.hpp"
#include "../include/RemoteUser.hpp"
#include <opendht.h>
#include <fmt/format.h>
#include <sodium/crypto_box_curve25519xchacha20poly1305.h>
#include <thread>
#include <chrono>
#include <sibs/SafeSerializer.hpp>
#include <sibs/SafeDeserializer.hpp>
#include <cassert>

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 thread *ntpThread = nullptr;
static bool timestampSynced = false;
static InfoHash CREATE_DATA_HASH = InfoHash::get("__odhtdb__.create_data");
static InfoHash ADD_DATA_HASH = InfoHash::get("__odhtdb__.add_data");

const int OPENDHT_INFOHASH_LEN = 20;

namespace odhtdb
{
    Database::Database(const char *bootstrapNodeAddr, u16 port, boost::filesystem::path storageDir)
    {
        node.run(port, dht::crypto::generateIdentity(), true);
        fmt::MemoryWriter portStr;
        portStr << port;
        node.bootstrap(bootstrapNodeAddr, portStr.c_str());

        // TODO: Make this work for multiple threads initializing database at same time
        ++databaseCount;
        if(databaseCount == 1)
        {
            if(ntpThread)
                delete ntpThread;

            ntpThread = new thread([]()
            {
                ntp::NtpClient ntpClient("pool.ntp.org");
                while(databaseCount > 0)
                {
                    ntp::NtpTimestamp ntpTimestamp = ntpClient.getTimestamp();
                    timeOffset = time(nullptr) - ntpTimestamp.seconds;
                    timestampSynced = true;
                    // TODO: Also use timestamp fraction (milliseconds)
                    this_thread::sleep_for(60s);
                }
                timestampSynced = false;
            });

            // TODO: Catch std::system_error instead of this if-statement
            if(ntpThread->joinable())
                ntpThread->detach();
        }

        while(!timestampSynced)
        {
            this_thread::sleep_for(10ms);
        }
    }

    Database::~Database()
    {
        // TODO: Make this work for multiple threads removing database object at same time
        --databaseCount;
        node.join();
    }

    void Database::seed()
    {
        // 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)

        using std::placeholders::_1;
        node.listen(CREATE_DATA_HASH, bind(&Database::listenCreateData, this, _1));
        node.listen(ADD_DATA_HASH, bind(&Database::listenAddData, this, _1));
    }

    void Database::create(const Key &key, Group *primaryAdminGroup)
    {
        // TODO: Append fractions to get real microseconds time
        u64 timeMicroseconds = ((u64)getSyncedTimestampUtc().seconds) * 1000000ull;
        stagedCreateObjects.emplace_back(StagedCreateObject(key, primaryAdminGroup, timeMicroseconds));
    }

    void Database::add(const Key &key, DataView data, LocalUser *creator)
    {
        // TODO: Append fractions to get real microseconds time
        u64 timeMicroseconds = ((u64)getSyncedTimestampUtc().seconds) * 1000000ull;
        stagedAddObjects.emplace_back(StagedAddObject(key, data, timeMicroseconds, creator->getPublicKey()));
    }

    void Database::commit()
    {
        // TODO: Combine staged objects into one object for efficiency.
        // TODO: Add rollback

        printf("Num objects to create: %d\n", stagedCreateObjects.size());
        for(StagedCreateObject &stagedObject : stagedCreateObjects)
        {
            commitStagedCreateObject(stagedObject);
        }
        stagedCreateObjects.clear();

        printf("Num objects to add: %d\n", stagedAddObjects.size());
        for(StagedAddObject &stagedObject : stagedAddObjects)
        {
            commitStagedAddObject(stagedObject);
        }
        stagedAddObjects.clear();
        
        // TODO: Add node.listen here to get notified when remote peers got the commit, then we can say we can return
    }

    // TODO: If same key already exists, fail the operation.
    // Security issue: A malicious remote peer (or routing peer) could listen to this create request and build their own
    // create request using same key, to steal ownership of the key.
    // Possible solution: If odhtdb is for example used to build a chat application, then the key could be the chat channel id
    // which could be created by hashing channel generated id and ownership information.
    // Remote peers would then not be able to steal ownership of the key since hash of ownership data has to match the key.
    // The key (channel id + ownership info) could then be shared with friends and they can use the key to join your channel.
    void Database::commitStagedCreateObject(const StagedCreateObject &stagedObject)
    {
        // TODO: Use (ed25519 or poly1305) and curve25519
        // TODO: Implement gas and price (refill when serving content (seeding) or by waiting. This is done to prevent spamming and bandwidth leeching)
        sibs::SafeSerializer serializer;
        assert(stagedObject.key.hashedKey.size() == OPENDHT_INFOHASH_LEN);
        serializer.add(stagedObject.key.hashedKey.data(), stagedObject.key.hashedKey.size());
        serializer.add(stagedObject.timestamp);
        serializer.add((u8)stagedObject.primaryAdminGroup->getName().size());
        serializer.add((u8*)stagedObject.primaryAdminGroup->getName().data(), stagedObject.primaryAdminGroup->getName().size());
        assert(stagedObject.primaryAdminGroup->getUsers().size() <= 255);
        serializer.add((u8)stagedObject.primaryAdminGroup->getUsers().size());
        for(User *user : stagedObject.primaryAdminGroup->getUsers())
        {
            serializer.add((u8*)user->getPublicKey().getData(), PUBLIC_KEY_NUM_BYTES);
            serializer.add((u8)user->getName().size());
            serializer.add((u8*)user->getName().data(), user->getName().size());
        }
        
        // TODO: Verify if serializer buffer needs to survive longer than this scope
        Value createDataValue(serializer.getBuffer().data(), serializer.getBuffer().size());
        node.put(CREATE_DATA_HASH, move(createDataValue), [](bool ok)
        {
            // TODO: Handle failure to put data
            if(!ok)
                fprintf(stderr, "Failed to put: %s, what to do?\n", "commitStagedCreateObject");
        }/* TODO: How to make this work?, time_point(), false*/);

        // Post data for listeners of this key
        /*
        Value putKeyValue(serializer.getBuffer().data() + OPENDHT_INFOHASH_LEN, serializer.getBuffer().size() - OPENDHT_INFOHASH_LEN);
        node.put(stagedObject.key.hashedKey, move(putKeyValue), [](bool ok)
        {
            // TODO: Handle failure to put data
            if(!ok)
                fprintf(stderr, "Failed to put for listeners: %s, what to do?\n", "commitStagedCreateObject");
        });
        */
    }

    void Database::commitStagedAddObject(const StagedAddObject &stagedObject)
    {
        // TODO: Use (ed25519 or poly1305) and curve25519
        // TODO: Implement gas and price (refill when serving content (seeding) or by waiting. This is done to prevent spamming and bandwidth leeching)
        sibs::SafeSerializer serializer;
        assert(stagedObject.key.hashedKey.size() == OPENDHT_INFOHASH_LEN);
        serializer.add(stagedObject.key.hashedKey.data(), OPENDHT_INFOHASH_LEN);
        serializer.add(stagedObject.timestamp);
        serializer.add((u8*)stagedObject.creatorPublicKey.getData(), PUBLIC_KEY_NUM_BYTES);
        assert(stagedObject.data.size < 0xFFFF - 120);
        serializer.add((u16)stagedObject.data.size);
        serializer.add((u8*)stagedObject.data.data, stagedObject.data.size);

        // TODO: Verify if serializer buffer needs to survive longer than this scope
        Value addDataValue(serializer.getBuffer().data(), serializer.getBuffer().size());
        node.put(ADD_DATA_HASH, move(addDataValue), [](bool ok)
        {
            // TODO: Handle failure to put data
            if(!ok)
                fprintf(stderr, "Failed to put for all: %s, what to do?\n", "commitStagedAddObject");
        });

        // Post data for listeners of this key
        /*
        Value putKeyValue(serializer.getBuffer().data() + OPENDHT_INFOHASH_LEN, serializer.getBuffer().size() - OPENDHT_INFOHASH_LEN);
        node.put(stagedObject.key.hashedKey, move(putKeyValue), [](bool ok)
        {
            // TODO: Handle failure to put data
            if(!ok)
                fprintf(stderr, "Failed to put for listeners: %s, what to do?\n", "commitStagedAddObject");
        });
        */
    }

    ntp::NtpTimestamp Database::getSyncedTimestampUtc() const
    {
        assert(timestampSynced);
        ntp::NtpTimestamp timestamp;
        timestamp.seconds = time(nullptr) - timeOffset;
        timestamp.fractions = 0; // TODO: Set this
        return timestamp;
    }

    StagedCreateObject Database::deserializeCreateRequest(const std::shared_ptr<dht::Value> &value)
    {
        StagedCreateObject result;

        sibs::SafeDeserializer deserializer(value->data.data(), value->data.size());
        u8 entryKeyRaw[OPENDHT_INFOHASH_LEN];
        deserializer.extract(entryKeyRaw, OPENDHT_INFOHASH_LEN);
        result.key.hashedKey = InfoHash(entryKeyRaw, OPENDHT_INFOHASH_LEN);
        result.timestamp = deserializer.extract<u64>();

        u8 adminGroupNameSize = deserializer.extract<u8>();
        string adminGroupName;
        adminGroupName.resize(adminGroupNameSize);
        deserializer.extract((u8*)&adminGroupName[0], adminGroupNameSize);
        result.primaryAdminGroup = new Group(adminGroupName);

        u8 numUsers = deserializer.extract<u8>();
        for(int i = 0; i < numUsers; ++i)
        {
            char userPublicKeyRaw[PUBLIC_KEY_NUM_BYTES];
            deserializer.extract((u8*)userPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
            Signature::PublicKey userPublicKey(userPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
            
            u8 userNameSize = deserializer.extract<u8>();
            string userName;
            userName.resize(userNameSize);
            deserializer.extract((u8*)&userName[0], userNameSize);
            
            RemoteUser *user = RemoteUser::create(userPublicKey, userName);
            result.primaryAdminGroup->addUser(user);
        }
        
        // NOTE: There might be more data in deserializer, but we can ignore those; we already got all data we need
        return result;
    }

    StagedAddObject Database::deserializeAddRequest(const std::shared_ptr<dht::Value> &value)
    {
        StagedAddObject result;

        sibs::SafeDeserializer deserializer(value->data.data(), value->data.size());
        u8 entryKeyRaw[OPENDHT_INFOHASH_LEN];
        deserializer.extract(entryKeyRaw, OPENDHT_INFOHASH_LEN);
        result.key.hashedKey = InfoHash(entryKeyRaw, OPENDHT_INFOHASH_LEN);
        result.timestamp = deserializer.extract<u64>();
        
        char creatorPublicKeyRaw[PUBLIC_KEY_NUM_BYTES];
        deserializer.extract((u8*)creatorPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
        Signature::PublicKey creatorPublicKey(creatorPublicKeyRaw, PUBLIC_KEY_NUM_BYTES);
        
        u16 dataSize = deserializer.extract<u16>();
        char *data = (char*)malloc(dataSize);
        if(!data)
            throw sibs::DeserializeException("Failed to allocate memory for add request");
        result.data.data = data;
        result.data.size = dataSize;

        return result;
    }

    bool Database::listenCreateData(std::shared_ptr<dht::Value> value)
    {
        printf("Got create data\n");
        try
        {
            // TODO: Verify createObject timestamp is not in the future
            StagedCreateObject createObject = deserializeCreateRequest(value);
            databaseStorage.createStorage(createObject.key, { createObject.primaryAdminGroup }, createObject.timestamp);
            //delete createObject.primaryAdminGroup;
        }
        catch (sibs::DeserializeException &e)
        {
            fprintf(stderr, "Warning: Failed to deserialize 'create' request: %s\n", e.what());
        }
        catch (DatabaseStorageAlreadyExists &e)
        {
            fprintf(stderr, "Warning: Failed to deserialize 'create' request: %s\n", e.what());
        }
        return true;
    }

    bool Database::listenAddData(std::shared_ptr<dht::Value> value)
    {
        printf("Got add data\n");
        try
        {
            // TODO: Verify createObject timestamp is not in the future
            StagedAddObject addObject = deserializeAddRequest(value);
            databaseStorage.appendStorage(addObject.key, addObject.data, addObject.timestamp, addObject.creatorPublicKey);
            //free(addObject.data.data);
        }
        catch (sibs::DeserializeException &e)
        {
            fprintf(stderr, "Warning: Failed to deserialize 'add' request: %s\n", e.what());
        }
        catch (DatabaseStorageNotFound &e)
        {
            fprintf(stderr, "Warning: Failed to deserialize 'add' request: %s\n", e.what());
        }
        return true;
    }
}