forked from okcashpro/okcash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmessage.cpp
3999 lines (3204 loc) · 112 KB
/
smessage.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
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014 The Okcash Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/*
Notes:
Running with -debug could leave to and from address hashes and public keys in the log.
parameters:
-nosmsg Disable secure messaging (fNoSmsg)
-debugsmsg Show extra debug messages (fDebugSmsg)
-smsgscanchain Scan the block chain for public key addresses on startup
Wallet Locked
A copy of each incoming message is stored in bucket files ending in _wl.dat
wl (wallet locked) bucket files are deleted if they expire, like normal buckets
When the wallet is unlocked all the messages in wl files are scanned.
Address Whitelist
Owned Addresses are stored in smsgAddresses vector
Saved to smsg.ini
Modify options using the smsglocalkeys rpc command or edit the smsg.ini file (with client closed)
*/
#include "smessage.h"
#include <stdint.h>
#include <time.h>
#include <map>
#include <stdexcept>
#include <sstream>
#include <errno.h>
#include <openssl/crypto.h>
#include <openssl/ec.h>
#include <openssl/ecdh.h>
#include <openssl/sha.h>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "base58.h"
#include "db.h"
#include "init.h" // pwalletMain
#include "txdb.h"
#include "sync.h"
#include "eckey.h"
#include "lz4/lz4.c"
#include "xxhash/xxhash.h"
#include "xxhash/xxhash.c"
boost::thread_group threadGroupSmsg;
// TODO: For buckets older than current, only need to store no. messages and hash in memory
boost::signals2::signal<void (SecMsgStored& inboxHdr)> NotifySecMsgInboxChanged;
boost::signals2::signal<void (SecMsgStored& outboxHdr)> NotifySecMsgOutboxChanged;
boost::signals2::signal<void ()> NotifySecMsgWalletUnlocked;
bool fSecMsgEnabled = false;
std::map<int64_t, SecMsgBucket> smsgBuckets;
std::vector<SecMsgAddress> smsgAddresses;
SecMsgOptions smsgOptions;
CCriticalSection cs_smsg;
CCriticalSection cs_smsgDB;
CCriticalSection cs_smsgThreads;
leveldb::DB *smsgDB = NULL;
namespace fs = boost::filesystem;
bool SecMsgCrypter::SetKey(const std::vector<uint8_t>& vchNewKey, uint8_t* chNewIV)
{
if (vchNewKey.size() < sizeof(chKey))
return false;
return SetKey(&vchNewKey[0], chNewIV);
};
bool SecMsgCrypter::SetKey(const uint8_t* chNewKey, uint8_t* chNewIV)
{
// -- for EVP_aes_256_cbc() key must be 256 bit, iv must be 128 bit.
memcpy(&chKey[0], chNewKey, sizeof(chKey));
memcpy(chIV, chNewIV, sizeof(chIV));
fKeySet = true;
return true;
};
bool SecMsgCrypter::Encrypt(uint8_t* chPlaintext, uint32_t nPlain, std::vector<uint8_t> &vchCiphertext)
{
if (!fKeySet)
return false;
// -- max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE - 1 bytes
int nLen = nPlain;
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<uint8_t> (nCLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, &chKey[0], &chIV[0]);
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, chPlaintext, nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk)
return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
};
bool SecMsgCrypter::Decrypt(uint8_t* chCiphertext, uint32_t nCipher, std::vector<uint8_t>& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nPLen = nCipher, nFLen = 0;
vchPlaintext.resize(nCipher);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, &chKey[0], &chIV[0]);
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &chCiphertext[0], nCipher);
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk)
return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
};
void SecMsgBucket::hashBucket()
{
if (fDebugSmsg)
LogPrintf("SecMsgBucket::hashBucket()\n");
timeChanged = GetTime();
std::set<SecMsgToken>::iterator it;
void* state = XXH32_init(1);
for (it = setTokens.begin(); it != setTokens.end(); ++it)
{
XXH32_update(state, it->sample, 8);
};
hash = XXH32_digest(state);
if (fDebugSmsg)
LogPrintf("Hashed %u messages, hash %u\n", setTokens.size(), hash);
};
bool SecMsgDB::Open(const char* pszMode)
{
if (smsgDB)
{
pdb = smsgDB;
return true;
};
bool fCreate = strchr(pszMode, 'c');
fs::path fullpath = GetDataDir() / "smsgDB";
if (!fCreate
&& (!fs::exists(fullpath)
|| !fs::is_directory(fullpath)))
{
LogPrintf("SecMsgDB::open() - DB does not exist.\n");
return false;
};
leveldb::Options options;
options.create_if_missing = fCreate;
leveldb::Status s = leveldb::DB::Open(options, fullpath.string(), &smsgDB);
if (!s.ok())
{
LogPrintf("SecMsgDB::open() - Error opening db: %s.\n", s.ToString().c_str());
return false;
};
pdb = smsgDB;
return true;
};
class SecMsgBatchScanner : public leveldb::WriteBatch::Handler
{
public:
std::string needle;
bool* deleted;
std::string* foundValue;
bool foundEntry;
SecMsgBatchScanner() : foundEntry(false) {}
virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value)
{
if (key.ToString() == needle)
{
foundEntry = true;
*deleted = false;
*foundValue = value.ToString();
};
};
virtual void Delete(const leveldb::Slice& key)
{
if (key.ToString() == needle)
{
foundEntry = true;
*deleted = true;
};
};
};
// When performing a read, if we have an active batch we need to check it first
// before reading from the database, as the rest of the code assumes that once
// a database transaction begins reads are consistent with it. It would be good
// to change that assumption in future and avoid the performance hit, though in
// practice it does not appear to be large.
bool SecMsgDB::ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const
{
if (!activeBatch)
return false;
*deleted = false;
SecMsgBatchScanner scanner;
scanner.needle = key.str();
scanner.deleted = deleted;
scanner.foundValue = value;
leveldb::Status s = activeBatch->Iterate(&scanner);
if (!s.ok())
{
LogPrintf("SecMsgDB ScanBatch error: %s\n", s.ToString().c_str());
return false;
};
return scanner.foundEntry;
}
bool SecMsgDB::TxnBegin()
{
if (activeBatch)
return true;
activeBatch = new leveldb::WriteBatch();
return true;
};
bool SecMsgDB::TxnCommit()
{
if (!activeBatch)
return false;
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status status = pdb->Write(writeOptions, activeBatch);
delete activeBatch;
activeBatch = NULL;
if (!status.ok())
{
LogPrintf("SecMsgDB batch commit failure: %s\n", status.ToString().c_str());
return false;
};
return true;
};
bool SecMsgDB::TxnAbort()
{
delete activeBatch;
activeBatch = NULL;
return true;
};
bool SecMsgDB::ReadPK(CKeyID& addr, CPubKey& pubkey)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(sizeof(addr) + 2);
ssKey << 'p';
ssKey << 'k';
ssKey << addr;
std::string strValue;
bool readFromDb = true;
if (activeBatch)
{
// -- check activeBatch first
bool deleted = false;
readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;
if (deleted)
return false;
};
if (readFromDb)
{
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);
if (!s.ok())
{
if (s.IsNotFound())
return false;
LogPrintf("LevelDB read failure: %s\n", s.ToString().c_str());
return false;
};
};
try {
CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
ssValue >> pubkey;
} catch (std::exception& e) {
LogPrintf("SecMsgDB::ReadPK() unserialize threw: %s.\n", e.what());
return false;
}
return true;
};
bool SecMsgDB::WritePK(CKeyID& addr, CPubKey& pubkey)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(sizeof(addr) + 2);
ssKey << 'p';
ssKey << 'k';
ssKey << addr;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(sizeof(pubkey));
ssValue << pubkey;
if (activeBatch)
{
activeBatch->Put(ssKey.str(), ssValue.str());
return true;
};
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());
if (!s.ok())
{
LogPrintf("SecMsgDB write failure: %s\n", s.ToString().c_str());
return false;
};
return true;
};
bool SecMsgDB::ExistsPK(CKeyID& addr)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(sizeof(addr)+2);
ssKey << 'p';
ssKey << 'k';
ssKey << addr;
std::string unused;
if (activeBatch)
{
bool deleted;
if (ScanBatch(ssKey, &unused, &deleted) && !deleted)
{
return true;
};
};
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);
return s.IsNotFound() == false;
};
bool SecMsgDB::NextSmesg(leveldb::Iterator* it, std::string& prefix, uint8_t* chKey, SecMsgStored& smsgStored)
{
if (!pdb)
return false;
if (!it->Valid()) // first run
it->Seek(prefix);
else
it->Next();
if (!(it->Valid()
&& it->key().size() == 18
&& memcmp(it->key().data(), prefix.data(), 2) == 0))
return false;
memcpy(chKey, it->key().data(), 18);
try {
CDataStream ssValue(it->value().data(), it->value().data() + it->value().size(), SER_DISK, CLIENT_VERSION);
ssValue >> smsgStored;
} catch (std::exception& e) {
LogPrintf("SecMsgDB::NextSmesg() unserialize threw: %s.\n", e.what());
return false;
}
return true;
};
bool SecMsgDB::NextSmesgKey(leveldb::Iterator* it, std::string& prefix, uint8_t* chKey)
{
if (!pdb)
return false;
if (!it->Valid()) // first run
it->Seek(prefix);
else
it->Next();
if (!(it->Valid()
&& it->key().size() == 18
&& memcmp(it->key().data(), prefix.data(), 2) == 0))
return false;
memcpy(chKey, it->key().data(), 18);
return true;
};
bool SecMsgDB::ReadSmesg(uint8_t* chKey, SecMsgStored& smsgStored)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
std::string strValue;
bool readFromDb = true;
if (activeBatch)
{
// -- check activeBatch first
bool deleted = false;
readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;
if (deleted)
return false;
};
if (readFromDb)
{
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue);
if (!s.ok())
{
if (s.IsNotFound())
return false;
LogPrintf("LevelDB read failure: %s\n", s.ToString().c_str());
return false;
};
};
try {
CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
ssValue >> smsgStored;
} catch (std::exception& e) {
LogPrintf("SecMsgDB::ReadSmesg() unserialize threw: %s.\n", e.what());
return false;
}
return true;
};
bool SecMsgDB::WriteSmesg(uint8_t* chKey, SecMsgStored& smsgStored)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue << smsgStored;
if (activeBatch)
{
activeBatch->Put(ssKey.str(), ssValue.str());
return true;
};
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str());
if (!s.ok())
{
LogPrintf("SecMsgDB write failed: %s\n", s.ToString().c_str());
return false;
};
return true;
};
bool SecMsgDB::ExistsSmesg(uint8_t* chKey)
{
if (!pdb)
return false;
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
std::string unused;
if (activeBatch)
{
bool deleted;
if (ScanBatch(ssKey, &unused, &deleted) && !deleted)
{
return true;
};
};
leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);
return s.IsNotFound() == false;
return true;
};
bool SecMsgDB::EraseSmesg(uint8_t* chKey)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write((const char*)chKey, 18);
if (activeBatch)
{
activeBatch->Delete(ssKey.str());
return true;
};
leveldb::WriteOptions writeOptions;
writeOptions.sync = true;
leveldb::Status s = pdb->Delete(writeOptions, ssKey.str());
if (s.ok() || s.IsNotFound())
return true;
LogPrintf("SecMsgDB erase failed: %s\n", s.ToString().c_str());
return false;
};
void ThreadSecureMsg()
{
// -- bucket management thread
std::vector<std::pair<int64_t, NodeId> > vTimedOutLocks;
while (fSecMsgEnabled)
{
int64_t now = GetTime();
if (fDebugSmsg)
LogPrintf("SecureMsgThread %d \n", now);
vTimedOutLocks.resize(0);
int64_t cutoffTime = now - SMSG_RETENTION;
{
LOCK(cs_smsg);
for (std::map<int64_t, SecMsgBucket>::iterator it(smsgBuckets.begin()); it != smsgBuckets.end(); it++)
{
//if (fDebugSmsg)
// LogPrintf("Checking bucket %d", size %u \n", it->first, it->second.setTokens.size());
if (it->first < cutoffTime)
{
if (fDebugSmsg)
LogPrintf("Removing bucket %d \n", it->first);
std::string fileName = boost::lexical_cast<std::string>(it->first);
fs::path fullPath = GetDataDir() / "smsgStore" / (fileName + "_01.dat");
if (fs::exists(fullPath))
{
try { fs::remove(fullPath);
} catch (const fs::filesystem_error& ex)
{
LogPrintf("Error removing bucket file %s.\n", ex.what());
};
} else
{
LogPrintf("Path %s does not exist \n", fullPath.string().c_str());
};
// -- look for a wl file, it stores incoming messages when wallet is locked
fullPath = GetDataDir() / "smsgStore" / (fileName + "_01_wl.dat");
if (fs::exists(fullPath))
{
try { fs::remove(fullPath);
} catch (const fs::filesystem_error& ex)
{
LogPrintf("Error removing wallet locked file %s.\n", ex.what());
};
};
smsgBuckets.erase(it);
} else
if (it->second.nLockCount > 0) // -- tick down nLockCount, so will eventually expire if peer never sends data
{
it->second.nLockCount--;
if (it->second.nLockCount == 0) // lock timed out
{
vTimedOutLocks.push_back(std::make_pair(it->first, it->second.nLockPeerId)); // cs_vNodes
it->second.nLockPeerId = 0;
}; // if (it->second.nLockCount == 0)
}; // ! if (it->first < cutoffTime)
};
} // cs_smsg
for (std::vector<std::pair<int64_t, NodeId> >::iterator it(vTimedOutLocks.begin()); it != vTimedOutLocks.end(); it++)
{
NodeId nPeerId = it->second;
int64_t ignoreUntil = GetTime() + SMSG_TIME_IGNORE;
if (fDebugSmsg)
LogPrintf("Lock on bucket %d for peer %d timed out.\n", it->first, nPeerId);
// -- look through the nodes for the peer that locked this bucket
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->id != nPeerId)
continue;
LOCK2(pnode->cs_vSend, pnode->smsgData.cs_smsg_net);
pnode->smsgData.ignoreUntil = ignoreUntil;
// -- alert peer that they are being ignored
std::vector<uint8_t> vchData;
vchData.resize(8);
memcpy(&vchData[0], &ignoreUntil, 8);
pnode->PushMessage("smsgIgnore", vchData);
if (fDebugSmsg)
LogPrintf("This node will ignore peer %d until %d.\n", nPeerId, ignoreUntil);
break;
};
} // cs_vNodes
};
MilliSleep(SMSG_THREAD_DELAY * 1000); // // check every SMSG_THREAD_DELAY seconds
};
};
void ThreadSecureMsgPow()
{
// -- proof of work thread
int rv;
std::vector<uint8_t> vchKey;
SecMsgStored smsgStored;
std::string sPrefix("qm");
uint8_t chKey[18];
while (fSecMsgEnabled)
{
// -- sleep at end, then fSecMsgEnabled is tested on wake
SecMsgDB dbOutbox;
leveldb::Iterator* it;
{
LOCK(cs_smsgDB);
if (!dbOutbox.Open("cr+"))
continue;
// -- fifo (smallest key first)
it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());
}
// -- break up lock, SecureMsgSetHash will take long
for (;;)
{
{
LOCK(cs_smsgDB);
if (!dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored))
break;
}
uint8_t* pHeader = &smsgStored.vchMessage[0];
uint8_t* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN];
SecureMessage* psmsg = (SecureMessage*) pHeader;
// -- do proof of work
rv = SecureMsgSetHash(pHeader, pPayload, psmsg->nPayload);
if (rv == 2)
break; // leave message in db, if terminated due to shutdown
// -- message is removed here, no matter what
{
LOCK(cs_smsgDB);
dbOutbox.EraseSmesg(chKey);
}
if (rv != 0)
{
LogPrintf("SecMsgPow: Could not get proof of work hash, message removed.\n");
continue;
};
// -- add to message store
{
LOCK(cs_smsg);
if (SecureMsgStore(pHeader, pPayload, psmsg->nPayload, true) != 0)
{
LogPrintf("SecMsgPow: Could not place message in buckets, message removed.\n");
continue;
};
}
// -- test if message was sent to self
if (SecureMsgScanMessage(pHeader, pPayload, psmsg->nPayload, true) != 0)
{
// message recipient is not this node (or failed)
};
};
{
LOCK(cs_smsg);
delete it;
}
// -- shutdown thread waits 5 seconds, this should be less
MilliSleep(2000); // seconds
};
};
int SecureMsgBuildBucketSet()
{
/*
Build the bucket set by scanning the files in the smsgStore dir.
smsgBuckets should be empty
*/
if (fDebugSmsg)
LogPrintf("SecureMsgBuildBucketSet()\n");
int64_t now = GetTime();
uint32_t nFiles = 0;
uint32_t nMessages = 0;
fs::path pathSmsgDir = GetDataDir() / "smsgStore";
fs::directory_iterator itend;
if (!fs::exists(pathSmsgDir)
|| !fs::is_directory(pathSmsgDir))
{
LogPrintf("Message store directory does not exist.\n");
return 0; // not an error
}
for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd)
{
if (!fs::is_regular_file(itd->status()))
continue;
std::string fileType = (*itd).path().extension().string();
if (fileType.compare(".dat") != 0)
continue;
std::string fileName = (*itd).path().filename().string();
if (fDebugSmsg)
LogPrintf("Processing file: %s.\n", fileName.c_str());
nFiles++;
// TODO files must be split if > 2GB
// time_noFile.dat
size_t sep = fileName.find_first_of("_");
if (sep == std::string::npos)
continue;
std::string stime = fileName.substr(0, sep);
int64_t fileTime = boost::lexical_cast<int64_t>(stime);
if (fileTime < now - SMSG_RETENTION)
{
LogPrintf("Dropping file %s, expired.\n", fileName.c_str());
try {
fs::remove((*itd).path());
} catch (const fs::filesystem_error& ex)
{
LogPrintf("Error removing bucket file %s, %s.\n", fileName.c_str(), ex.what());
};
continue;
};
if (boost::algorithm::ends_with(fileName, "_wl.dat"))
{
if (fDebugSmsg)
LogPrintf("Skipping wallet locked file: %s.\n", fileName.c_str());
continue;
};
size_t nTokenSetSize = 0;
SecureMessage smsg;
{
LOCK(cs_smsg);
std::set<SecMsgToken>& tokenSet = smsgBuckets[fileTime].setTokens;
FILE *fp;
if (!(fp = fopen((*itd).path().string().c_str(), "rb")))
{
LogPrintf("Error opening file: %s\n", strerror(errno));
continue;
};
for (;;)
{
long int ofs = ftell(fp);
SecMsgToken token;
token.offset = ofs;
errno = 0;
if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN)
{
if (errno != 0)
{
LogPrintf("fread header failed: %s\n", strerror(errno));
} else
{
//LogPrintf("End of file.\n");
};
break;
};
token.timestamp = smsg.timestamp;
if (smsg.nPayload < 8)
continue;
if (fread(token.sample, sizeof(uint8_t), 8, fp) != 8)
{
LogPrintf("fread data failed: %s\n", strerror(errno));
break;
};
if (fseek(fp, smsg.nPayload-8, SEEK_CUR) != 0)
{
LogPrintf("fseek, strerror: %s.\n", strerror(errno));
break;
};
tokenSet.insert(token);
};
fclose(fp);
smsgBuckets[fileTime].hashBucket();
nTokenSetSize = tokenSet.size();
} // LOCK(cs_smsg);
nMessages += nTokenSetSize;
if (fDebugSmsg)
LogPrintf("Bucket %d contains %u messages.\n", fileTime, nTokenSetSize);
};
LogPrintf("Processed %u files, loaded %u buckets containing %u messages.\n", nFiles, smsgBuckets.size(), nMessages);
return 0;
};
int SecureMsgAddWalletAddresses()
{
if (fDebugSmsg)
LogPrintf("SecureMsgAddWalletAddresses()\n");
std::string sAnonPrefix("ao ");
uint32_t nAdded = 0;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook)
{
if (!IsMine(*pwalletMain, entry.first))
continue;
// -- skip addresses for anon outputs
if (entry.second.compare(0, sAnonPrefix.length(), sAnonPrefix) == 0)
continue;
// TODO: skip addresses for stealth transactions
CBitcoinAddress coinAddress(entry.first);
if (!coinAddress.IsValid())
continue;
std::string address;
std::string strPublicKey;
address = coinAddress.ToString();
bool fExists = 0;
for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
if (address != it->sAddress)
continue;
fExists = 1;
break;
};
if (fExists)
continue;
bool recvEnabled = 1;
bool recvAnon = 1;
smsgAddresses.push_back(SecMsgAddress(address, recvEnabled, recvAnon));
nAdded++;
};
if (fDebugSmsg)
LogPrintf("Added %u addresses to whitelist.\n", nAdded);
return 0;
};
int SecureMsgReadIni()
{
if (!fSecMsgEnabled)
return false;
if (fDebugSmsg)
LogPrintf("SecureMsgReadIni()\n");
fs::path fullpath = GetDataDir() / "smsg.ini";
FILE *fp;
errno = 0;
if (!(fp = fopen(fullpath.string().c_str(), "r")))
{
LogPrintf("Error opening file: %s\n", strerror(errno));
return 1;
};
char cLine[512];
char *pName, *pValue;
char cAddress[64];
int addrRecv, addrRecvAnon;
while (fgets(cLine, 512, fp))
{
cLine[strcspn(cLine, "\n")] = '\0';
cLine[strcspn(cLine, "\r")] = '\0';
cLine[511] = '\0'; // for safety
// -- check that line contains a name value pair and is not a comment, or section header
if (cLine[0] == '#' || cLine[0] == '[' || strcspn(cLine, "=") < 1)
continue;
if (!(pName = strtok(cLine, "="))
|| !(pValue = strtok(NULL, "=")))
continue;