aboutsummaryrefslogtreecommitdiff
path: root/include/odhtdb/Database.hpp
blob: 372b19c8896aadafec2c063705001d7ab58bff54 (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
#pragma once

#include "types.hpp"
#include "Key.hpp"
#include "DataView.hpp"
#include "DatabaseStorage.hpp"
#include "Hash.hpp"
#include "utils.hpp"
#include "Signature.hpp"
#include "Permission.hpp"
#include "DatabaseNode.hpp"
#include "Encryption.hpp"
#include "OwnedMemory.hpp"
#include "DatabaseOperation.hpp"
#include "DatabaseOrder.hpp"
#include <opendht/dhtrunner.h>
#include <vector>
#include <ntp/NtpClient.hpp>
#include <boost/filesystem/path.hpp>
#include <sibs/SafeSerializer.hpp>
#include <stdexcept>
#include <functional>

namespace odhtdb
{    
    class CommitCreateException : public std::runtime_error
    {
    public:
        CommitCreateException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    class CommitAddException : public std::runtime_error
    {
    public:
        CommitAddException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    class DatabaseCreateException : public std::runtime_error
    {
    public:
        DatabaseCreateException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    class DatabaseAddException : public std::runtime_error
    {
    public:
        DatabaseAddException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    struct DatabaseCreateNodeRequest
    {
        DISABLE_COPY(DatabaseCreateNodeRequest)
        
        const Hash *nodeHash;
        u64 timestamp; // In microseconds
        const Signature::PublicKey *creatorPublicKey;
        const DataView groupId;
        bool loadedFromCache;
        
        DatabaseCreateNodeRequest(const Hash *_nodeHash, u64 _timestamp, const Signature::PublicKey *_creatorPublicKey, const DataView &_groupId) : 
            nodeHash(_nodeHash),
            timestamp(_timestamp),
            creatorPublicKey(_creatorPublicKey),
            groupId(_groupId),
            loadedFromCache(false)
        {
            
        }
    };

    struct DatabaseAddNodeRequest
    {
        DISABLE_COPY(DatabaseAddNodeRequest)
        
        const Hash *nodeHash;
        const Hash *requestHash;
        u64 timestamp; // In microseconds
        const Signature::PublicKey *creatorPublicKey;
        const DataView decryptedData;
        bool loadedFromCache;
        
        DatabaseAddNodeRequest(const Hash *_nodeHash, const Hash *_requestHash, u64 _timestamp, const Signature::PublicKey *_creatorPublicKey, const DataView &_decryptedData) : 
            nodeHash(_nodeHash),
            requestHash(_requestHash),
            timestamp(_timestamp),
            creatorPublicKey(_creatorPublicKey),
            decryptedData(_decryptedData),
            loadedFromCache(false)
        {
            
        }
    };

    struct DatabaseAddUserRequest
    {
        DISABLE_COPY(DatabaseAddUserRequest)

        const Hash *nodeHash;
        const Hash *requestHash;
        u64 timestamp; // In microseconds
        const Signature::PublicKey *creatorPublicKey;
        const Signature::PublicKey *userToAddPublicKey;
        const DataView groupToAddUserTo;
        bool loadedFromCache;

        DatabaseAddUserRequest(const Hash *_nodeHash, const Hash *_requestHash, u64 _timestamp, const Signature::PublicKey *_creatorPublicKey, const Signature::PublicKey *_userToAddPublicKey, const DataView &_groupToAddUserTo) : 
            nodeHash(_nodeHash),
            requestHash(_requestHash),
            timestamp(_timestamp),
            creatorPublicKey(_creatorPublicKey),
            userToAddPublicKey(_userToAddPublicKey),
            groupToAddUserTo(_groupToAddUserTo),
            loadedFromCache(false)
        {

        }
    };
    
    class DatabaseCreateResponse
    {
    public:
        DatabaseCreateResponse(std::shared_ptr<Signature::KeyPair> nodeAdminKeyPair, std::shared_ptr<OwnedByteArray> nodeAdminGroupId, std::shared_ptr<OwnedByteArray> key, std::shared_ptr<Hash> hash);
        
        const std::shared_ptr<Signature::KeyPair> getNodeAdminKeyPair() const;
        const std::shared_ptr<OwnedByteArray> getNodeAdminGroupId() const;
        const std::shared_ptr<OwnedByteArray> getNodeEncryptionKey() const;
        const std::shared_ptr<Hash> getRequestHash() const;
    private:
        std::shared_ptr<Signature::KeyPair> nodeAdminKeyPair;
        std::shared_ptr<OwnedByteArray> nodeAdminGroupId;
        std::shared_ptr<OwnedByteArray> key;
        std::shared_ptr<Hash> hash;
    };
    
    struct DatabaseSeedInfo
    {
        std::shared_ptr<std::future<size_t>> newDataListenerFuture;
        std::shared_ptr<std::future<size_t>> responseKeyFuture;
        std::shared_ptr<std::future<size_t>> requestOldDataListenerFuture;
        
        std::shared_ptr<dht::InfoHash> reponseKeyInfoHash;
        
        DatabaseSeedInfo(){}
        DatabaseSeedInfo(const DatabaseSeedInfo &other)
        {
            newDataListenerFuture = other.newDataListenerFuture;
            responseKeyFuture = other.responseKeyFuture;
            requestOldDataListenerFuture = other.requestOldDataListenerFuture;
            reponseKeyInfoHash = other.reponseKeyInfoHash;
        }
        DatabaseSeedInfo& operator=(const DatabaseSeedInfo &other)
        {
            newDataListenerFuture = other.newDataListenerFuture;
            responseKeyFuture = other.responseKeyFuture;
            requestOldDataListenerFuture = other.requestOldDataListenerFuture;
            reponseKeyInfoHash = other.reponseKeyInfoHash;
            return *this;
        }
    };

    using CreateNodeCallbackFunc = std::function<void(const DatabaseCreateNodeRequest&)>;
    using AddNodeCallbackFunc = std::function<void(const DatabaseAddNodeRequest&)>;
    using AddUserCallbackFunc = std::function<void(const DatabaseAddUserRequest&)>;
    
    using ReceiveCustomMessageCallbackFunc = std::function<sibs::SafeSerializer(const void *data, usize size)>;
    using SendCustomMessageCallbackFunc = std::function<bool(bool gotResponse, const void *data, usize size)>;

    struct DatabaseCallbackFuncs
    {
        CreateNodeCallbackFunc createNodeCallbackFunc;
        AddNodeCallbackFunc addNodeCallbackFunc;
        AddUserCallbackFunc addUserCallbackFunc;
    };

    class Database
    {
        DISABLE_COPY(Database)
        friend class DatabaseStorage;
    public:
        Database(const char *bootstrapNodeAddr, u16 port, const boost::filesystem::path &storageDir, DatabaseCallbackFuncs callbackFuncs);
        ~Database();

        // Safe to call multiple times with same node hash, will be ignored if the node is already beeing seeded
        void seed(const DatabaseNode &nodeToSeed, DatabaseFetchOrder fetchOrder = DatabaseFetchOrder::OLDEST_FIRST);
        void stopSeeding(const Hash &nodeHash);
        void loadNode(const Hash &nodeHash, DatabaseLoadOrder loadOrder = DatabaseLoadOrder::OLDEST_FIRST);
        
        // Throws DatabaseCreateException on failure.
        std::unique_ptr<DatabaseCreateResponse> create();
        // Throws PermissionDeniedException if user @userToPerformActionWith is not allowed to add data to node
        void addData(const DatabaseNode &nodeInfo, const Signature::KeyPair &userToPerformActionWith, DataView dataToAdd);
        // Throws PermissionDeniedException if user @userToPerformActionWith is not allowed to add user @userToAdd to group @groupToAddUserTo
        void addUser(const DatabaseNode &nodeInfo, const Signature::KeyPair &userToPerformActionWith, const Signature::PublicKey &userToAddPublicKey, const DataView &groupToAddUserTo);
        
        static ntp::NtpTimestamp getSyncedTimestampUtc();
        
        bool doesStoredUserExist(const std::string &username) const;
        
        // Throws SqlExecException if user with same name already exists
        void storeUserWithoutNodes(const std::string &username, const std::string &password);
        
        // Username has to be either unique or if it's the same as existing one, then password has to match.
        // Node has to be unique for the user.
        // Throws DatabaseStorageWrongPassword or SqlExecException on failure (if username is not unique in node).
        void storeNodeInfoForUserEncrypted(const DatabaseNode &nodeInfo, const std::string &username, const std::string &password, const Signature::KeyPair &keyPair);
        
        // Returns nodes, node encryption key, public key and private key of encrypted user.
        // Throws DatabaseStorageWrongPassword if password for the stored user is wrong.
        MapHash<StoredNodeInfo> getStoredNodeUserInfoDecrypted(const std::string &username, const std::string &password) const;
        
        std::vector<OwnedByteArray> getUserGroups(const Hash &nodeHash, const Signature::PublicKey &userPublicKey) const;

        // Returns -1 on failure
        int getUserLowestPermissionLevel(const Hash &nodeHash, const Signature::PublicKey &userPublicKey) const;
        
        std::future<size_t> receiveCustomMessage(const dht::InfoHash &requestKey, ReceiveCustomMessageCallbackFunc callbackFunc);
        
        void sendCustomMessage(const dht::InfoHash &key, std::vector<u8> &&data);
        
        // Return true in @callbackFunc if you want to continue listening for responses, otherwise return false
        std::future<size_t> sendCustomMessage(const dht::InfoHash &key, std::vector<u8> &&data, SendCustomMessageCallbackFunc callbackFunc);
        
        void cancelNodeListener(const dht::InfoHash &infoHash, std::future<size_t> &nodeListener);
        
        int clearCache();
        
        static dht::InfoHash getInfoHash(const void *data, usize size);
    private:
        void sendOldDataToPeer(const DatabaseNode nodeToSeed, const std::shared_ptr<dht::InfoHash> requestResponseInfoHash, const std::shared_ptr<dht::Value> value, usize valueOffset);
        void deserializeCreateRequest(const std::shared_ptr<dht::Value> &value, const Hash &hash, const std::shared_ptr<OwnedByteArray> encryptionKey);
        void deserializeAddRequest(const std::shared_ptr<dht::Value> &value, const Hash &requestDataHash, const std::shared_ptr<Hash> &nodeHash, const std::shared_ptr<OwnedByteArray> encryptionKey);
        bool listenCreateData(std::shared_ptr<dht::Value> value, const Hash &hash, const std::shared_ptr<OwnedByteArray> encryptionKey);
        bool listenAddData(std::shared_ptr<dht::Value> value, const Hash &requestDataHash, const std::shared_ptr<Hash> nodeHash, const std::shared_ptr<OwnedByteArray> encryptionKey);
    private:
        dht::DhtRunner node;
        DatabaseStorage databaseStorage;
        std::function<void(const DatabaseCreateNodeRequest&)> onCreateNodeCallbackFunc;
        std::function<void(const DatabaseAddNodeRequest&)> onAddNodeCallbackFunc;
        std::function<void(const DatabaseAddUserRequest&)> onAddUserCallbackFunc;
        MapHash<DatabaseSeedInfo> seedInfoMap;
        std::thread remoteNodesSaveThread;
        bool shuttingDown;
    };
}