aboutsummaryrefslogtreecommitdiff
path: root/tests/main.cpp
blob: 104c9b8670c16b24fa93fdf0b7ec3ecb2a6d87a3 (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
#include "assert.hpp"
#include "../include/odhtdb/Log.hpp"
#include "../include/odhtdb/Database.hpp"
#include "../include/odhtdb/Group.hpp"
#include "../include/odhtdb/LocalUser.hpp"
#include "../include/odhtdb/Encryption.hpp"
#include "../include/odhtdb/Hash.hpp"
#include "../include/odhtdb/hex2bin.hpp"
#include "../include/odhtdb/bin2hex.hpp"
#include "../include/odhtdb/DataView.hpp"
#include <vector>
#include <chrono>
#include <thread>
#include <opendht.h>

using namespace std;
using namespace chrono_literals;
using namespace odhtdb;

void testBinHexConvert()
{
    DataView input { (void*)"hello", 5 };
    
    string inputHex = bin2hex((const char*)input.data, input.size);
    assertEquals<string>("68656c6c6f", inputHex);
    
    string inputBin = hex2bin(inputHex.c_str(), inputHex.size());
    if(inputBin.size() != input.size)
    {
        string errMsg = "Expected input converted to hex and then back to binary size to be 5, was: ";
        errMsg += to_string(inputBin.size());
        fail(errMsg);
    }
    
    if(memcmp(input.data, inputBin.data(), input.size) != 0)
    {
        string errMsg = "Expected input converted to hex and then back to binary to be same as original input ('hello'), was: ";
        errMsg += string(inputBin.c_str(), inputBin.size());
        fail(errMsg);
    }
}

void testHash()
{
    Hash hash("odhtdb", 6);
    string hashHex = hash.toString();
    assertEquals<string>("a7b30ec8ab92de60e551b26bb8f78d315697f84dd7f5549a143477e095ec934f", hashHex);
    Log::debug("hash of 'odhtdb' is: a7b30ec8ab92de60e551b26bb8f78d315697f84dd7f5549a143477e095ec934f");
}

void testSignData(LocalUser *localUser)
{
    std::string publicKeyStr = localUser->getPublicKey().toString();
    Log::debug("Local user public key: %s", publicKeyStr.c_str());
    
    std::string privateKeyStr = localUser->getPrivateKey().toString();
    Log::debug("Local user private key: %s", privateKeyStr.c_str());
    
    string expectedUnsignedData = "hello, world!";
    string signedData = localUser->getPrivateKey().sign(DataView((void*)expectedUnsignedData.data(), expectedUnsignedData.size()));
    assertEquals(SIGNED_HASH_SIZE + expectedUnsignedData.size(), signedData.size());
    
    string unsignedData = localUser->getPublicKey().unsign(DataView((void*)signedData.data(), signedData.size()));
    assertEquals(expectedUnsignedData, unsignedData);
    
    try
    {
        Signature::KeyPair anotherKeyPair;
        anotherKeyPair.getPublicKey().unsign(DataView((void*)signedData.data(), signedData.size()));
        fail("Expected unsign to fail since the data was not signed with the private key matching given public key");
    }
    catch (UnsignWrongKeyException &e)
    {
        
    }
    catch (exception &e)
    {
        string errMsg = "Expected unsign to fail with UnsignWrongKeyException, fail reason: ";
        errMsg += e.what();
        fail(errMsg);
    }
    
    try
    {
        Signature::KeyPair anotherKeyPair;
        anotherKeyPair.getPublicKey().unsign(DataView((void*)signedData.data(), 3));
        fail("Expected unsign to fail since the (signed) data is too small to have been signed (signed hash is 64 bytes)");
    }
    catch (UnsignInvalidSizeException &e)
    {
        
    }
    catch (exception &e)
    {
        string errMsg = "Expected unsign to fail with UnsignInvalidSizeException, fail reason: ";
        errMsg += e.what();
        fail(errMsg);
    }
}

void testEncryption()
{
    const char *message = "hello, world!";
    const unsigned long long messageLength = 13;
    Encryption encryption(DataView((void*)message, messageLength));
    
    Decryption decryption(encryption.getCipherText(), encryption.getNonce(), encryption.getKey());
    assertEquals<unsigned long long>(messageLength, decryption.getDecryptedText().size);
    assertEquals(0, strncmp(message, (const char*)decryption.getDecryptedText().data, messageLength));
}

void testCachedIdentity()
{
    pair<shared_ptr<dht::crypto::PrivateKey>, shared_ptr<dht::crypto::Certificate>> identity = dht::crypto::generateIdentity();
    dht::Blob privateKeyData = identity.first->serialize();
    printf("Private key size: %d, serialized data: %s\n", privateKeyData.size(), Hash(privateKeyData.data(), privateKeyData.size()).toString().c_str());
    
    dht::crypto::PrivateKey privateKeyDeserialized(privateKeyData);
    privateKeyData = identity.first->serialize();
    printf("Private key size: %d, serialized data: %s\n", privateKeyData.size(), Hash(privateKeyData.data(), privateKeyData.size()).toString().c_str());
    
    dht::Blob certificateData;
    identity.second->pack(certificateData);
    printf("Certificate data size: %d, serialized data: %s\n", certificateData.size(), Hash(certificateData.data(), certificateData.size()).toString().c_str());
    
    dht::crypto::Certificate certificateDeserialized(certificateData);
    certificateData.clear();
    identity.second->pack(certificateData);
    printf("Certificate data size: %d, serialized data: %s\n", certificateData.size(), Hash(certificateData.data(), certificateData.size()).toString().c_str());
}

void testTimestamp(const Database &database)
{
    auto timestamp1 = database.getSyncedTimestampUtc();
    this_thread::sleep_for(chrono::milliseconds(100));
    auto timestamp2 = database.getSyncedTimestampUtc();
    
    if(timestamp2.getCombined() > timestamp1.getCombined())
        Log::debug("Second timestamp is more than first one, as expected");
    else
        fail("Second timestamp is not more than first one for some reason");
}

int main()
{
    Log::debug("Starting tests...");
    testCachedIdentity();
    testBinHexConvert();
    testHash();
    testEncryption();
    
    LocalUser *localUser = LocalUser::create(Signature::KeyPair(), "dec05eba", nullptr);
    testSignData(localUser);
    
    // TODO: Setup local bootstrap node for tests
    Database database("bootstrap.ring.cx", 4222, "storage");
    
    testTimestamp(database);
    
    int createNodeCounter = 0;
    int addDataCounter = 0;
    int addUserCounter = 0;
    
    database.setOnCreateNodeCallback([&createNodeCounter](const DatabaseCreateNodeRequest &request)
    {
        Log::debug("Create node callback");
        ++createNodeCounter;
    });

    database.setOnAddNodeCallback([&addDataCounter](const DatabaseAddNodeRequest &request)
    {
        Log::debug("Add node callback");
        ++addDataCounter;
    });

    database.setOnAddUserCallback([&addUserCounter](const DatabaseAddUserRequest &request)
    {
        Log::debug("Add user callback");
        ++addUserCounter;
    });

    auto databaseCreateResponse = database.create("adminUserName", "latenight");
    DatabaseNode databaseNode(databaseCreateResponse->getNodeEncryptionKey(), databaseCreateResponse->getRequestHash());
    auto adminUser = (LocalUser*)databaseCreateResponse->getNodeAdminUser();
    database.addData(databaseNode, adminUser, DataView{ (void*)"hello, world!", 13 });
    database.addUser(databaseNode, adminUser, localUser->getName(), localUser->getPublicKey(), adminUser->getGroups()[0]);
    localUser->addToGroup(adminUser->getGroups()[0]);
    database.addData(databaseNode, localUser, DataView{ (void*)"hello, aaald!", 13 });
    database.commit();
    
    database.seed(databaseNode);
    auto start = chrono::high_resolution_clock::now();
    while(chrono::high_resolution_clock::now() - start < 3s)
    {
        this_thread::sleep_for(10ms);
    }
    
    assertEquals(1, createNodeCounter);
    assertEquals(2, addDataCounter);
    assertEquals(1, addUserCounter);
    
    return 0;
}