forked from m21/mastercore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmastercore.cpp
4470 lines (3736 loc) · 161 KB
/
mastercore.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
//
// first & so far only Master protocol source file
// WARNING: Work In Progress -- major refactoring will be occurring often
//
// I am adding comments to aid with navigation and overall understanding of the design.
// this is the 'core' portion of the node+wallet: mastercored
// see 'qt' subdirectory for UI files
//
// remaining work, search for: TODO, FIXME
//
//
// global TODO: need locks on the maps in this file & balances (moneys[],reserved[] & raccept[]) !!!
//
#include "mastercore.h"
#include "mastercore_convert.h"
#include "mastercore_dex.h"
#include "mastercore_errors.h"
#include "mastercore_script.h"
#include "mastercore_sp.h"
#include "mastercore_tx.h"
#include "mastercore_version.h"
#include "omnicore_encoding.h"
#include "omnicore_utils.h"
#include "base58.h"
#include "chainparams.h"
#include "coincontrol.h"
#include "init.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/standard.h"
#include "sync.h"
#include "tinyformat.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include "wallet.h"
#include <boost/algorithm/string.hpp>
#include <boost/exception/to_string.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/thread/mutex.hpp>
#include <openssl/sha.h>
#include "json/json_spirit_value.h"
#include "json/json_spirit_writer_template.h"
#include "leveldb/db.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <fstream>
#include <map>
#include <set>
#include <string>
#include <vector>
using boost::algorithm::token_compress_on;
using boost::multiprecision::cpp_int;
using boost::multiprecision::int128_t;
using boost::to_string;
using json_spirit::Array;
using json_spirit::Pair;
using json_spirit::Object;
using json_spirit::write_string;
using leveldb::Iterator;
using leveldb::Slice;
using leveldb::Status;
using std::make_pair;
using std::map;
using std::ofstream;
using std::string;
using std::vector;
using namespace mastercore;
// comment out MY_HACK & others here - used for Unit Testing only !
// #define MY_HACK
string exodus_address = "1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P";
static const string exodus_testnet = "mpexoDuSkGGqvqrkrjiFng38QPkJQVFyqv";
static const string getmoney_testnet = "moneyqMan7uh8FqdCA2BV5yZ8qVrc9ikLP";
// part of 'breakout' feature
static const int nBlockTop = 0;
// static const int nBlockTop = 271000;
static int nWaterlineBlock = 0; //
uint64_t global_metadex_market;
uint64_t global_balance_money_maineco[100000];
uint64_t global_balance_reserved_maineco[100000];
uint64_t global_balance_money_testeco[100000];
uint64_t global_balance_reserved_testeco[100000];
string global_alert_message;
static uint64_t exodus_prev = 0;
static uint64_t exodus_balance;
static boost::filesystem::path MPPersistencePath;
const int msc_debug_parser_data = 0;
const int msc_debug_parser= 0;
const int msc_debug_verbose=0;
const int msc_debug_verbose2=0;
const int msc_debug_verbose3=0;
const int msc_debug_vin = 0;
const int msc_debug_script= 0;
const int msc_debug_dex = 1;
const int msc_debug_send = 1;
const int msc_debug_tokens= 0;
const int msc_debug_spec = 1;
const int msc_debug_exo = 0;
const int msc_debug_tally = 1;
const int msc_debug_sp = 1;
const int msc_debug_sto = 1;
const int msc_debug_txdb = 0;
const int msc_debug_tradedb = 1;
const int msc_debug_persistence = 0;
// disable all flags for metadex for the immediate tag, then turn back on 0 & 2 at least
int msc_debug_metadex1= 0;
int msc_debug_metadex2= 0;
int msc_debug_metadex3= 0; // enable this to see the orderbook before & after each TX
const static int disable_Divs = 0;
const static int disableLevelDB = 0;
static int mastercoreInitialized = 0;
static int reorgRecoveryMode = 0;
static int reorgRecoveryMaxHeight = 0;
static bool bRawTX = false;
// TODO: there would be a block height for each TX version -- rework together with BLOCKHEIGHTRESTRICTIONS above
static const int txRestrictionsRules[][3] = {
{MSC_TYPE_SIMPLE_SEND, GENESIS_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_TRADE_OFFER, MSC_DEX_BLOCK, MP_TX_PKT_V1},
{MSC_TYPE_ACCEPT_OFFER_BTC, MSC_DEX_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_CREATE_PROPERTY_FIXED, MSC_SP_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_CREATE_PROPERTY_VARIABLE, MSC_SP_BLOCK, MP_TX_PKT_V1},
{MSC_TYPE_CLOSE_CROWDSALE, MSC_SP_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_SEND_TO_OWNERS, MSC_STO_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_METADEX, MSC_METADEX_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_OFFER_ACCEPT_A_BET, MSC_BET_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_CREATE_PROPERTY_MANUAL, MSC_MANUALSP_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_GRANT_PROPERTY_TOKENS, MSC_MANUALSP_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_REVOKE_PROPERTY_TOKENS, MSC_MANUALSP_BLOCK, MP_TX_PKT_V0},
{MSC_TYPE_CHANGE_ISSUER_ADDRESS, MSC_MANUALSP_BLOCK, MP_TX_PKT_V0},
// end of array marker, in addition to sizeof/sizeof
{-1,-1},
};
CMPTxList *mastercore::p_txlistdb;
CMPTradeList *mastercore::t_tradelistdb;
CMPSTOList *mastercore::s_stolistdb;
// a copy from main.cpp -- unfortunately that one is in a private namespace
int mastercore::GetHeight()
{
if (0 < nBlockTop) return nBlockTop;
LOCK(cs_main);
return chainActive.Height();
}
uint32_t mastercore::GetLatestBlockTime()
{
LOCK(cs_main);
if (chainActive.Tip())
return (int)(chainActive.Tip()->GetBlockTime());
else
return (int)(Params().GenesisBlock().nTime); // Genesis block's time of current network
}
//--- CUT HERE --- mostly copied from util.h & util.cpp
// LogPrintf() has been broken a couple of times now
// by well-meaning people adding mutexes in the most straightforward way.
// It breaks because it may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// defining a mutex as a global object doesn't work (the mutex gets
// destroyed, and then some later destructor calls OutputDebugStringF,
// maybe indirectly, and you get a core dump at shutdown trying to lock
// the mutex).
static boost::once_flag mp_debugPrintInitFlag = BOOST_ONCE_INIT;
// We use boost::call_once() to make sure these are initialized in
// in a thread-safe manner the first time it is called:
static FILE* fileout = NULL;
static boost::mutex* mutexDebugLog = NULL;
static void mp_DebugPrintInit()
{
assert(fileout == NULL);
assert(mutexDebugLog == NULL);
boost::filesystem::path pathDebug = GetDataDir() / LOG_FILENAME ;
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
mutexDebugLog = new boost::mutex();
}
int mp_LogPrintStr(const std::string &str)
{
int ret = 0; // Returns total number of characters written
if (fPrintToConsole)
{
// print to console
ret = fwrite(str.data(), 1, str.size(), stdout);
}
else if (fPrintToDebugLog)
{
static bool fStartedNewLine = true;
boost::call_once(&mp_DebugPrintInit, mp_debugPrintInitFlag);
if (fileout == NULL)
return ret;
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / LOG_FILENAME ;
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
if (!str.empty() && str[str.size()-1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
ret = fwrite(str.data(), 1, str.size(), fileout);
}
return ret;
}
// indicate whether persistence is enabled at this point, or not
// used to write/read files, for breakout mode, debugging, etc.
static bool readPersistence()
{
#ifdef MY_HACK
return false;
#else
return true;
#endif
}
// indicate whether persistence is enabled at this point, or not
// used to write/read files, for breakout mode, debugging, etc.
static bool writePersistence(int block_now)
{
// if too far away from the top -- do not write
if (GetHeight() > (block_now + MAX_STATE_HISTORY)) return false;
return true;
}
// copied from ShrinkDebugFile, util.cpp
static void shrinkDebugFile()
{
// Scroll log if it's getting too big
const int buffer_size = 8000000; // 8MBytes
boost::filesystem::path pathLog = GetDataDir() / LOG_FILENAME;
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 50000000) // 50MBytes
{
// Restart the file with some of the end
char *pch = new char[buffer_size];
if (NULL != pch)
{
fseek(file, -buffer_size, SEEK_END);
int nBytes = fread(pch, 1, buffer_size, file);
fclose(file); file = NULL;
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file); file = NULL;
}
delete [] pch;
}
}
else
{
if (NULL != file) fclose(file);
}
}
string mastercore::strMPProperty(unsigned int i)
{
string str = "*unknown*";
// test user-token
if (0x80000000 & i)
{
str = strprintf("Test token: %d : 0x%08X", 0x7FFFFFFF & i, i);
}
else
switch (i)
{
case OMNI_PROPERTY_BTC: str = "BTC"; break;
case OMNI_PROPERTY_MSC: str = "MSC"; break;
case OMNI_PROPERTY_TMSC: str = "TMSC"; break;
default: str = strprintf("SP token: %d", i);
}
return str;
}
inline bool isNonMainNet()
{
return Params().NetworkIDString() != "main";
}
inline bool TestNet()
{
return Params().NetworkIDString() == "test";
}
inline bool RegTest()
{
return Params().NetworkIDString() == "regtest";
}
string FormatPriceMP(double n)
{
string str = strprintf("%lf", n);
// clean up trailing zeros - good for RPC not so much for UI
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );
if (str.length() > 0) { std::string::iterator it = str.end() - 1; if (*it == '.') { str.erase(it); } } //get rid of trailing dot if non decimal
return str;
}
string FormatDivisibleShortMP(int64_t n)
{
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%d.%08d", quotient, remainder);
// clean up trailing zeros - good for RPC not so much for UI
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );
if (str.length() > 0) { std::string::iterator it = str.end() - 1; if (*it == '.') { str.erase(it); } } //get rid of trailing dot if non decimal
return str;
}
// mostly taken from Bitcoin's FormatMoney()
string FormatDivisibleMP(int64_t n, bool fSign)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%d.%08d", quotient, remainder);
if (!fSign) return str;
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else
str.insert((unsigned int)0, 1, '+');
return str;
}
std::string mastercore::FormatIndivisibleMP(int64_t n)
{
string str = strprintf("%ld", n);
return str;
}
std::string FormatMP(unsigned int property, int64_t n, bool fSign)
{
if (isPropertyDivisible(property)) return FormatDivisibleMP(n, fSign);
else return FormatIndivisibleMP(n);
}
string const CMPSPInfo::watermarkKey("watermark");
CCriticalSection cs_tally;
OfferMap mastercore::my_offers;
AcceptMap mastercore::my_accepts;
CMPSPInfo *mastercore::_my_sps;
CrowdMap mastercore::my_crowds;
PendingMap mastercore::my_pending;
static CMPPending *pendingDelete(const uint256 txid, bool bErase = false)
{
if (msc_debug_verbose3) file_log("%s(%s)\n", __FUNCTION__, txid.GetHex().c_str());
PendingMap::iterator it = my_pending.find(txid);
if (it != my_pending.end())
{
// display
CMPPending *p_pending = &(it->second);
int64_t src_amount = getMPbalance(p_pending->src, p_pending->prop, PENDING);
if (msc_debug_verbose3) file_log("%s()src= %ld, line %d, file: %s\n", __FUNCTION__, src_amount, __LINE__, __FILE__);
if (src_amount)
{
update_tally_map(p_pending->src, p_pending->prop, p_pending->amount, PENDING);
}
if (bErase)
{
my_pending.erase(it);
}
else
{
return &(it->second);
}
}
return (CMPPending *) NULL;
}
static int pendingAdd(const uint256 &txid, const string &FromAddress, unsigned int propId, int64_t Amount, int64_t type, const string &txDesc)
{
CMPPending pending;
if (msc_debug_verbose3) file_log("%s(%s,%s,%u,%ld,%d, %s), line %d, file: %s\n", __FUNCTION__, txid.GetHex().c_str(), FromAddress.c_str(), propId, Amount, type, txDesc,__LINE__, __FILE__);
// support for pending, 0-confirm
if (update_tally_map(FromAddress, propId, -Amount, PENDING))
{
pending.src = FromAddress;
pending.amount = Amount;
pending.prop = propId;
pending.desc = txDesc;
pending.type = type;
my_pending.insert(std::make_pair(txid, pending));
}
return 0;
}
// this is the master list of all amounts for all addresses for all properties, map is sorted by Bitcoin address
std::map<string, CMPTally> mastercore::mp_tally_map;
CMPTally *mastercore::getTally(const string & address)
{
LOCK (cs_tally);
map<string, CMPTally>::iterator it = mp_tally_map.find(address);
if (it != mp_tally_map.end()) return &(it->second);
return (CMPTally *) NULL;
}
// look at balance for an address
int64_t getMPbalance(const string &Address, unsigned int property, TallyType ttype)
{
uint64_t balance = 0;
if (TALLY_TYPE_COUNT <= ttype) return 0;
LOCK(cs_tally);
const map<string, CMPTally>::iterator my_it = mp_tally_map.find(Address);
if (my_it != mp_tally_map.end())
{
balance = (my_it->second).getMoney(property, ttype);
}
return balance;
}
int64_t getUserAvailableMPbalance(const string &Address, unsigned int property)
{
int64_t money = getMPbalance(Address, property, BALANCE);
int64_t pending = getMPbalance(Address, property, PENDING);
if (0 > pending)
{
return (money + pending); // show the decrease in money available
}
return money;
}
static bool isRangeOK(const uint64_t input)
{
if (MAX_INT_8_BYTES < input) return false;
return true;
}
// returns false if we are out of range and/or overflow
// call just before multiplying large numbers
bool isMultiplicationOK(const uint64_t a, const uint64_t b)
{
// printf("%s(%lu, %lu): ", __FUNCTION__, a, b);
if (!a || !b) return true;
if (MAX_INT_8_BYTES < a) return false;
if (MAX_INT_8_BYTES < b) return false;
const uint64_t result = a*b;
if (MAX_INT_8_BYTES < result) return false;
if ((0 != a) && (result / a != b)) return false;
return true;
}
bool mastercore::isTestEcosystemProperty(unsigned int property)
{
if ((OMNI_PROPERTY_TMSC == property) || (TEST_ECO_PROPERTY_1 <= property)) return true;
return false;
}
bool mastercore::isMainEcosystemProperty(unsigned int property)
{
if ((OMNI_PROPERTY_BTC != property) && !isTestEcosystemProperty(property)) return true;
return false;
}
bool mastercore::isMetaDExOfferActive(const uint256 txid, unsigned int propertyId)
{
for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it)
{
if (my_it->first == propertyId) //at bear minimum only go deeper if it's the right property id
{
md_PricesMap & prices = my_it->second;
for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it)
{
md_Set & indexes = (it->second);
for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it)
{
CMPMetaDEx obj = *it;
if( obj.getHash().GetHex() == txid.GetHex() ) return true;
}
}
}
}
return false;
}
std::string mastercore::getMasterCoreAlertString()
{
return global_alert_message;
}
std::string mastercore::getTokenLabel(unsigned int propertyId)
{
std::string tokenStr;
if (propertyId < 3) {
if(propertyId == 1) { tokenStr = " MSC"; } else { tokenStr = " TMSC"; }
} else {
tokenStr = " SPT#" + to_string(propertyId);
}
return tokenStr;
}
bool mastercore::parseAlertMessage(std::string rawAlertStr, int32_t *alertType, uint64_t *expiryValue, uint32_t *typeCheck, uint32_t *verCheck, std::string *alertMessage)
{
std::vector<std::string> vstr;
boost::split(vstr, rawAlertStr, boost::is_any_of(":"), token_compress_on);
if (5 == vstr.size())
{
try {
*alertType = boost::lexical_cast<int32_t>(vstr[0]);
*expiryValue = boost::lexical_cast<uint64_t>(vstr[1]);
*typeCheck = boost::lexical_cast<uint32_t>(vstr[2]);
*verCheck = boost::lexical_cast<uint32_t>(vstr[3]);
} catch (const boost::bad_lexical_cast &e) {
file_log("DEBUG ALERT - error in converting values from global alert string\n");
return false; //(something went wrong)
}
*alertMessage = vstr[4];
if ((*alertType < 1) || (*alertType > 4) || (*expiryValue == 0)) {
file_log("DEBUG ALERT ERROR - Something went wrong decoding the global alert string, values are not as expected.\n");
return false;
}
return true;
}
return false;
}
std::string mastercore::getMasterCoreAlertTextOnly()
{
std::vector<std::string> vstr;
if(!global_alert_message.empty())
{
boost::split(vstr, global_alert_message, boost::is_any_of(":"), token_compress_on);
// make sure there are 5 tokens, 5th is text message
if (5 == vstr.size())
{
return vstr[4];
}
else
{
file_log("DEBUG ALERT ERROR - Something went wrong decoding the global alert string, there are not 5 tokens\n");
return "";
}
}
return "";
}
bool mastercore::checkExpiredAlerts(unsigned int curBlock, uint64_t curTime)
{
//expire any alerts that need expiring
int32_t alertType = 0;
uint64_t expiryValue = 0;
uint32_t typeCheck = 0;
uint32_t verCheck = 0;
string alertMessage;
if(!global_alert_message.empty())
{
bool parseSuccess = parseAlertMessage(global_alert_message, &alertType, &expiryValue, &typeCheck, &verCheck, &alertMessage);
if (parseSuccess)
{
switch (alertType)
{
case 1: //Text based alert only expiring by block number, show alert in UI and getalert_MP call, ignores type check value (eg use 0)
if (curBlock > expiryValue)
{
//the alert has expired, clear the global alert string
file_log("DEBUG ALERT - Expiring alert string %s\n",global_alert_message.c_str());
global_alert_message = "";
return true;
}
break;
case 2: //Text based alert only expiring by block time, show alert in UI and getalert_MP call, ignores type check value (eg use 0)
if (curTime > expiryValue)
{
//the alert has expired, clear the global alert string
file_log("DEBUG ALERT - Expiring alert string %s\n",global_alert_message.c_str());
global_alert_message = "";
return true;
}
break;
case 3: //Text based alert only expiring by client version, show alert in UI and getalert_MP call, ignores type check value (eg use 0)
if (OMNICORE_VERSION > expiryValue)
{
//the alert has expired, clear the global alert string
file_log("DEBUG ALERT - Expiring alert string %s\n",global_alert_message.c_str());
global_alert_message = "";
return true;
}
break;
case 4: //Update alert, show upgrade alert in UI and getalert_MP call + use isTransactionTypeAllowed to verify client support and shutdown if not present
//check of the new tx type is supported at live block
bool txSupported = isTransactionTypeAllowed(expiryValue+1, OMNI_PROPERTY_MSC, typeCheck, verCheck);
//check if we are at/past the live blockheight
bool txLive = (chainActive.Height()>(int64_t)expiryValue);
//testnet allows all types of transactions, so override this here for testing
//txSupported = false; //testing
//txLive = true; //testing
if ((!txSupported) && (txLive))
{
// we know we have transactions live we don't understand
// can't be trusted to provide valid data, shutdown
file_log("DEBUG ALERT - Shutting down due to unsupported live TX - alert string %s\n",global_alert_message.c_str());
printf("DEBUG ALERT - Shutting down due to unsupported live TX - alert string %s\n",global_alert_message.c_str()); //echo to screen
if (!GetBoolArg("-overrideforcedshutdown", false)) AbortNode("Shutting down due to alert: " + getMasterCoreAlertTextOnly());
return false;
}
if ((!txSupported) && (!txLive))
{
// warn the user this version does not support the new coming TX and they will need to update
// we don't actually need to take any action here, we leave the alert string in place and simply don't expire it
}
if (txSupported)
{
// we can simply expire this update as this version supports the new coming TX
file_log("DEBUG ALERT - Expiring alert string %s\n",global_alert_message.c_str());
global_alert_message = "";
return true;
}
break;
}
return false;
}
return false;
}
else { return false; }
return false;
}
// get total tokens for a property
// optionally counts the number of addresses who own that property: n_owners_total
int64_t mastercore::getTotalTokens(unsigned int propertyId, int64_t *n_owners_total)
{
int64_t prev = 0, owners = 0;
LOCK(cs_tally);
CMPSPInfo::Entry property;
if (false == _my_sps->getSP(propertyId, property)) return 0; // property ID does not exist
int64_t totalTokens = 0;
bool fixedIssuance = property.fixed;
if (!fixedIssuance || n_owners_total)
{
for(map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it)
{
string address = (my_it->first).c_str();
totalTokens += getMPbalance(address, propertyId, BALANCE);
totalTokens += getMPbalance(address, propertyId, SELLOFFER_RESERVE);
totalTokens += getMPbalance(address, propertyId, METADEX_RESERVE);
if (propertyId<3) totalTokens += getMPbalance(address, propertyId, ACCEPT_RESERVE);
if (prev != totalTokens)
{
prev = totalTokens;
owners++;
}
}
}
if (fixedIssuance)
{
totalTokens = property.num_tokens; //only valid for TX50
}
if (n_owners_total) *n_owners_total = owners;
return totalTokens;
}
// return true if everything is ok
bool mastercore::update_tally_map(string who, unsigned int which_property, int64_t amount, TallyType ttype)
{
bool bRet = false;
uint64_t before, after;
if (0 == amount)
{
file_log("%s(%s, %u=0x%X, %+ld, ttype= %d) 0 FUNDS !\n", __FUNCTION__, who.c_str(), which_property, which_property, amount, ttype);
return false;
}
LOCK(cs_tally);
before = getMPbalance(who, which_property, ttype);
map<string, CMPTally>::iterator my_it = mp_tally_map.find(who);
if (my_it == mp_tally_map.end())
{
// insert an empty element
my_it = (mp_tally_map.insert(std::make_pair(who,CMPTally()))).first;
}
CMPTally &tally = my_it->second;
bRet = tally.updateMoney(which_property, amount, ttype);
after = getMPbalance(who, which_property, ttype);
if (!bRet) file_log("%s(%s, %u=0x%X, %+ld, ttype=%d) INSUFFICIENT FUNDS\n", __FUNCTION__, who.c_str(), which_property, which_property, amount, ttype);
if (msc_debug_tally)
{
if ((exodus_address != who) || (exodus_address == who && msc_debug_exo))
{
file_log("%s(%s, %u=0x%X, %+ld, ttype=%d); before=%lu, after=%lu\n",
__FUNCTION__, who.c_str(), which_property, which_property, amount, ttype, before, after);
}
}
return bRet;
}
std::string p128(int128_t quantity)
{
//printf("\nTest # was %s\n", boost::lexical_cast<std::string>(quantity).c_str() );
return boost::lexical_cast<std::string>(quantity);
}
std::string p_arb(cpp_int quantity)
{
//printf("\nTest # was %s\n", boost::lexical_cast<std::string>(quantity).c_str() );
return boost::lexical_cast<std::string>(quantity);
}
//calculateFundraiser does token calculations per transaction
//calcluateFractional does calculations for missed tokens
void calculateFundraiser(unsigned short int propType, uint64_t amtTransfer, unsigned char bonusPerc,
uint64_t fundraiserSecs, uint64_t currentSecs, uint64_t numProps, unsigned char issuerPerc, uint64_t totalTokens,
std::pair<uint64_t, uint64_t>& tokens, bool &close_crowdsale )
{
//uint64_t weeks_sec = 604800;
int128_t weeks_sec_ = 604800L;
//define weeks in seconds
int128_t precision_ = 1000000000000L;
//define precision for all non-bitcoin values (bonus percentages, for example)
int128_t percentage_precision = 100L;
//define precision for all percentages (10/100 = 10%)
//uint64_t bonusSeconds = fundraiserSecs - currentSecs;
//calcluate the bonusseconds
//printf("\n bonus sec %lu\n", bonusSeconds);
int128_t bonusSeconds_ = fundraiserSecs - currentSecs;
//double weeks_d = bonusSeconds / (double) weeks_sec;
//debugging
int128_t weeks_ = (bonusSeconds_ / weeks_sec_) * precision_ + ( (bonusSeconds_ % weeks_sec_ ) * precision_) / weeks_sec_;
//calculate the whole number of weeks to apply bonus
//printf("\n weeks_d: %.8lf \n weeks: %s + (%s / %s) =~ %.8lf \n", weeks_d, p128(bonusSeconds_ / weeks_sec_).c_str(), p128(bonusSeconds_ % weeks_sec_).c_str(), p128(weeks_sec_).c_str(), boost::lexical_cast<double>(bonusSeconds_ / weeks_sec_) + boost::lexical_cast<double> (bonusSeconds_ % weeks_sec_) / boost::lexical_cast<double>(weeks_sec_) );
//debugging lines
//double ebPercentage_d = weeks_d * bonusPerc;
//debugging lines
int128_t ebPercentage_ = weeks_ * bonusPerc;
//calculate the earlybird percentage to be applied
//printf("\n ebPercentage_d: %.8lf \n ebPercentage: %s + (%s / %s ) =~ %.8lf \n", ebPercentage_d, p128(ebPercentage_ / precision_).c_str(), p128( (ebPercentage_) % precision_).c_str() , p128(precision_).c_str(), boost::lexical_cast<double>(ebPercentage_ / precision_) + boost::lexical_cast<double>(ebPercentage_ % precision_) / boost::lexical_cast<double>(precision_));
//debugging
//double bonusPercentage_d = ( ebPercentage_d / 100 ) + 1;
//debugging
int128_t bonusPercentage_ = (ebPercentage_ + (precision_ * percentage_precision) ) / percentage_precision;
//calcluate the bonus percentage to apply up to 'percentage_precision' number of digits
//printf("\n bonusPercentage_d: %.18lf \n bonusPercentage: %s + (%s / %s) =~ %.11lf \n", bonusPercentage_d, p128(bonusPercentage_ / precision_).c_str(), p128(bonusPercentage_ % precision_).c_str(), p128(precision_).c_str(), boost::lexical_cast<double>(bonusPercentage_ / precision_) + boost::lexical_cast<double>(bonusPercentage_ % precision_) / boost::lexical_cast<double>(precision_));
//debugging
//double issuerPercentage_d = (double) (issuerPerc * 0.01);
//debugging
int128_t issuerPercentage_ = (int128_t)issuerPerc * precision_ / percentage_precision;
//printf("\n issuerPercentage_d: %.8lf \n issuerPercentage: %s + (%s / %s) =~ %.8lf \n", issuerPercentage_d, p128(issuerPercentage_ / precision_ ).c_str(), p128(issuerPercentage_ % precision_).c_str(), p128( precision_ ).c_str(), boost::lexical_cast<double>(issuerPercentage_ / precision_) + boost::lexical_cast<double>(issuerPercentage_ % precision_) / boost::lexical_cast<double>(precision_));
//debugging
int128_t satoshi_precision_ = 100000000;
//define the precision for bitcoin amounts (satoshi)
//uint64_t createdTokens, createdTokens_decimal;
//declare used variables for total created tokens
//uint64_t issuerTokens, issuerTokens_decimal;
//declare used variables for total issuer tokens
//printf("\n NUMBER OF PROPERTIES %ld", numProps);
//printf("\n AMOUNT INVESTED: %ld BONUS PERCENTAGE: %.11f and %s", amtTransfer,bonusPercentage_d, p128(bonusPercentage_).c_str());
//long double ct = ((amtTransfer/1e8) * (long double) numProps * bonusPercentage_d);
//int128_t createdTokens_ = (int128_t)amtTransfer*(int128_t)numProps* bonusPercentage_;
cpp_int createdTokens = boost::lexical_cast<cpp_int>((int128_t)amtTransfer*(int128_t)numProps)* boost::lexical_cast<cpp_int>(bonusPercentage_);
//printf("\n CREATED TOKENS UINT %s \n", p_arb(createdTokens).c_str());
//printf("\n CREATED TOKENS %.8Lf, %s + (%s / %s) ~= %.8lf",ct, p128(createdTokens_ / (precision_ * satoshi_precision_) ).c_str(), p128(createdTokens_ % (precision_ * satoshi_precision_) ).c_str() , p128( precision_*satoshi_precision_ ).c_str(), boost::lexical_cast<double>(createdTokens_ / (precision_ * satoshi_precision_) ) + boost::lexical_cast<double>(createdTokens_ % (precision_ * satoshi_precision_)) / boost::lexical_cast<double>(precision_*satoshi_precision_));
//long double it = (uint64_t) ct * issuerPercentage_d;
//int128_t issuerTokens_ = (createdTokens_ / (satoshi_precision_ * precision_ )) * (issuerPercentage_ / 100) * precision_;
cpp_int issuerTokens = (createdTokens / (satoshi_precision_ * precision_ )) * (issuerPercentage_ / 100) * precision_;
//printf("\n ISSUER TOKENS: %.8Lf, %s + (%s / %s ) ~= %.8lf \n",it, p128(issuerTokens_ / (precision_ * satoshi_precision_ * 100 ) ).c_str(), p128( issuerTokens_ % (precision_ * satoshi_precision_ * 100 ) ).c_str(), p128(precision_*satoshi_precision_*100).c_str(), boost::lexical_cast<double>(issuerTokens_ / (precision_ * satoshi_precision_ * 100)) + boost::lexical_cast<double>(issuerTokens_ % (satoshi_precision_*precision_*100) )/ boost::lexical_cast<double>(satoshi_precision_*precision_*100));
//printf("\n UINT %s \n", p_arb(issuerTokens).c_str());
//total tokens including remainders
//printf("\n DIVISIBLE TOKENS (UI LAYER) CREATED: is ~= %.8lf, and %.8lf\n",(double)createdTokens + (double)createdTokens_decimal/(satoshi_precision *precision), (double) issuerTokens + (double)issuerTokens_decimal/(satoshi_precision*precision*percentage_precision) );
//if (2 == propType)
//printf("\n DIVISIBLE TOKENS (UI LAYER) CREATED: is ~= %.8lf, and %.8lf\n", (uint64_t) (boost::lexical_cast<double>(createdTokens_ / (precision_ * satoshi_precision_) ) + boost::lexical_cast<double>(createdTokens_ % (precision_ * satoshi_precision_)) / boost::lexical_cast<double>(precision_*satoshi_precision_) )/1e8, (uint64_t) (boost::lexical_cast<double>(issuerTokens_ / (precision_ * satoshi_precision_ * 100)) + boost::lexical_cast<double>(issuerTokens_ % (satoshi_precision_*precision_*100) )/ boost::lexical_cast<double>(satoshi_precision_*precision_*100)) / 1e8 );
//else
//printf("\n INDIVISIBLE TOKENS (UI LAYER) CREATED: is = %lu, and %lu\n", boost::lexical_cast<uint64_t>(createdTokens_ / (precision_ * satoshi_precision_ ) ), boost::lexical_cast<uint64_t>(issuerTokens_ / (precision_ * satoshi_precision_ * 100)));
cpp_int createdTokens_int = createdTokens / (precision_ * satoshi_precision_);
cpp_int issuerTokens_int = issuerTokens / (precision_ * satoshi_precision_ * 100 );
cpp_int newTotalCreated = totalTokens + createdTokens_int + issuerTokens_int;
if ( newTotalCreated > MAX_INT_8_BYTES) {
cpp_int maxCreatable = MAX_INT_8_BYTES - totalTokens;
cpp_int created = createdTokens_int + issuerTokens_int;
cpp_int ratio = (created * precision_ * satoshi_precision_) / maxCreatable;
//printf("\n created %s, ratio %s, maxCreatable %s, totalTokens %s, createdTokens_int %s, issuerTokens_int %s \n", p_arb(created).c_str(), p_arb(ratio).c_str(), p_arb(maxCreatable).c_str(), p_arb(totalTokens).c_str(), p_arb(createdTokens_int).c_str(), p_arb(issuerTokens_int).c_str() );
//debugging
issuerTokens_int = (issuerTokens_int * precision_ * satoshi_precision_)/ratio;
//calcluate the ratio of tokens for what we can create and apply it
createdTokens_int = MAX_INT_8_BYTES - issuerTokens_int ;
//give the rest to the user
//printf("\n created %s, ratio %s, maxCreatable %s, totalTokens %s, createdTokens_int %s, issuerTokens_int %s \n", p_arb(created).c_str(), p_arb(ratio).c_str(), p_arb(maxCreatable).c_str(), p_arb(totalTokens).c_str(), p_arb(createdTokens_int).c_str(), p_arb(issuerTokens_int).c_str() );
//debugging
close_crowdsale = true; //close up the crowdsale after assigning all tokens
}
tokens = std::make_pair(boost::lexical_cast<uint64_t>(createdTokens_int) , boost::lexical_cast<uint64_t>(issuerTokens_int));
//give tokens
}
// certain transaction types are not live on the network until some specific block height
// certain transactions will be unknown to the client, i.e. "black holes" based on their version
// the Restrictions array is as such: type, block-allowed-in, top-version-allowed
bool mastercore::isTransactionTypeAllowed(int txBlock, unsigned int txProperty, unsigned int txType, unsigned short version, bool bAllowNullProperty)
{
bool bAllowed = false;
bool bBlackHole = false;
unsigned int type;
int block_FirstAllowed;
unsigned short version_TopAllowed;
// bitcoin as property is never allowed, unless explicitly stated otherwise
if ((OMNI_PROPERTY_BTC == txProperty) && !bAllowNullProperty) return false;
// everything is always allowed on Bitcoin's TestNet or with TMSC/TestEcosystem on MainNet
if ((isNonMainNet()) || isTestEcosystemProperty(txProperty))
{
bAllowed = true;
}
for (unsigned int i = 0; i < sizeof(txRestrictionsRules)/sizeof(txRestrictionsRules[0]); i++)
{
type = txRestrictionsRules[i][0];
block_FirstAllowed = txRestrictionsRules[i][1];
version_TopAllowed = txRestrictionsRules[i][2];
if (txType != type) continue;
if (version_TopAllowed < version)
{
file_log("Black Hole identified !!! %d, %u, %u, %u\n", txBlock, txProperty, txType, version);
bBlackHole = true;
// TODO: what else?
// ...
}
if (0 > block_FirstAllowed) break; // array contains a negative -- nothing's allowed or done parsing
if (block_FirstAllowed <= txBlock) bAllowed = true;
}
return bAllowed && !bBlackHole;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// some old TODOs
// 6) verify large-number calculations (especially divisions & multiplications)
// 9) build in consesus checks with the masterchain.info & masterchest.info -- possibly run them automatically, daily (?)
// 10) need a locking mechanism between Core & Qt -- to retrieve the tally, for instance, this and similar to this: LOCK(wallet->cs_wallet);
//
uint64_t calculate_and_update_devmsc(unsigned int nTime)
{
//do nothing if before end of fundraiser
if (nTime < 1377993874) return -9919;
// taken mainly from msc_validate.py: def get_available_reward(height, c)
uint64_t devmsc = 0;
int64_t exodus_delta;
// spec constants:
const uint64_t all_reward = 5631623576222;
const double seconds_in_one_year = 31556926;
const double seconds_passed = nTime - 1377993874; // exodus bootstrap deadline