37 #include <boost/assign/list_of.hpp>
38 #include <boost/algorithm/string.hpp>
39 #include <boost/algorithm/string/find.hpp>
40 #include <boost/algorithm/string/join.hpp>
41 #include <boost/lexical_cast.hpp>
42 #include <boost/format.hpp>
43 #include <boost/filesystem.hpp>
44 #include "json/json_spirit_utils.h"
45 #include "json/json_spirit_value.h"
47 #include "leveldb/db.h"
48 #include "leveldb/write_batch.h"
50 #include <openssl/sha.h>
54 #include <boost/multiprecision/cpp_int.hpp>
59 using boost::multiprecision::int128_t;
60 using boost::multiprecision::cpp_int;
62 using namespace boost;
198 fileout = fopen(pathDebug.string().c_str(),
"a");
210 ret = fwrite(str.data(), 1, str.size(), stdout);
214 static bool fStartedNewLine =
true;
226 if (freopen(pathDebug.string().c_str(),
"a",
fileout) != NULL)
233 if (!str.empty() && str[str.size()-1] ==
'\n')
234 fStartedNewLine =
true;
236 fStartedNewLine =
false;
238 ret = fwrite(str.data(), 1, str.size(),
fileout);
269 const int buffer_size = 8000000;
271 FILE* file = fopen(pathLog.string().c_str(),
"r");
273 if (file && boost::filesystem::file_size(pathLog) > 50000000)
276 char *pch =
new char[buffer_size];
279 fseek(file, -buffer_size, SEEK_END);
280 int nBytes = fread(pch, 1, buffer_size, file);
281 fclose(file); file = NULL;
283 file = fopen(pathLog.string().c_str(),
"w");
286 fwrite(pch, 1, nBytes, file);
287 fclose(file); file = NULL;
294 if (NULL != file) fclose(file);
300 string str =
"*unknown*";
305 str =
strprintf(
"Test token: %d : 0x%08X", 0x7FFFFFFF & i, i);
313 default: str =
strprintf(
"SP token: %d", i);
329 int64_t n_abs = (n > 0 ? n : -n);
330 int64_t quotient = n_abs/
COIN;
331 int64_t remainder = n_abs%
COIN;
332 string str =
strprintf(
"%d.%08d", quotient, remainder);
334 if (!fSign)
return str;
337 str.insert((
unsigned int)0, 1,
'-');
339 str.insert((
unsigned int)0, 1,
'+');
349 std::string
FormatMP(
unsigned int property, int64_t n,
bool fSign)
369 if (msc_debug_verbose3) file_log(
"%s(%s)\n", __FUNCTION__, txid.
GetHex().c_str());
371 PendingMap::iterator it =
my_pending.find(txid);
378 p_pending->
print(txid);
382 if (msc_debug_verbose3) file_log(
"%s()src= %ld, line %d, file: %s\n", __FUNCTION__, src_amount, __LINE__, __FILE__);
395 return &(it->second);
402 static int pendingAdd(
const uint256 &txid,
const string &FromAddress,
unsigned int propId, int64_t Amount)
406 if (msc_debug_verbose3) file_log(
"%s(%s,%s,%u,%ld), line %d, file: %s\n", __FUNCTION__, txid.
GetHex().c_str(), FromAddress.c_str(), propId, Amount, __LINE__, __FILE__);
411 pending.
src = FromAddress;
413 pending.
prop = propId;
416 my_pending.insert(std::make_pair(txid, pending));
429 map<string, CMPTally>::iterator it =
mp_tally_map.find(address);
439 uint64_t balance = 0;
445 const map<string, CMPTally>::iterator my_it =
mp_tally_map.find(Address);
449 balance = (my_it->second).getMoney(property, ttype);
462 return (money + pending);
481 if (!a || !b)
return true;
486 const uint64_t result = a*b;
490 if ((0 != a) && (result / a != b))
return false;
511 for (md_PropertiesMap::iterator my_it =
metadex.begin(); my_it !=
metadex.end(); ++my_it)
513 if (my_it->first == propertyId)
516 for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it)
518 md_Set & indexes = (it->second);
519 for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it)
539 uint64_t expiryValue;
542 std::vector<std::string> vstr;
549 if (5 == vstr.size())
553 alertType = boost::lexical_cast<int32_t>(vstr[0]);
554 expiryValue = boost::lexical_cast<uint64_t>(vstr[1]);
555 typeCheck = boost::lexical_cast<uint32_t>(vstr[2]);
556 verCheck = boost::lexical_cast<uint32_t>(vstr[3]);
557 }
catch (
const boost::bad_lexical_cast &e)
559 file_log(
"DEBUG ALERT - error in converting values from global alert string\n");
565 file_log(
"DEBUG ALERT ERROR - Something went wrong decoding the global alert string, there are not 5 tokens\n");
568 if ((alertType < 1) || (alertType > 4) || (expiryValue == 0))
570 file_log(
"DEBUG ALERT ERROR - Something went wrong decoding the global alert string, values are not as expected.\n");
576 if (curBlock > expiryValue)
585 if (curTime > expiryValue)
613 if ((!txSupported) && (txLive))
617 file_log(
"DEBUG ALERT - Shutting down due to unsupported live TX - alert string %s\n",
global_alert_message.c_str());
618 printf(
"DEBUG ALERT - Shutting down due to unsupported live TX - alert string %s\n",
global_alert_message.c_str());
623 if ((!txSupported) && (!txLive))
640 else {
return false; }
648 int64_t prev = 0, owners = 0;
653 if (
false ==
_my_sps->
getSP(propertyId, property))
return 0;
655 int64_t totalTokens = 0;
656 bool fixedIssuance =
property.
fixed;
658 if (!fixedIssuance || n_owners_total)
662 string address = (my_it->first).c_str();
668 if (prev != totalTokens)
678 totalTokens =
property.num_tokens;
681 if (n_owners_total) *n_owners_total = owners;
690 uint64_t before, after;
694 file_log(
"%s(%s, %u=0x%X, %+ld, ttype= %d) 0 FUNDS !\n", __FUNCTION__, who.c_str(), which_property, which_property, amount, ttype);
702 map<string, CMPTally>::iterator my_it =
mp_tally_map.find(who);
711 bRet = tally.
updateMoney(which_property, amount, ttype);
714 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);
720 file_log(
"%s(%s, %u=0x%X, %+ld, ttype=%d); before=%lu, after=%lu\n",
721 __FUNCTION__, who.c_str(), which_property, which_property, amount, ttype, before, after);
728 std::string
p128(int128_t quantity)
731 return boost::lexical_cast<std::string>(quantity);
736 return boost::lexical_cast<std::string>(quantity);
741 uint64_t fundraiserSecs, uint64_t currentSecs, uint64_t numProps,
unsigned char issuerPerc, uint64_t totalTokens,
742 std::pair<uint64_t, uint64_t>& tokens,
bool &close_crowdsale )
745 int128_t weeks_sec_ = 604800L;
747 int128_t precision_ = 1000000000000L;
749 int128_t percentage_precision = 100L;
755 int128_t bonusSeconds_ = fundraiserSecs - currentSecs;
760 int128_t weeks_ = (bonusSeconds_ / weeks_sec_) * precision_ + ( (bonusSeconds_ % weeks_sec_ ) * precision_) / weeks_sec_;
769 int128_t ebPercentage_ = weeks_ * bonusPerc;
778 int128_t bonusPercentage_ = (ebPercentage_ + (precision_ * percentage_precision) ) / percentage_precision;
787 int128_t issuerPercentage_ = (int128_t)issuerPerc * precision_ / percentage_precision;
792 int128_t satoshi_precision_ = 100000000;
807 cpp_int createdTokens = boost::lexical_cast<cpp_int>((int128_t)amtTransfer*(int128_t)numProps)* boost::lexical_cast<cpp_int>(bonusPercentage_);
817 cpp_int issuerTokens = (createdTokens / (satoshi_precision_ * precision_ )) * (issuerPercentage_ / 100) * precision_;
830 cpp_int createdTokens_int = createdTokens / (precision_ * satoshi_precision_);
831 cpp_int issuerTokens_int = issuerTokens / (precision_ * satoshi_precision_ * 100 );
832 cpp_int newTotalCreated = totalTokens + createdTokens_int + issuerTokens_int;
837 cpp_int created = createdTokens_int + issuerTokens_int;
838 cpp_int ratio = (created * precision_ * satoshi_precision_) / maxCreatable;
843 issuerTokens_int = (issuerTokens_int * precision_ * satoshi_precision_)/ratio;
850 close_crowdsale =
true;
852 tokens = std::make_pair(boost::lexical_cast<uint64_t>(createdTokens_int) , boost::lexical_cast<uint64_t>(issuerTokens_int));
861 bool bAllowed =
false;
862 bool bBlackHole =
false;
864 int block_FirstAllowed;
865 unsigned short version_TopAllowed;
876 for (
unsigned int i = 0; i <
sizeof(
txRestrictionsRules)/
sizeof(txRestrictionsRules[0]); i++)
878 type = txRestrictionsRules[i][0];
879 block_FirstAllowed = txRestrictionsRules[i][1];
880 version_TopAllowed = txRestrictionsRules[i][2];
882 if (txType != type)
continue;
884 if (version_TopAllowed < version)
886 file_log(
"Black Hole identified !!! %d, %u, %u, %u\n", txBlock, txProperty, txType, version);
894 if (0 > block_FirstAllowed)
break;
896 if (block_FirstAllowed <= txBlock) bAllowed =
true;
899 return bAllowed && !bBlackHole;
913 if (nTime < 1377993874)
return -9919;
917 int64_t exodus_delta;
919 const uint64_t all_reward = 5631623576222;
920 const double seconds_in_one_year = 31556926;
921 const double seconds_passed = nTime - 1377993874;
922 const double years = seconds_passed/seconds_in_one_year;
923 const double part_available = 1 - pow(0.5, years);
924 const double available_reward=all_reward * part_available;
929 if (msc_debug_exo) file_log(
"devmsc=%lu, exodus_prev=%lu, exodus_delta=%ld\n", devmsc, exodus_prev, exodus_delta);
932 if (0>exodus_delta)
return 0;
935 exodus_prev = devmsc;
947 int my_addresses_count = 0;
953 for (propertyId = 1; propertyId<nextSPID; propertyId++)
968 for (propertyId = 1; propertyId<nextSPID; propertyId++)
987 return (my_addresses_count);
992 unsigned char sha_input[128];
993 unsigned char sha_result[128];
994 vector<unsigned char> vec_chars;
996 strcpy((
char *)sha_input, address.c_str());
1000 SHA256(sha_input, strlen((
const char *)sha_input), sha_result);
1002 vec_chars.resize(32);
1003 memcpy(&vec_chars[0], &sha_result[0], 32);
1004 ObfsHashes[j] =
HexStr(vec_chars);
1005 boost::to_upper(ObfsHashes[j]);
1007 if (msc_debug_verbose2)
if (5>j) file_log(
"%d: sha256 hex: %s\n", j, ObfsHashes[j].c_str());
1008 strcpy((
char *)sha_input, ObfsHashes[j].c_str());
1014 vector<vector<unsigned char> > vSolutions;
1016 if (!
Solver(scriptPubKey, whichTypeRet, vSolutions))
return false;
1027 int deadline_timeleft=1377993600-nTime;
1028 double bonus= 1 + std::max( 0.10 * deadline_timeleft / (60 * 60 * 24 * 7), 0.0 );
1037 uint64_t msc_tot= round( 100 * ExodusHighestValue * bonus );
1038 if (msc_debug_exo) file_log(
"Exodus Fundraiser tx detected, tx %s generated %lu.%08lu\n",wtx.
GetHash().
ToString().c_str(), msc_tot /
COIN, msc_tot %
COIN);
1050 int p2shAllowed = 0;
1075 vector<string>script_data;
1076 vector<string>address_data;
1078 vector<int64_t>value_data;
1081 string strReference;
1083 unsigned int packet_size = 0;
1085 int marker_count = 0, getmoney_count = 0;
1087 vector<string>multisig_script_data;
1089 uint64_t outAll = 0;
1092 mp_tx->
Set(wtx.
GetHash(), nBlock, idx, nTime);
1095 for (
unsigned int i = 0; i < wtx.
vout.size(); i++)
1100 outAll += wtx.
vout[i].nValue;
1108 ExodusValues[marker_count++] = wtx.
vout[i].nValue;
1112 TestNetMoneyValues[getmoney_count++] = wtx.
vout[i].nValue;
1119 else if (!marker_count)
1124 file_log(
"____________________________________________________________________________________________________________________________________\n");
1125 file_log(
"%s(block=%d, %s idx= %d); txid: %s\n", __FUNCTION__, nBlock,
DateTimeStrFormat(
"%Y-%m-%d %H:%M:%S", nTime).c_str(),
1130 for (
unsigned int i = 0; i < wtx.
vout.size(); i++)
1138 bool validType =
false;
1146 if (msc_debug_parser_data) file_log(
"saving address_data #%d: %s:%s\n", i, strAddress.c_str(), wtx.
vout[i].scriptPubKey.ToString().c_str());
1149 wtx.
vout[i].scriptPubKey.mscore_parse(script_data);
1150 address_data.push_back(strAddress);
1151 value_data.push_back(wtx.
vout[i].nValue);
1158 std::vector<CTxDestination> vDest;
1168 if (msc_debug_parser_data)
1170 file_log(
"address_data.size=%lu\n", address_data.size());
1171 file_log(
"script_data.size=%lu\n", script_data.size());
1172 file_log(
"value_data.size=%lu\n", value_data.size());
1175 int inputs_errors = 0;
1176 map <string, uint64_t> inputs_sum_of_values;
1179 for (
unsigned int i = 0; i < wtx.
vin.size(); i++)
1183 if (msc_debug_vin) file_log(
"vin=%d:%s\n", i, wtx.
vin[i].scriptSig.ToString().c_str());
1192 unsigned int n = wtx.
vin[i].prevout.n;
1196 uint64_t nValue = txPrev.vout[n].nValue;
1205 if (!
getOutputType(txPrev.vout[n].scriptPubKey, whichType)) ++inputs_errors;
1208 if (inputs_errors)
break;
1213 inputs_sum_of_values[addressSource.
ToString()] += nValue;
1215 else ++inputs_errors;
1217 if (msc_debug_vin) file_log(
"vin=%d:%s\n", i, wtx.
vin[i].ToString().c_str());
1220 txFee = inAll - outAll;
1229 for(map<string, uint64_t>::iterator my_it = inputs_sum_of_values.begin(); my_it != inputs_sum_of_values.end(); ++my_it)
1231 uint64_t nTemp = my_it->second;
1235 strSender = my_it->first;
1236 if (msc_debug_exo) file_log(
"looking for The Sender: %s , nMax=%lu, nTemp=%lu\n", strSender.c_str(), nMax, nTemp);
1241 if (!strSender.empty())
1243 if (msc_debug_verbose) file_log(
"The Sender: %s : His Input Sum of Values= %lu.%08lu ; fee= %lu.%08lu\n",
1248 file_log(
"The sender is still EMPTY !!! txid: %s\n", wtx.
GetHash().
GetHex().c_str());
1253 int64_t BTC_amount = ExodusValues[0];
1266 if (0 < BTC_amount && !bRPConly) (void)
TXExodusFundraiser(wtx, strSender, BTC_amount, nBlock, nTime);
1269 for (
unsigned int i = 0; i < wtx.
vout.size(); i++)
1282 std::vector<CTxDestination> vDest;
1286 if (msc_debug_script) file_log(
"scriptPubKey: %s\n", wtx.
vout[i].scriptPubKey.mscore_getHex().c_str());
1290 if (msc_debug_script) file_log(
" >> multisig: ");
1303 if (msc_debug_script) file_log(
"%s ; ", address.
ToString().c_str());
1306 if (msc_debug_script) file_log(
"\n");
1308 wtx.
vout[i].scriptPubKey.mscore_parse(multisig_script_data,
false);
1317 int mdata_count = 0;
1323 string strScriptData;
1324 string strDataAddress;
1325 string strRefAddress;
1326 unsigned char dataAddressSeq = 0xFF;
1327 unsigned char seq = 0xFF;
1328 int64_t dataAddressValue = 0;
1331 for (
unsigned k = 0; k<script_data.size();k++)
1336 string strSub = script_data[k].substr(2,16);
1337 seq = (
ParseHex(script_data[k].substr(0,2)))[0];
1339 if ((
"0000000000000001" == strSub) || (
"0000000000000002" == strSub))
1341 if (strScriptData.empty())
1344 strDataAddress = address_data[k];
1345 dataAddressSeq = seq;
1346 dataAddressValue = value_data[k];
1347 if (msc_debug_parser_data) file_log(
"Data Address located - data[%d]:%s: %s (%lu.%08lu)\n", k, script_data[k].c_str(), address_data[k].c_str(), value_data[k] /
COIN, value_data[k] %
COIN);
1352 strDataAddress =
"";
1353 if (msc_debug_parser_data) file_log(
"Multiple Data Addresses found (collision?) Class A invalidated, defaulting to BTC payment\n");
1360 if (!strDataAddress.empty())
1362 unsigned char expectedRefAddressSeq = dataAddressSeq + 1;
1363 for (
unsigned k = 0; k<script_data.size();k++)
1369 seq = (
ParseHex(script_data[k].substr(0,2)))[0];
1371 if ((address_data[k] != strDataAddress) && (address_data[k] !=
exodus_address) && (expectedRefAddressSeq == seq))
1373 if (strRefAddress.empty())
1375 strRefAddress = address_data[k];
1376 if (msc_debug_parser_data) file_log(
"Reference Address located via seqnum - data[%d]:%s: %s (%lu.%08lu)\n", k, script_data[k].c_str(), address_data[k].c_str(), value_data[k] /
COIN, value_data[k] %
COIN);
1382 if (msc_debug_parser_data) file_log(
"Reference Address sequence number collision, will fall back to evaluating matching output amounts\n");
1388 if (strRefAddress.empty())
1390 for (
unsigned k = 0; k<script_data.size();k++)
1396 if ((address_data[k] != strDataAddress) && (address_data[k] !=
exodus_address) && (dataAddressValue == value_data[k]))
1398 for (
int exodus_idx=0;exodus_idx<marker_count;exodus_idx++)
1400 if (value_data[k] == ExodusValues[exodus_idx])
1402 if (strRefAddress.empty())
1404 strRefAddress = address_data[k];
1405 if (msc_debug_parser_data) file_log(
"Reference Address located via matching amounts - data[%d]:%s: %s (%lu.%08lu)\n", k, script_data[k].c_str(), address_data[k].c_str(), value_data[k] /
COIN, value_data[k] %
COIN);
1410 if (msc_debug_parser_data) file_log(
"Reference Address collision, multiple potential candidates. Class A invalidated, defaulting to BTC payment\n");
1421 if (!strRefAddress.empty()) strReference=strRefAddress;
1424 if (strRefAddress.empty()) strDataAddress=
"";
1428 if (strDataAddress.empty())
1432 file_log(
"!! sender: %s , receiver: %s\n", strSender.c_str(), strReference.c_str());
1433 file_log(
"!! this may be the BTC payment for an offer !!\n");
1440 for (
unsigned int i = 0; i < wtx.
vout.size(); i++)
1449 file_log(
"payment #%d %s %11.8lf\n", count, strAddress.c_str(), (double)wtx.
vout[i].nValue/(
double)
COIN);
1452 if (bRPConly) count = 55555;
1457 return count ? count : -5678;
1462 if (msc_debug_parser_data) file_log(
"valid Class A:from=%s:to=%s:data=%s\n", strSender.c_str(), strReference.c_str(), strScriptData.c_str());
1472 if (msc_debug_parser_data) file_log(
"Beginning reference identification\n");
1474 bool referenceFound =
false;
1475 bool changeRemoved =
false;
1476 unsigned int potentialReferenceOutputs = 0;
1479 BOOST_FOREACH(
const string &addr, address_data)
1482 if (msc_debug_parser_data) file_log(
"ref? data[%d]:%s: %s (%lu.%08lu)\n",
1483 k, script_data[k].c_str(), addr.c_str(), value_data[k] /
COIN, value_data[k] %
COIN);
1488 ++potentialReferenceOutputs;
1489 if (1 == potentialReferenceOutputs)
1491 strReference = addr;
1492 referenceFound =
true;
1493 if (msc_debug_parser_data) file_log(
"Single reference potentially id'd as follows: %s \n", strReference.c_str());
1498 referenceFound =
false;
1499 if (msc_debug_parser_data) file_log(
"More than one potential reference candidate, blanking strReference, need to go fishing\n");
1505 if (!referenceFound)
1507 if (msc_debug_parser_data) file_log(
"Reference has not been found yet, going fishing\n");
1509 BOOST_FOREACH(
const string &addr, address_data)
1514 if ((addr == strSender) && (!changeRemoved))
1517 changeRemoved =
true;
1518 if (msc_debug_parser_data) file_log(
"Removed change\n");
1523 strReference = addr;
1524 if (msc_debug_parser_data) file_log(
"Resetting strReference as follows: %s \n ", strReference.c_str());
1530 if (msc_debug_parser_data) file_log(
"Ending reference identification\n");
1531 if (msc_debug_parser_data) file_log(
"Final decision on reference identification is: %s\n", strReference.c_str());
1533 if (msc_debug_parser) file_log(
"%s(), line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
1535 for (
unsigned int k = 0; k<multisig_script_data.size();k++)
1537 if (msc_debug_parser) file_log(
"%s(), line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
1541 char *c_addr_type = (
char *)
"";
1544 if (msc_debug_parser) file_log(
"%s(), line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
1547 vector<unsigned char>hash =
ParseHex(strObfuscatedHashes[mdata_count+1]);
1548 vector<unsigned char>packet =
ParseHex(multisig_script_data[k].substr(2*1,2*
PACKET_SIZE));
1550 for (
unsigned int i=0;i<packet.size();i++)
1552 packet[i] ^= hash[i];
1556 strPacket =
HexStr(packet.begin(),packet.end(),
false);
1561 file_log(
"increase MAX_PACKETS ! mdata_count= %d\n", mdata_count);
1566 if (msc_debug_parser_data) file_log(
"multisig_data[%d]:%s: %s%s\n", k, multisig_script_data[k].c_str(), strAddress.c_str(), c_addr_type);
1568 if (!strPacket.empty())
1570 if (msc_debug_parser) file_log(
"packet #%d: %s\n", mdata_count, strPacket.c_str());
1572 if (msc_debug_parser) file_log(
"%s(), line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
1577 if (
sizeof(single_pkt)<packet_size)
1582 if (msc_debug_parser) file_log(
"%s(), line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
1584 if (msc_debug_parser) file_log(
"%s(), line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
1587 for (
int m=0;m<mdata_count;m++)
1589 if (msc_debug_parser) file_log(
"m=%d: %s\n", m,
HexStr(packets[m],
PACKET_SIZE + packets[m],
false).c_str());
1592 if (1+m != packets[m][0])
1594 if (msc_debug_spec) file_log(
"Error: non-sequential seqnum ! expected=%d, got=%d\n", 1+m, packets[m][0]);
1601 if (msc_debug_verbose) file_log(
"single_pkt: %s\n",
HexStr(single_pkt, packet_size + single_pkt,
false).c_str());
1603 mp_tx->
Set(strSender, strReference, 0, wtx.
GetHash(), nBlock, idx, (
unsigned char *)&single_pkt, packet_size, fMultisig, (inAll-outAll));
1612 int n_total = 0, n_found = 0;
1616 if ((0 >= nHeight) || (max_block < nHeight))
return -1;
1618 printf(
"starting block= %d, max_block= %d\n", nHeight, max_block);
1621 for (
int blockNum = nHeight;blockNum<=max_block;blockNum++)
1626 if (msc_debug_exo) file_log(
"%s(%d; max=%d):%s, line %d, file: %s\n",
1627 __FUNCTION__, blockNum, max_block, strBlockHash.c_str(), __LINE__, __FILE__);
1640 n_total += tx_count;
1651 printf(
"%34s => ", (my_it->first).c_str());
1652 (my_it->second).print();
1655 printf(
"starting block= %d, max_block= %d\n", nHeight, max_block);
1656 printf(
"n_total= %d, n_found= %d\n", n_total, n_found);
1663 std::vector<std::string> addrData;
1664 boost::split(addrData, s, boost::is_any_of(
"="), token_compress_on);
1665 if (addrData.size() != 2) {
1669 string strAddress = addrData[0];
1672 std::vector<std::string> vProperties;
1673 boost::split(vProperties, addrData[1], boost::is_any_of(
";"), token_compress_on);
1675 std::vector<std::string>::const_iterator iter;
1676 for (iter = vProperties.begin(); iter != vProperties.end(); ++iter) {
1677 if ((*iter).empty()) {
1681 std::vector<std::string> curData;
1682 boost::split(curData, *iter, boost::is_any_of(
","), token_compress_on);
1683 if (curData.size() < 1) {
1688 size_t delimPos = curData[0].find(
':');
1690 uint64_t balance = 0, sellReserved = 0, acceptReserved = 0;
1692 if (delimPos != curData[0].npos) {
1693 property =
atoi(curData[0].substr(0,delimPos));
1694 balance = boost::lexical_cast<boost::uint64_t>(curData[0].substr(delimPos + 1, curData[0].npos));
1696 balance = boost::lexical_cast<boost::uint64_t>(curData[0]);
1699 if (curData.size() >= 2) {
1700 sellReserved = boost::lexical_cast<boost::uint64_t>(curData[1]);
1703 if (curData.size() >= 3) {
1704 acceptReserved = boost::lexical_cast<boost::uint64_t>(curData[2]);
1707 if (balance == 0 && sellReserved == 0 && acceptReserved == 0) {
1716 const uint64_t metadexReserve = 0;
1728 uint64_t amountOriginal, btcDesired, minFee, left_forsale;
1729 unsigned int prop, prop_desired;
1730 unsigned char blocktimelimit;
1731 std::vector<std::string> vstr;
1732 boost::split(vstr, s, boost::is_any_of(
" ,="), token_compress_on);
1737 if ((10 != vstr.size()) && (9 != vstr.size()))
return -1;
1739 sellerAddr = vstr[i++];
1740 offerBlock =
atoi(vstr[i++]);
1741 amountOriginal = boost::lexical_cast<uint64_t>(vstr[i++]);
1742 prop = boost::lexical_cast<
unsigned int>(vstr[i++]);
1743 btcDesired = boost::lexical_cast<uint64_t>(vstr[i++]);
1744 prop_desired = boost::lexical_cast<
unsigned int>(vstr[i++]);
1745 minFee = boost::lexical_cast<uint64_t>(vstr[i++]);
1746 blocktimelimit =
atoi(vstr[i++]);
1747 txidStr = vstr[i++];
1752 CMPOffer newOffer(offerBlock, amountOriginal, prop, btcDesired, minFee, blocktimelimit,
uint256(txidStr));
1754 if (
my_offers.insert(std::make_pair(combo, newOffer)).second)
1765 assert(10 == vstr.size());
1767 left_forsale = boost::lexical_cast<uint64_t>(vstr[i++]);
1769 CMPMetaDEx new_mdex(sellerAddr, offerBlock, prop, amountOriginal, prop_desired,
1770 btcDesired,
uint256(txidStr), blocktimelimit, (
unsigned char) minFee, left_forsale );
1777 md_Set temp_indexes, *p_indexes = NULL;
1779 std::pair<md_Set::iterator,bool> ret;
1781 if (p_prices) p_indexes =
get_Indexes(p_prices, neworder_price);
1783 if (!p_indexes) p_indexes = &temp_indexes;
1785 ret = p_indexes->insert(new_mdex);
1787 if (
false == ret.second)
return -1;
1790 if (!p_prices) p_prices = &temp_prices;
1792 (*p_prices)[neworder_price] = *p_indexes;
1806 unsigned char blocktimelimit;
1807 std::vector<std::string> vstr;
1808 boost::split(vstr, s, boost::is_any_of(
" ,="), token_compress_on);
1809 uint64_t amountRemaining, amountOriginal, offerOriginal, btcDesired;
1811 string sellerAddr, buyerAddr, txidStr;
1814 if (10 != vstr.size())
return -1;
1816 sellerAddr = vstr[i++];
1817 prop = boost::lexical_cast<
unsigned int>(vstr[i++]);
1818 buyerAddr = vstr[i++];
1819 nBlock =
atoi(vstr[i++]);
1820 amountRemaining = boost::lexical_cast<uint64_t>(vstr[i++]);
1821 amountOriginal = boost::lexical_cast<uint64_t>(vstr[i++]);
1822 blocktimelimit =
atoi(vstr[i++]);
1823 offerOriginal = boost::lexical_cast<uint64_t>(vstr[i++]);
1824 btcDesired = boost::lexical_cast<uint64_t>(vstr[i++]);
1825 txidStr = vstr[i++];
1828 CMPAccept newAccept(amountOriginal, amountRemaining, nBlock, blocktimelimit, prop, offerOriginal, btcDesired,
uint256(txidStr));
1829 if (
my_accepts.insert(std::make_pair(combo, newAccept)).second) {
1839 uint64_t exodusPrev;
1840 unsigned int nextSPID, nextTestSPID;
1841 std::vector<std::string> vstr;
1842 boost::split(vstr, s, boost::is_any_of(
" ,="), token_compress_on);
1843 if (3 != vstr.size())
return -1;
1846 exodusPrev = boost::lexical_cast<uint64_t>(vstr[i++]);
1847 nextSPID = boost::lexical_cast<
unsigned int>(vstr[i++]);
1848 nextTestSPID = boost::lexical_cast<
unsigned int>(vstr[i++]);
1859 unsigned int propertyId;
1861 unsigned int property_desired;
1863 unsigned char early_bird;
1864 unsigned char percentage;
1868 std::vector<std::string> vstr;
1869 boost::split(vstr, s, boost::is_any_of(
" ,"), token_compress_on);
1872 if (9 > vstr.size())
return -1;
1874 sellerAddr = vstr[i++];
1875 propertyId =
atoi(vstr[i++]);
1876 nValue = boost::lexical_cast<uint64_t>(vstr[i++]);
1877 property_desired =
atoi(vstr[i++]);
1878 deadline = boost::lexical_cast<uint64_t>(vstr[i++]);
1879 early_bird = (
unsigned char)
atoi(vstr[i++]);
1880 percentage = (
unsigned char)
atoi(vstr[i++]);
1881 u_created = boost::lexical_cast<uint64_t>(vstr[i++]);
1882 i_created = boost::lexical_cast<uint64_t>(vstr[i++]);
1884 CMPCrowd newCrowdsale(propertyId,nValue,property_desired,deadline,early_bird,percentage,u_created,i_created);
1887 while (i < vstr.size()) {
1888 std::vector<std::string> entryData;
1889 boost::split(entryData, vstr[i++], boost::is_any_of(
"="), token_compress_on);
1890 if ( 2 != entryData.size())
return -1;
1892 std::vector<std::string> valueData;
1893 boost::split(valueData, entryData[1], boost::is_any_of(
";"), token_compress_on);
1895 std::vector<uint64_t> vals;
1896 std::vector<std::string>::const_iterator iter;
1897 for (iter = valueData.begin(); iter != valueData.end(); ++iter) {
1898 vals.push_back(boost::lexical_cast<uint64_t>(*iter));
1901 newCrowdsale.insertDatabase(entryData[0], vals);
1905 if (
my_crowds.insert(std::make_pair(sellerAddr, newCrowdsale)).second) {
1914 static int msc_file_load(
const string &filename,
int what,
bool verifyHash =
false)
1917 int (*inputLineFunc)(
const string &) = NULL;
1920 SHA256_Init(&shaCtx);
1959 if (msc_debug_persistence)
1961 LogPrintf(
"Loading %s ... \n", filename);
1962 file_log(
"%s(%s), line %d, file: %s\n", __FUNCTION__, filename.c_str(), __LINE__, __FILE__);
1966 file.open(filename.c_str());
1967 if (!file.is_open())
1969 if (msc_debug_persistence)
LogPrintf(
"%s(%s): file not found, line %d, file: %s\n", __FUNCTION__, filename.c_str(), __LINE__, __FILE__);
1975 std::string fileHash;
1979 std::getline(file, line);
1980 if (line.empty() || line[0] ==
'#')
continue;
1983 line.erase( std::remove( line.begin(), line.end(),
'\r' ), line.end() ) ;
1986 if (line[0] ==
'!') {
1987 fileHash = line.substr(1);
1993 SHA256_Update(&shaCtx, line.c_str(), line.length());
1996 if (inputLineFunc) {
1997 if (inputLineFunc(line) < 0) {
2008 if (verifyHash && res == 0) {
2011 SHA256_Final((
unsigned char*)&hash1, &shaCtx);
2013 SHA256((
unsigned char*)&hash1,
sizeof(hash1), (
unsigned char*)&hash2);
2015 if (
false == boost::iequals(hash2.
ToString(), fileHash)) {
2016 file_log(
"File %s loaded, but failed hash validation!\n", filename.c_str());
2021 file_log(
"%s(%s), loaded lines= %d, res= %d\n", __FUNCTION__, filename.c_str(), lines, res);
2022 LogPrintf(
"%s(): file: %s , loaded lines= %d, res= %d\n", __FUNCTION__, filename, lines, res);
2048 if (NULL == spBlockIndex) {
2055 if (remainingSPs < 0) {
2061 spBlockIndex = spBlockIndex->
pprev;
2067 std::set<uint256> persistedBlocks;
2069 boost::filesystem::directory_iterator endIter;
2070 for (; dIter != endIter; ++dIter) {
2071 if (
false == boost::filesystem::is_regular_file(dIter->status()) || dIter->path().empty()) {
2076 std::string fName = (*--dIter->path().end()).
string();
2077 std::vector<std::string> vstr;
2078 boost::split(vstr, fName, boost::is_any_of(
"-."), token_compress_on);
2079 if ( vstr.size() == 3 &&
2080 boost::equals(vstr[2],
"dat")) {
2082 blockHash.
SetHex(vstr[1]);
2089 persistedBlocks.insert(blockHash);
2097 while (NULL != curTip && persistedBlocks.size() > 0) {
2098 if (persistedBlocks.find(*spBlockIndex->
phashBlock) != persistedBlocks.end()) {
2114 persistedBlocks.erase(*spBlockIndex->
phashBlock);
2122 curTip = curTip->
pprev;
2126 if (persistedBlocks.size() == 0) {
2139 map<string, CMPTally>::iterator iter;
2141 bool emptyWallet =
true;
2143 string lineOut = (*iter).first;
2144 lineOut.append(
"=");
2145 CMPTally &curAddr = (*iter).second;
2147 unsigned int prop = 0;
2148 while (0 != (prop = curAddr.
next())) {
2149 uint64_t balance = (*iter).second.getMoney(prop,
BALANCE);
2151 uint64_t acceptReserved = (*iter).second.getMoney(prop,
ACCEPT_RESERVE);
2152 const uint64_t metadexReserve = (*iter).second.getMoney(prop,
METADEX_RESERVE);
2156 if ( 0 == balance && 0 == sellReserved && 0 == acceptReserved && 0 == metadexReserve ) {
2160 emptyWallet =
false;
2167 % metadexReserve).str());
2171 if (
false == emptyWallet) {
2173 SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length());
2176 file << lineOut << endl;
2185 OfferMap::const_iterator iter;
2188 std::vector<std::string> vstr;
2189 boost::split(vstr, (*iter).first, boost::is_any_of(
"-"), token_compress_on);
2190 CMPOffer const &offer = (*iter).second;
2200 for (md_PropertiesMap::iterator my_it =
metadex.begin(); my_it !=
metadex.end(); ++my_it)
2203 for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it)
2205 md_Set & indexes = (it->second);
2206 for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it)
2219 AcceptMap::const_iterator iter;
2222 std::vector<std::string> vstr;
2223 boost::split(vstr, (*iter).first, boost::is_any_of(
"-+"), token_compress_on);
2224 CMPAccept const &accept = (*iter).second;
2225 accept.
saveAccept(file, shaCtx, vstr[0], vstr[1]);
2242 SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length());
2245 file << lineOut << endl;
2252 CrowdMap::const_iterator iter;
2255 CMPCrowd const &crowd = (*iter).second;
2267 file.open(balancePath.string().c_str());
2270 SHA256_Init(&shaCtx);
2299 SHA256_Final((
unsigned char*)&hash1, &shaCtx);
2301 SHA256((
unsigned char*)&hash1,
sizeof(hash1), (
unsigned char*)&hash2);
2302 file <<
"!" << hash2.
ToString() << endl;
2312 if (boost::equals(str, statePrefix[i])) {
2323 std::set<uint256> statefulBlockHashes;
2326 boost::filesystem::directory_iterator endIter;
2327 for (; dIter != endIter; ++dIter) {
2328 std::string fName = dIter->path().empty() ?
"<invalid>" : (*--dIter->path().end()).
string();
2329 if (
false == boost::filesystem::is_regular_file(dIter->status())) {
2331 file_log(
"Non-regular file found in persistence directory : %s\n", fName.c_str());
2335 std::vector<std::string> vstr;
2336 boost::split(vstr, fName, boost::is_any_of(
"-."), token_compress_on);
2337 if ( vstr.size() == 3 &&
2339 boost::equals(vstr[2],
"dat")) {
2341 blockHash.
SetHex(vstr[1]);
2342 statefulBlockHashes.insert(blockHash);
2344 file_log(
"None state file found in persistence directory : %s\n", fName.c_str());
2349 std::set<uint256>::const_iterator iter;
2350 for (iter = statefulBlockHashes.begin(); iter != statefulBlockHashes.end(); ++iter) {
2353 map<uint256,CBlockIndex *>::const_iterator indexIter =
mapBlockIndex.find((*iter));
2355 curIndex = (*indexIter).second;
2360 if (msc_debug_persistence)
2363 file_log(
"State from Block:%s is no longer need, removing files (age-from-tip: %d)\n", (*iter).ToString().c_str(), topIndex->
nHeight - curIndex->
nHeight);
2365 file_log(
"State from Block:%s is no longer need, removing files (not in index)\n", (*iter).ToString().c_str());
2370 const char *blockHashStr = (*iter).
ToString().c_str();
2407 if (mastercoreInitialized) {
2412 printf(
"%s()%s, line %d, file: %s\n", __FUNCTION__,
isNonMainNet() ?
"TESTNET":
"", __LINE__, __FILE__);
2416 file_log(
"\n%s OMNICORE INIT, build date: " __DATE__
" " __TIME__
"\n\n",
DateTimeStrFormat(
"%Y-%m-%d %H:%M:%S",
GetTime()).c_str());
2431 file_log(
"Process was started with --startclean option, attempting to clear persistence files...");
2434 boost::filesystem::path persistPath =
GetDataDir() /
"MP_persist";
2435 boost::filesystem::path txlistPath =
GetDataDir() /
"MP_txlist";
2436 boost::filesystem::path tradePath =
GetDataDir() /
"MP_tradelist";
2437 boost::filesystem::path spPath =
GetDataDir() /
"MP_spinfo";
2438 boost::filesystem::path stoPath =
GetDataDir() /
"MP_stolist";
2439 if (boost::filesystem::exists(persistPath)) boost::filesystem::remove_all(persistPath);
2440 if (boost::filesystem::exists(txlistPath)) boost::filesystem::remove_all(txlistPath);
2441 if (boost::filesystem::exists(tradePath)) boost::filesystem::remove_all(tradePath);
2442 if (boost::filesystem::exists(spPath)) boost::filesystem::remove_all(spPath);
2443 if (boost::filesystem::exists(stoPath)) boost::filesystem::remove_all(stoPath);
2444 file_log(
"Success clearing persistence files (did not raise any exceptions).");
2446 catch(boost::filesystem::filesystem_error
const & e)
2448 file_log(
"Exception deleting folders for --startclean option.\n");
2449 printf(
"Exception deleting folders for --startclean option.\n");
2461 static const uint64_t snapshotDevMSC = 0;
2472 if (nWaterlineBlock < 0) {
2477 if (nWaterlineBlock < snapshotHeight)
2479 nWaterlineBlock = snapshotHeight;
2484 nWaterlineBlock += 1;
2542 printf(
"%s(), line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
2556 file_log(
"\n%s OMNICORE SHUTDOWN, build date: " __DATE__
" " __TIME__
"\n\n",
DateTimeStrFormat(
"%Y-%m-%d %H:%M:%S",
GetTime()).c_str());
2569 if (!mastercoreInitialized) {
2581 int interp_ret = -555555, pop_ret;
2583 if (nBlock < nWaterlineBlock)
return -1;
2591 if (interp_ret) file_log(
"!!! interpretPacket() returned %d !!!\n", interp_ret);
2596 if (!disableLevelDB)
2598 bool bValid = (0 <= interp_ret);
2628 std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->
mapAddressBook.find(address_parsed.
Get());
2631 return (mi->second.name);
2658 int64_t nDustLimit = 1 + (((nSize * nRelayTxFee * 3) - 1) / 1000);
2666 int64_t n_max = (
COIN * (20 * (0.0001)));
2668 int64_t n_total = 0;
2671 if (0 < additional) n_max += additional;
2675 string sAddress =
"";
2678 for (map<uint256, CWalletTx>::iterator it = wallet->
mapWallet.begin();
2680 const uint256& wtxid = it->first;
2691 for (
unsigned int i = 0; i < pcoin->
vout.size(); i++) {
2697 bIsMine =
IsMine(*wallet, dest);
2698 bIsSpent = wallet->
IsSpent(wtxid, i);
2700 if (!bIsMine || bIsSpent)
2703 int64_t n = bIsSpent ? 0 : pcoin->
vout[i].nValue;
2706 if (msc_debug_tokens)
2707 file_log(
"%s:IsMine()=%s:IsSpent()=%s:%s: i=%d, nValue= %lu\n",
2708 sAddress.c_str(), bIsMine ?
"yes" :
"NO",
2709 bIsSpent ?
"YES" :
"no", wtxid.
ToString().c_str(), i, n);
2713 if (FromAddress == sAddress) {
2715 coinControl.
Select(outpt);
2719 if (n_max <= n_total)
2725 if (n_max <= n_total)
2743 int mastercore::ClassB_send(
const string &senderAddress,
const string &receiverAddress,
const string &redemptionAddress,
const vector<unsigned char> &
data,
uint256 & txid, int64_t referenceamount)
2747 vector< pair<CScript, int64_t> > vecSend;
2750 if (0 >
selectCoins(senderAddress, coinControl, referenceamount))
2761 if (
false == redemptionAddress.empty()) {
2768 if (wallet && address.
IsValid())
2772 file_log(
"%s() ERROR: Redemption Address must be specified !\n", __FUNCTION__);
2784 if (!wallet->
GetPubKey(keyID, redeemingPubKey))
2794 int nRemainingBytes = data.size();
2796 unsigned char seqNum = 1;
2800 while (nRemainingBytes > 0) {
2807 vector<CPubKey> keys;
2809 keys.push_back(redeemingPubKey);
2812 for (i = 0; i < nKeys; i++)
2815 vector<unsigned char> fakeKey;
2816 fakeKey.push_back(seqNum);
2820 fakeKey.insert(fakeKey.end(), data.begin() + nNextByte, data.begin() + nNextByte + numBytes);
2821 nNextByte += numBytes;
2822 nRemainingBytes -= numBytes;
2826 fakeKey.push_back(0);
2831 vector<unsigned char>hash =
ParseHex(strObfuscatedHashes[seqNum]);
2833 fakeKey[j] = fakeKey[j] ^ hash[j];
2837 fakeKey.insert(fakeKey.begin(), 2);
2842 unsigned char random_byte = (
unsigned char)(
GetRand(256));
2843 for (j = 0; i < 256 ; j++)
2845 fakeKey[32] = random_byte;
2848 file_log(
"pubKey check: %s\n", (
HexStr(pubKey.
begin(), pubKey.
end()).c_str()));
2855 keys.push_back(pubKey);
2861 vecSend.push_back(make_pair(multisig_output,
GetDustLimit(multisig_output)));
2865 int64_t nFeeRet = 0;
2866 std::string strFailReason;
2877 if (!receiverAddress.empty())
2881 vecSend.push_back(make_pair(scriptPubKey, 0 < referenceamount ? referenceamount :
GetDustLimit(scriptPubKey)));
2886 vecSend.push_back(make_pair(scriptPubKey,
GetDustLimit(scriptPubKey)));
2903 printf(
"RawTX:\n%s\n\n", strHex.c_str());
2908 file_log(
"%s():%s; nFeeRet = %lu, line %d, file: %s\n", __FUNCTION__, wtxNew.
ToString().c_str(), nFeeRet, __LINE__, __FILE__);
2924 const int64_t amount = Amount;
2925 const unsigned int prop = PropertyID;
2927 if (msc_debug_send) file_log(
"%s(From: %s , To: %s , Property= %u, Amount= %lu, Available= %ld, Pending= %ld)\n",
2928 __FUNCTION__, FromAddress.c_str(), ToAddress.c_str(), PropertyID, Amount, iAvailable, iUserAvailable);
2933 if (error_code) *error_code = rc;
2938 bool bCancel_checkBypass =
false;
2942 bCancel_checkBypass =
true;
2946 if ((((uint64_t)iAvailable < Amount) || (0 == Amount)) && !bCancel_checkBypass)
2948 LogPrintf(
"%s(): aborted -- not enough MP property (%lu < %lu)\n", __FUNCTION__, iAvailable, Amount);
2949 if (msc_debug_send) file_log(
"%s(): aborted -- not enough MP property (%lu < %lu)\n", __FUNCTION__, iAvailable, Amount);
2951 if (error_code) *error_code = rc;
2958 if (((iUserAvailable < (int64_t)Amount) || (0 == Amount)) && !bCancel_checkBypass)
2960 LogPrintf(
"%s(): aborted -- not enough MP property with PENDING reduction (%lu < %lu)\n", __FUNCTION__, iUserAvailable, Amount);
2961 if (msc_debug_send) file_log(
"%s(): aborted -- not enough MP property with PENDING reduction (%lu < %lu)\n", __FUNCTION__, iUserAvailable, Amount);
2964 if (error_code) *error_code = rc;
2969 vector<unsigned char>
data;
2978 if (PropertyID_2 != 0 || bCancel_checkBypass ==
true)
2981 unsigned char action = boost::lexical_cast<
int>(additional);
2993 rc =
ClassB_send(FromAddress, ToAddress, RedeemAddress, data, txid, additional);
2994 if (msc_debug_send) file_log(
"ClassB_send returned %d\n", rc);
2996 if (error_code) *error_code = rc;
3000 (void)
pendingAdd(txid, FromAddress, prop, amount);
3011 readoptions.fill_cache =
false;
3012 Iterator* it = pdb->NewIterator(readoptions);
3013 string lastAlertTxid;
3014 string lastAlertData;
3016 int64_t lastAlertBlock = 0;
3017 for(it->SeekToFirst(); it->Valid(); it->Next())
3020 svalue = it->value();
3021 string itData = svalue.ToString().c_str();
3022 std::vector<std::string> vstr;
3023 boost::split(vstr, itData, boost::is_any_of(
":"), token_compress_on);
3025 if (4 == vstr.size())
3029 if (
atoi(vstr[0]) == 1)
3031 if ( (
atoi(vstr[1]) > lastAlertBlock) && (
atoi(vstr[1]) < blockHeight) )
3033 lastAlertTxid = skey.ToString().c_str();
3034 lastAlertData = svalue.ToString().c_str();
3035 lastAlertBlock =
atoi(vstr[1]);
3044 if(lastAlertTxid.empty())
3046 file_log(
"DEBUG ALERT No alerts found to load\n");
3050 file_log(
"DEBUG ALERT Loading lastAlertTxid %s\n", lastAlertTxid);
3054 hash.
SetHex(lastAlertTxid);
3059 file_log(
"DEBUG ALERT Unable to load lastAlertTxid, transaction not found\n");
3065 string new_global_alert_message;
3068 if (0<=mp_obj.
step1())
3072 if (0 == mp_obj.
step2_Alert(&new_global_alert_message))
3089 std::vector<std::string> vstr;
3092 readoptions.fill_cache =
false;
3094 Iterator* it = pdb->NewIterator(readoptions);
3095 for(it->SeekToFirst(); it->Valid(); it->Next())
3098 svalue = it->value();
3099 string svalueStr = svalue.
ToString().c_str();
3100 boost::split(vstr, svalueStr, boost::is_any_of(
":"), token_compress_on);
3102 if (3 <= vstr.size())
3104 if (vstr[0] == txidStr) {
delete it; cancelTxid.
SetHex(skey.ToString().c_str());
return cancelTxid; }
3115 int numberOfCancels = 0;
3116 std::vector<std::string> vstr;
3118 Status status = pdb->Get(readoptions, txid.
ToString() +
"-C", &strValue);
3122 boost::split(vstr, strValue, boost::is_any_of(
":"), token_compress_on);
3124 if (4 <= vstr.size())
3126 numberOfCancels =
atoi(vstr[3]);
3129 return numberOfCancels;
3135 int numberOfPurchases = 0;
3136 std::vector<std::string> vstr;
3138 Status status = pdb->Get(readoptions, txid.
ToString(), &strValue);
3142 boost::split(vstr, strValue, boost::is_any_of(
":"), token_compress_on);
3144 if (4 <= vstr.size())
3146 numberOfPurchases =
atoi(vstr[3]);
3149 return numberOfPurchases;
3156 readoptions.fill_cache =
false;
3157 Iterator* it = pdb->NewIterator(readoptions);
3158 for(it->SeekToFirst(); it->Valid(); it->Next())
3161 if (skey.ToString().length() == 64) { ++count; }
3171 readoptions.fill_cache =
false;
3172 Iterator* it = pdb->NewIterator(readoptions);
3173 for(it->SeekToFirst(); it->Valid(); it->Next())
3176 svalue = it->value();
3177 if (skey.ToString().length() == 64)
3179 string strValue = svalue.ToString().c_str();
3180 std::vector<std::string> vstr;
3181 boost::split(vstr, strValue, boost::is_any_of(
":"), token_compress_on);
3182 if (4 == vstr.size())
3184 if (
atoi(vstr[1]) == block) { ++count; }
3194 if (!pdb)
return "";
3196 Status status = pdb->Get(readoptions, key, &strValue);
3197 if (status.ok()) {
return strValue; }
else {
return ""; }
3203 std::vector<std::string> vstr;
3205 Status status = pdb->Get(readoptions, txid.
ToString()+
"-"+to_string(purchaseNumber), &strValue);
3209 boost::split(vstr, strValue, boost::is_any_of(
":"), token_compress_on);
3211 if (5 == vstr.size())
3213 *vout =
atoi(vstr[0]);
3216 *propertyId =
atoi(vstr[3]);
3217 *nValue = boost::lexical_cast<boost::uint64_t>(vstr[4]);;
3229 unsigned int type = 99992104;
3230 unsigned int refNumber = 1;
3231 uint64_t existingAffectedTXCount = 0;
3232 string txidMasterStr = txidMaster.
ToString() +
"-C";
3237 std::vector<std::string> vstr;
3239 Status status = pdb->Get(readoptions, txidMasterStr, &strValue);
3243 boost::split(vstr, strValue, boost::is_any_of(
":"), token_compress_on);
3246 if (4 <= vstr.size())
3248 existingAffectedTXCount =
atoi(vstr[3]);
3249 refNumber = existingAffectedTXCount + 1;
3254 const string key = txidMasterStr;
3255 const string value =
strprintf(
"%u:%d:%u:%lu", fValid ? 1:0, nBlock, type, refNumber);
3256 file_log(
"METADEXCANCELDEBUG : Writing master record %s(%s, valid=%s, block= %d, type= %d, number of affected transactions= %d)\n", __FUNCTION__, txidMaster.
ToString().c_str(), fValid ?
"YES":
"NO", nBlock, type, refNumber);
3259 status = pdb->Put(writeoptions, key, value);
3260 file_log(
"METADEXCANCELDEBUG : %s(): %s, line %d, file: %s\n", __FUNCTION__, status.ToString().c_str(), __LINE__, __FILE__);
3264 const string txidStr = txidMaster.
ToString() +
"-C";
3266 const string subValue =
strprintf(
"%s:%d:%lu", txidSub.
ToString(), propertyId, nValue);
3268 file_log(
"METADEXCANCELDEBUG : Writing sub-record %s with value %s\n", subKey.c_str(), subValue.c_str());
3271 subStatus = pdb->Put(writeoptions, subKey, subValue);
3272 file_log(
"METADEXCANCELDEBUG : %s(): %s, line %d, file: %s\n", __FUNCTION__, subStatus.ToString().c_str(), __LINE__, __FILE__);
3281 unsigned int type = 99999999;
3282 uint64_t numberOfPayments = 1;
3283 unsigned int paymentNumber = 1;
3284 uint64_t existingNumberOfPayments = 0;
3291 if (paymentEntryExists)
3294 std::vector<std::string> vstr;
3296 Status status = pdb->Get(readoptions, txid.
ToString(), &strValue);
3300 boost::split(vstr, strValue, boost::is_any_of(
":"), token_compress_on);
3303 if (4 <= vstr.size())
3305 existingNumberOfPayments =
atoi(vstr[3]);
3306 paymentNumber = existingNumberOfPayments + 1;
3307 numberOfPayments = existingNumberOfPayments + 1;
3313 const string key = txid.
ToString();
3314 const string value =
strprintf(
"%u:%d:%u:%lu", fValid ? 1:0, nBlock, type, numberOfPayments);
3316 file_log(
"DEXPAYDEBUG : Writing master record %s(%s, valid=%s, block= %d, type= %d, number of payments= %lu)\n", __FUNCTION__, txid.
ToString().c_str(), fValid ?
"YES":
"NO", nBlock, type, numberOfPayments);
3319 status = pdb->Put(writeoptions, key, value);
3320 file_log(
"DEXPAYDEBUG : %s(): %s, line %d, file: %s\n", __FUNCTION__, status.ToString().c_str(), __LINE__, __FILE__);
3324 const string txidStr = txid.
ToString();
3326 const string subValue =
strprintf(
"%d:%s:%s:%d:%lu", vout, buyer, seller, propertyId, nValue);
3328 file_log(
"DEXPAYDEBUG : Writing sub-record %s with value %s\n", subKey.c_str(), subValue.c_str());
3331 subStatus = pdb->Put(writeoptions, subKey, subValue);
3332 file_log(
"DEXPAYDEBUG : %s(): %s, line %d, file: %s\n", __FUNCTION__, subStatus.ToString().c_str(), __LINE__, __FILE__);
3344 const string key = txid.
ToString();
3345 const string value =
strprintf(
"%u:%d:%u:%lu", fValid ? 1:0, nBlock, type, nValue);
3348 file_log(
"%s(%s, valid=%s, block= %d, type= %d, value= %lu)\n",
3349 __FUNCTION__, txid.
ToString().c_str(), fValid ?
"YES":
"NO", nBlock, type, nValue);
3353 status = pdb->Put(writeoptions, key, value);
3355 if (msc_debug_txdb) file_log(
"%s(): %s, line %d, file: %s\n", __FUNCTION__, status.ToString().c_str(), __LINE__, __FILE__);
3361 if (!pdb)
return false;
3364 Status status = pdb->Get(readoptions, txid.
ToString(), &strValue);
3368 if (status.IsNotFound())
return false;
3376 Status status = pdb->Get(readoptions, txid.
ToString(), &value);
3390 file_log(
"CMPTxList stats: nWritten= %d , nRead= %d\n", nWritten, nRead);
3398 readoptions.fill_cache =
false;
3400 Iterator* it = pdb->NewIterator(readoptions);
3402 for(it->SeekToFirst(); it->Valid(); it->Next())
3405 svalue = it->value();
3407 printf(
"entry #%8d= %s:%s\n", count, skey.ToString().c_str(), svalue.ToString().c_str());
3418 leveldb::Slice skey, svalue;
3419 unsigned int count = 0;
3420 std::vector<std::string> vstr;
3422 unsigned int n_found = 0;
3424 leveldb::Iterator* it = pdb->NewIterator(iteroptions);
3426 for(it->SeekToFirst(); it->Valid(); it->Next())
3429 svalue = it->value();
3435 string strvalue = it->value().ToString();
3438 boost::split(vstr, strvalue, boost::is_any_of(
":"), token_compress_on);
3441 if (2 <= vstr.size())
3443 block =
atoi(vstr[1]);
3445 if ((starting_block <= block) && (block <= ending_block))
3448 file_log(
"%s() DELETING: %s=%s\n", __FUNCTION__, skey.ToString().c_str(), svalue.ToString().c_str());
3449 if (bDeleteFound) pdb->Delete(writeoptions, skey);
3454 printf(
"%s(%d, %d); n_found= %d\n", __FUNCTION__, starting_block, ending_block, n_found);
3464 if (!sdb)
return "";
3465 string mySTOReceipts =
"";
3468 readoptions.fill_cache =
false;
3469 Iterator* it = sdb->NewIterator(readoptions);
3470 for(it->SeekToFirst(); it->Valid(); it->Next())
3473 string recipientAddress = skey.ToString();
3475 if((!filterAddress.empty()) && (filterAddress != recipientAddress))
continue;
3477 svalue = it->value();
3478 string strValue = svalue.ToString();
3480 std::vector<std::string> vstr;
3481 boost::split(vstr, strValue, boost::is_any_of(
","), token_compress_on);
3482 for(uint32_t i = 0; i<vstr.size(); i++)
3485 std::vector<std::string> svstr;
3486 boost::split(svstr, vstr[i], boost::is_any_of(
":"), token_compress_on);
3487 if(4 == svstr.size())
3489 size_t txidMatch = mySTOReceipts.find(svstr[0]);
3490 if(txidMatch==std::string::npos) mySTOReceipts += svstr[0]+
":"+svstr[1]+
":"+recipientAddress+
":"+svstr[2]+
",";
3495 return mySTOReceipts;
3503 bool filterByWallet =
true;
3504 bool filterByAddress =
false;
3506 if (filterAddress ==
"*") filter =
false;
3507 if ((filterAddress !=
"") && (filterAddress !=
"*")) { filterByWallet =
false; filterByAddress =
true; }
3517 readoptions.fill_cache =
false;
3518 Iterator* it = sdb->NewIterator(readoptions);
3519 for(it->SeekToFirst(); it->Valid(); it->Next())
3522 string recipientAddress = skey.ToString();
3523 svalue = it->value();
3524 string strValue = svalue.ToString();
3526 size_t txidMatch = strValue.find(txid.
ToString());
3527 if(txidMatch!=std::string::npos)
3533 if( ( (filterByAddress) && (filterAddress == recipientAddress) ) || ( (filterByWallet) && (
IsMyAddress(recipientAddress)) ) )
3534 { }
else {
continue; }
3536 std::vector<std::string> vstr;
3537 boost::split(vstr, strValue, boost::is_any_of(
","), token_compress_on);
3538 for(uint32_t i = 0; i<vstr.size(); i++)
3540 std::vector<std::string> svstr;
3541 boost::split(svstr, vstr[i], boost::is_any_of(
":"), token_compress_on);
3542 if(4 == svstr.size())
3547 uint64_t amount = 0;
3548 uint64_t propertyId = 0;
3551 amount = boost::lexical_cast<uint64_t>(svstr[3]);
3552 propertyId = boost::lexical_cast<uint64_t>(svstr[2]);
3553 }
catch (
const boost::bad_lexical_cast &e)
3555 file_log(
"DEBUG STO - error in converting values from leveldb\n");
3560 recipient.push_back(Pair(
"address", recipientAddress));
3570 recipientArray->push_back(recipient);
3584 if (!sdb)
return false;
3587 Status status = sdb->Get(readoptions, address, &strValue);
3591 if (status.IsNotFound())
return false;
3605 std::vector<std::string> vstr;
3607 Status status = sdb->Get(readoptions, address, &strValue);
3612 size_t txidMatch = strValue.find(txid.
ToString());
3613 if(txidMatch!=std::string::npos) file_log(
"STODEBUG : Duplicating entry for %s : %s\n",address,txid.
ToString());
3615 const string key = address;
3616 const string newValue =
strprintf(
"%s:%d:%u:%lu,", txid.
ToString(), nBlock, propertyId, amount);
3617 strValue += newValue;
3622 status = sdb->Put(writeoptions, key, strValue);
3623 file_log(
"STODBDEBUG : %s(): %s, line %d, file: %s\n", __FUNCTION__, status.ToString().c_str(), __LINE__, __FILE__);
3629 const string key = address;
3630 const string value =
strprintf(
"%s:%d:%u:%lu,", txid.
ToString(), nBlock, propertyId, amount);
3634 status = sdb->Put(writeoptions, key, value);
3635 file_log(
"STODBDEBUG : %s(): %s, line %d, file: %s\n", __FUNCTION__, status.ToString().c_str(), __LINE__, __FILE__);
3645 readoptions.fill_cache =
false;
3647 Iterator* it = sdb->NewIterator(readoptions);
3649 for(it->SeekToFirst(); it->Valid(); it->Next())
3652 svalue = it->value();
3654 printf(
"entry #%8d= %s:%s\n", count, skey.ToString().c_str(), svalue.ToString().c_str());
3662 file_log(
"CMPSTOList stats: tWritten= %d , tRead= %d\n", sWritten, sRead);
3668 leveldb::Slice skey, svalue;
3669 unsigned int count = 0;
3670 std::vector<std::string> vstr;
3671 unsigned int n_found = 0;
3672 leveldb::Iterator* it = sdb->NewIterator(iteroptions);
3673 for(it->SeekToFirst(); it->Valid(); it->Next())
3676 string address = skey.ToString();
3677 svalue = it->value();
3679 string strvalue = it->value().ToString();
3680 boost::split(vstr, strvalue, boost::is_any_of(
","), token_compress_on);
3681 string newValue =
"";
3682 bool needsUpdate =
false;
3683 for(uint32_t i = 0; i<vstr.size(); i++)
3685 std::vector<std::string> svstr;
3686 boost::split(svstr, vstr[i], boost::is_any_of(
":"), token_compress_on);
3687 if(4 == svstr.size())
3689 if(
atoi(svstr[1]) <= blockNum) { newValue += vstr[i]; }
else { needsUpdate =
true; }
3696 const string key = address;
3701 status = sdb->Put(writeoptions, key, newValue);
3702 file_log(
"DEBUG STO - rewriting STO data after reorg\n");
3703 file_log(
"STODBDEBUG : %s(): %s, line %d, file: %s\n", __FUNCTION__, status.ToString().c_str(), __LINE__, __FILE__);
3708 printf(
"%s(%d); stodb n_found= %d\n", __FUNCTION__, blockNum, n_found);
3718 if (!tdb)
return false;
3719 leveldb::Slice skey, svalue;
3720 unsigned int count = 0;
3721 std::vector<std::string> vstr;
3723 leveldb::Iterator* it = tdb->NewIterator(iteroptions);
3724 for(it->SeekToFirst(); it->Valid(); it->Next())
3727 svalue = it->value();
3728 string strkey = it->key().ToString();
3729 size_t txidMatch = strkey.find(txidStr);
3730 if(txidMatch!=std::string::npos)
3736 if (strkey.length() == 129)
3738 if (txidMatch==0) { matchTxid = strkey.substr(65,64); }
else { matchTxid = strkey.substr(0,64); }
3740 string strvalue = it->value().ToString();
3741 boost::split(vstr, strvalue, boost::is_any_of(
":"), token_compress_on);
3742 if (7 == vstr.size())
3745 string address1 = vstr[0];
3746 string address2 = vstr[1];
3747 unsigned int prop1 = 0;
3748 unsigned int prop2 = 0;
3749 uint64_t uAmount1 = 0;
3750 uint64_t uAmount2 = 0;
3751 uint64_t nBought = 0;
3753 string amountBought;
3757 prop1 = boost::lexical_cast<
unsigned int>(vstr[2]);
3758 prop2 = boost::lexical_cast<
unsigned int>(vstr[3]);
3759 uAmount1 = boost::lexical_cast<uint64_t>(vstr[4]);
3760 uAmount2 = boost::lexical_cast<uint64_t>(vstr[5]);
3771 if (prop1 == propertyId)
3774 amountBought = amount2;
3775 amountSold = amount1;
3782 amountBought = amount1;
3783 amountSold = amount2;
3787 int blockNum =
atoi(vstr[6]);
3789 trade.push_back(Pair(
"txid", matchTxid));
3790 trade.push_back(Pair(
"address", address));
3791 trade.push_back(Pair(
"block", blockNum));
3792 trade.push_back(Pair(
"amountsold", amountSold));
3793 trade.push_back(Pair(
"amountbought", amountBought));
3794 tradeArray->push_back(trade);
3796 *totalBought += nBought;
3797 *totalSold += nSold;
3803 if (count) {
return true; }
else {
return false; }
3810 const string value =
strprintf(
"%s:%s:%u:%u:%lu:%lu:%d", address1, address2, prop1, prop2, amount1, amount2, blockNum);
3814 status = tdb->Put(writeoptions, key, value);
3816 if (msc_debug_tradedb) file_log(
"%s(): %s\n", __FUNCTION__, status.ToString().c_str());
3823 leveldb::Slice skey, svalue;
3824 unsigned int count = 0;
3825 std::vector<std::string> vstr;
3827 unsigned int n_found = 0;
3828 leveldb::Iterator* it = tdb->NewIterator(iteroptions);
3829 for(it->SeekToFirst(); it->Valid(); it->Next())
3832 svalue = it->value();
3834 string strvalue = it->value().ToString();
3835 boost::split(vstr, strvalue, boost::is_any_of(
":"), token_compress_on);
3837 if (7 == vstr.size())
3839 block =
atoi(vstr[6]);
3841 if (block >= blockNum)
3844 file_log(
"%s() DELETING FROM TRADEDB: %s=%s\n", __FUNCTION__, skey.ToString().c_str(), svalue.ToString().c_str());
3845 tdb->Delete(writeoptions, skey);
3850 printf(
"%s(%d); tradedb n_found= %d\n", __FUNCTION__, blockNum, n_found);
3859 file_log(
"CMPTradeList stats: tWritten= %d , tRead= %d\n", tWritten, tRead);
3866 readoptions.fill_cache =
false;
3867 Iterator* it = tdb->NewIterator(readoptions);
3868 for(it->SeekToFirst(); it->Valid(); it->Next())
3881 readoptions.fill_cache =
false;
3883 Iterator* it = tdb->NewIterator(readoptions);
3885 for(it->SeekToFirst(); it->Valid(); it->Next())
3888 svalue = it->value();
3890 printf(
"entry #%8d= %s:%s\n", count, skey.ToString().c_str(), svalue.ToString().c_str());
3901 if (0 == ending_block) ending_block =
GetHeight();
3918 if (msc_debug_txdb) file_log(
"%s()\n", __FUNCTION__);
3925 std::vector<std::string> vstr;
3926 boost::split(vstr, result, boost::is_any_of(
":"), token_compress_on);
3928 file_log(
"%s() size=%lu : %s\n", __FUNCTION__, vstr.size(), result.c_str());
3930 if (1 <= vstr.size()) validity =
atoi(vstr[0]);
3934 if (2 <= vstr.size()) *block =
atoi(vstr[1]);
3940 if (3 <= vstr.size()) *type =
atoi(vstr[2]);
3946 if (4 <= vstr.size()) *nAmended = boost::lexical_cast<boost::uint64_t>(vstr[3]);
3952 if ((
int)0 == validity)
return false;
3962 std::vector<unsigned char> vch;
3963 const_iterator pc = begin();
3970 if (!GetOp(pc, opcode, vch))
3978 if (count || bNoBypass) msc_parsed.push_back(
ValueString(vch));
3990 if (reorgRecoveryMode > 0) {
3991 reorgRecoveryMode = 0;
3998 reorgRecoveryMaxHeight = 0;
4008 if (best_state_block < 0) {
4012 nWaterlineBlock = best_state_block;
4016 if (nWaterlineBlock < nBlockPrev) {
4023 if (nBlockTop < nBlockPrev + 1)
4035 unsigned int countMP) {
4036 if (!mastercoreInitialized) {
4041 if (nBlockTop < nBlockNow)
4047 uint64_t devmsc = 0;
4050 if (how_many_erased)
4051 file_log(
"%s(%d); erased %u accepts this block, line %d, file: %s\n",
4052 __FUNCTION__, how_many_erased, nBlockNow, __LINE__, __FILE__);
4058 file_log(
"devmsc for block %d: %lu, Exodus balance: %lu\n", nBlockNow,
4076 reorgRecoveryMode = 1;
4092 static const string addr =
"1MpNote1jsHkbQLwEmgoMr29EoUC1nyxxV";
4120 std::string new_global_alert_message;
4122 if (0>step1())
return -98765;
4132 step_rc = step2_Value();
4133 if (0>step_rc)
return step_rc;
4135 rc = logicMath_SimpleSend();
4139 step_rc = step2_Value();
4140 if (0>step_rc)
return step_rc;
4142 rc = logicMath_TradeOffer(obj_o);
4146 step_rc = step2_Value();
4147 if (0>step_rc)
return step_rc;
4149 rc = logicMath_AcceptOffer_BTC();
4154 const char *p = step2_SmartProperty(step_rc);
4155 if (0>step_rc)
return step_rc;
4158 step_rc = step3_sp_fixed(p);
4159 if (0>step_rc)
return step_rc;
4170 newSP.
name.assign(name);
4176 const unsigned int id =
_my_sps->
putSP(ecosystem, newSP);
4185 const char *p = step2_SmartProperty(step_rc);
4186 if (0>step_rc)
return step_rc;
4189 step_rc = step3_sp_variable(p);
4190 if (0>step_rc)
return step_rc;
4207 newSP.
name.assign(name);
4210 newSP.
fixed =
false;
4217 const unsigned int id =
_my_sps->
putSP(ecosystem, newSP);
4218 my_crowds.insert(std::make_pair(sender,
CMPCrowd(
id, nValue, property, deadline, early_bird, percentage, 0, 0)));
4219 file_log(
"CREATED CROWDSALE id: %u value: %lu property: %u\n",
id, nValue, property);
4227 CrowdMap::iterator it =
my_crowds.find(sender);
4232 memcpy(&property, &pkt[4], 4);
4235 if (msc_debug_sp) file_log(
"%s() trying to ERASE CROWDSALE for propid= %u=%X\n", __FUNCTION__, property, property);
4238 if ((it->second).getPropertyId() != property)
4284 const char *p = step2_SmartProperty(step_rc);
4285 if (0>step_rc)
return step_rc;
4296 newSP.
name.assign(name);
4299 newSP.
fixed =
false;
4302 const unsigned int id =
_my_sps->
putSP(ecosystem, newSP);
4303 file_log(
"CREATED MANUAL PROPERTY id: %u admin: %s \n",
id, sender.c_str());
4310 step_rc = step2_Value();
4311 if (0>step_rc)
return step_rc;
4313 rc = logicMath_GrantTokens();
4317 step_rc = step2_Value();
4318 if (0>step_rc)
return step_rc;
4320 rc = logicMath_RevokeTokens();
4324 if (disable_Divs)
break;
4327 step_rc = step2_Value();
4328 if (0>step_rc)
return step_rc;
4331 FILE *fp = fopen(pathOwners.string().c_str(),
"a");
4339 file_log(
"\nPROBLEM writing %s, errno= %d\n",
OWNERS_FILENAME, errno);
4342 rc = logicMath_SendToOwners(fp);
4359 if (307057 > block)
return -31337;
4361 step_rc = step2_Value();
4362 if (0>step_rc)
return step_rc;
4364 rc = logicMath_MetaDEx(mdex_o);
4369 memcpy(&property, &pkt[4], 4);
4372 rc = logicMath_ChangeIssuer();
4376 rc = logicMath_SavingsMark();
4380 rc = logicMath_SavingsCompromised();
4385 if ((
int)version == 65535)
4387 rc = step2_Alert(&new_global_alert_message);
4408 if (sender.empty()) ++invalid;
4412 if (receiver.empty())
4416 if (receiver.empty()) ++invalid;
4432 if (crowd && (crowd->
getCurrDes() == property) )
4437 file_log(
"INVESTMENT SEND to Crowdsale Issuer: %s\n", receiver.c_str());
4442 std::pair <uint64_t,uint64_t> tokens;
4444 bool close_crowdsale =
false;
4457 nValue = nValue * 1e8;
4467 (uint64_t) blockTime,
4484 uint64_t txdata[] = { (uint64_t) nValue, (uint64_t) blockTime, (uint64_t) tokens.first, (uint64_t) tokens.second };
4486 std::vector<uint64_t> txDataVec(txdata, txdata +
sizeof(txdata)/
sizeof(txdata[0]) );
4498 if( close_crowdsale ) {
4519 file_log(
"\t Total Tokens: %s\n",
FormatMP(property, totalTokens).c_str());
4521 if (0 >= totalTokens)
4535 OwnerAddrType OwnerAddrSet;
4540 const string address = (my_it->first).c_str();
4543 if (address == sender)
continue;
4554 OwnerAddrSet.insert(make_pair(tokens, address));
4555 totalTokens += tokens;
4560 file_log(
" Excluding Sender: %s\n",
FormatMP(property, totalTokens).c_str());
4565 uint64_t n_owners = 0;
4568 for (
unsigned int itern=0;itern<=1;itern++)
4571 uint64_t owns, should_receive, will_really_receive, sent_so_far = 0;
4572 double percentage, piece;
4573 for(OwnerAddrType::reverse_iterator my_it = OwnerAddrSet.rbegin(); my_it != OwnerAddrSet.rend(); ++my_it)
4575 const string address = my_it->second;
4577 owns = my_it->first;
4578 percentage = (double) owns / (
double) totalTokens;
4579 piece = percentage * nValue;
4580 should_receive = ceil(piece);
4583 if ((nValue - sent_so_far) < should_receive)
4585 will_really_receive = nValue - sent_so_far;
4589 will_really_receive = should_receive;
4592 sent_so_far += will_really_receive;
4607 if (sent_so_far >= nValue)
4609 file_log(
"SendToOwners: DONE HERE : those who could get paid got paid, SOME DID NOT, but that's ok\n");
4619 file_log(
"%14lu = %s, perc= %20.10lf, piece= %20.10lf, should_get= %14lu, will_really_get= %14lu, sent_so_far= %14lu\n",
4620 owns, address.c_str(), percentage, piece, should_receive, will_really_receive, sent_so_far);
4623 if (fhandle) fprintf(fhandle,
"%s = %s\n", address.c_str(),
FormatMP(property, will_really_receive).c_str());
4635 file_log(
"\t Owners: %lu\n", n_owners);
4638 file_log(
"\t Transfer fee: %lu.%08lu %s\n", nXferFee/
COIN, nXferFee%
COIN,
strMPProperty(feeProperty).c_str());
4647 if (feeProperty == property)
4664 if (sent_so_far != nValue)
4666 file_log(
"sent_so_far= %14lu, nValue= %14lu, n_owners= %lu\n", sent_so_far, nValue, n_owners);
uint32_t GetLatestBlockTime(void)
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
std::string mscore_parse(std::vector< std::string > &msc_parsed, bool bNoBypass=true) const
int popBlock(uint256 const &block_hash)
int getNumberOfPurchases(const uint256 txid)
void SetHex(const char *psz)
uint64_t GetRand(uint64_t nMax)
const int msc_debug_script
uint64_t global_MSC_total
static int64_t selectCoins(const string &FromAddress, CCoinControl &coinControl, int64_t additional)
#define OMNICORE_VERSION_BASE
static char const *const statePrefix[NUM_FILETYPES]
string global_alert_message
static string exodus_address
int mastercore_handler_disc_begin(int nBlockNow, CBlockIndex const *pBlockIndex)
void saveAccept(ofstream &file, SHA256_CTX *shaCtx, string const &addr, string const &buyer) const
void Set(const uint256 &t, int b, unsigned int idx, int64_t bt)
bool isTestEcosystemProperty(unsigned int property)
int input_globals_state_string(const string &s)
static void prune_state_files(CBlockIndex const *topIndex)
const_iterator begin() const
static uint64_t exodus_prev
static PendingMap my_pending
int deleteAboveBlock(int blockNum)
int ClassB_send(const string &senderAddress, const string &receiverAddress, const string &redemptionAddress, const vector< unsigned char > &data, uint256 &txid, int64_t additional=0)
bool getTX(const uint256 &txid, string &value)
static int write_mp_metadex(ofstream &file, SHA256_CTX *shaCtx)
std::map< CTxDestination, CAddressBookData > mapAddressBook
static int reorgRecoveryMaxHeight
CCriticalSection cs_wallet
Main wallet lock.
static uint64_t exodus_balance
static int write_globals_state(ofstream &file, SHA256_CTX *shaCtx)
md_PricesMap * get_Prices(unsigned int prop)
bool isMainEcosystemProperty(unsigned int property)
int input_msc_balances_string(const string &s)
bool exists(const uint256 &txid)
static int write_state_file(CBlockIndex const *pBlockIndex, int what)
int mastercore_handler_tx(const CTransaction &tx, int nBlock, unsigned int idx, CBlockIndex const *pBlockIndex)
void init(unsigned int nextSPID=0x3UL, unsigned int nextTestSPID=TEST_ECO_PROPERTY_1)
int parseTransaction(bool bRPConly, const CTransaction &wtx, int nBlock, unsigned int idx, CMPTransaction *mp_tx, unsigned int nTime)
int logicMath_SimpleSend(void)
bool exists(string address)
bool update_tally_map(string who, unsigned int which_currency, int64_t amount, TallyType ttype)
uint64_t getCurrDes() const
std::string ToString() const
cpp_dec_float_100 XDOUBLE
bool getMatchingTrades(const uint256 txid, unsigned int propertyId, Array *tradeArray, uint64_t *totalSold, uint64_t *totalBought)
void swapByteOrder32(uint32_t &ui)
void recordMetaDExCancelTX(const uint256 &txidMaster, const uint256 &txidSub, bool fValid, int nBlock, unsigned int propertyId, uint64_t nValue)
static bool readPersistence()
const int msc_debug_verbose
bool isMultiplicationOK(const uint64_t a, const uint64_t b)
#define STR_PAYMENT_SUBKEY_TXID_PAYMENT_COMBO(txidStr)
CMPTally * getTally(const string &address)
void saveCrowdSale(ofstream &file, SHA256_CTX *shaCtx, string const &addr) const
uint64_t global_balance_reserved_testeco[100000]
void getRecipients(const uint256 txid, string filterAddress, Array *recipientArray, uint64_t *total, uint64_t *stoFee)
#define TEST_ECO_PROPERTY_1
Double ended buffer combining vector and stream-like interfaces.
static const int disableLevelDB
const int msc_debug_tally
#define STR_ACCEPT_ADDR_PROP_ADDR_COMBO(_seller, _buyer)
bool hasSP(unsigned int spid)
base58-encoded Bitcoin addresses.
std::map< string, CMPOffer > OfferMap
std::map< std::string, std::vector< uint64_t > > getDatabase() const
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
const int msc_debug_verbose3
static const string getmoney_testnet
std::map< string, CMPCrowd > CrowdMap
static bool isRangeOK(const uint64_t input)
CTxDestination Get() const
#define OMNI_PROPERTY_MSC
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
CChain chainActive
The currently-connected chain of blocks.
#define PUSH_BACK_BYTES(vector, value)
Pushes bytes to the end of a vector.
bool isPropertyDivisible(unsigned int propertyId)
unsigned int property_desired
volatile bool fReopenDebugLog
int deleteAboveBlock(int blockNum)
std::map< std::string, std::vector< uint64_t > > historicalData
int mastercore_handler_disc_end(int nBlockNow, CBlockIndex const *pBlockIndex)
std::string p_arb(cpp_int quantity)
int mastercore_handler_block_begin(int nBlockPrev, CBlockIndex const *pBlockIndex)
static const int disable_Divs
void recordPaymentTX(const uint256 &txid, bool fValid, int nBlock, unsigned int vout, unsigned int propertyId, uint64_t nValue, string buyer, string seller)
bool GetKeyID(CKeyID &keyID) const
unsigned int eraseExpiredAccepts(int blockNow)
void SetDestination(const CTxDestination &address)
int getNumberOfMetaDExCancels(const uint256 txid)
int input_mp_offers_string(const string &s)
bool IsMyAddress(const std::string &address)
int calculateFractional(unsigned short int propType, unsigned char bonusPerc, uint64_t fundraiserSecs, uint64_t numProps, unsigned char issuerPerc, const std::map< std::string, std::vector< uint64_t > > txFundraiserData, const uint64_t amountPremined)
std::string ValueString(const std::vector< unsigned char > &vch)
int input_mp_accepts_string(const string &s)
bool CreateTransaction(const std::vector< std::pair< CScript, int64_t > > &vecSend, CWalletTx &wtxNew, CReserveKey &reservekey, int64_t &nFeeRet, std::string &strFailReason, const CCoinControl *coinControl=NULL)
static bool writePersistence(int block_now)
int step2_Alert(std::string *new_global_alert_message)
#define OMNI_PROPERTY_TMSC
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
bool getValidMPTX(const uint256 &txid, int *block=NULL, unsigned int *type=NULL, uint64_t *nAmended=NULL)
static int write_msc_balances(ofstream &file, SHA256_CTX *shaCtx)
uint64_t getIssuerCreated() const
int Height() const
Return the maximal height in the chain.
opcodetype
Script opcodes.
void dumpCrowdsaleInfo(const string &address, CMPCrowd &crowd, bool bExpired=false)
bool IsSpent(const uint256 &hash, unsigned int n) const
int TXExodusFundraiser(const CTransaction &wtx, const string &sender, int64_t ExodusHighestValue, int nBlock, unsigned int nTime)
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
bool isMPinBlockRange(int, int, bool)
int getMPTradeCountTotal()
string getLabel(const string &address)
unsigned int GetSerializeSize(char a, int, int=0)
int DEx_payment(uint256 txid, unsigned int vout, string seller, string buyer, uint64_t BTC_paid, int blockNow, uint64_t *nAmended=NULL)
const int msc_debug_parser
const std::string NotificationAddress()
CMPTradeList * t_tradelistdb
static boost::filesystem::path MPPersistencePath
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)
std::vector< CTxOut > vout
uint64_t rounduint64(long double ld)
Converts numbers to 64 bit wide unsigned integer whereby any signedness is ignored.
CTxDestination destChange
int setLastAlert(int blockHeight)
static const int txRestrictionsRules[][3]
bool updateMoney(unsigned int which_property, int64_t amount, TallyType ttype)
An encapsulated public key.
int64_t GetDustLimit(const CScript &scriptPubKey)
#define OMNI_PROPERTY_BTC
uint64_t global_balance_money_testeco[100000]
bool isMPinBlockRange(int starting_block, int ending_block, bool bDeleteFound)
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, vector< vector< unsigned char > > &vSolutionsRet)
std::map< string, CMPTally > mp_tally_map
uint64_t getNewAmount() const
bool CommitTransaction(CWalletTx &wtxNew, CReserveKey &reservekey)
bool isMetaDExOfferActive(const uint256 txid, unsigned int propertyId)
static int pendingAdd(const uint256 &txid, const string &FromAddress, unsigned int propId, int64_t Amount)
void print(uint256 txid) const
std::string ToString() const
int64_t feeCheck(const string &address)
void recordSTOReceive(std::string, const uint256 &, int, unsigned int, uint64_t)
bool getSP(unsigned int spid, Entry &info)
uint64_t global_balance_reserved_maineco[100000]
uint256 send_INTERNAL_1packet(const string &FromAddress, const string &ToAddress, const string &RedeemAddress, unsigned int PropertyID, uint64_t Amount, unsigned int PropertyID_2, uint64_t Amount_2, unsigned int TransactionType, int64_t additional, int *error_code=NULL)
static const string exodus_testnet
const int msc_debug_parser_data
std::map< XDOUBLE, md_Set > md_PricesMap
An outpoint - a combination of a transaction hash and an index n into its vout.
static bool is_state_prefix(std::string const &str)
std::string GetHex() const
uint256 findMetaDExCancel(const uint256 txid)
static CMPPending * pendingDelete(const uint256 txid, bool bErase=false)
std::string ToString() const
int64_t getTotalTokens(unsigned int propertyId, int64_t *n_owners_total=NULL)
static int write_mp_accepts(ofstream &file, SHA256_CTX *shaCtx)
const unsigned char * begin() const
CCriticalSection cs_tally
const char * GetOpName(opcodetype opcode)
int mastercore_save_state(CBlockIndex const *pBlockIndex)
virtual const CBlock & GenesisBlock() const =0
bool SetString(const char *psz, unsigned int nVersionBytes=1)
#define STR_REF_SUBKEY_TXID_REF_COMBO(txidStr)
A transaction with a bunch of additional info that only the owner cares about.
void eraseMaxedCrowdsale(const string &address, uint64_t blockTime, int block)
std::string p128(int128_t quantity)
#define PACKET_SIZE_CLASS_A
void insertDatabase(std::string txhash, std::vector< uint64_t > txdata)
string getKeyValue(string key)
static int reorgRecoveryMode
#define TRANSFER_FEE_PER_OWNER
static int nWaterlineBlock
static const int64_t COIN
std::set< CMPMetaDEx, MetaDEx_compare > md_Set
bool getPurchaseDetails(const uint256 txid, int purchaseNumber, string *buyer, string *seller, uint64_t *vout, uint64_t *propertyId, uint64_t *nValue)
void setWatermark(uint256 const &watermark)
static int write_mp_offers(ofstream &file, SHA256_CTX *shaCtx)
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
const int msc_debug_persistence
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, vector< CTxDestination > &addressRet, int &nRequiredRet)
unsigned int putSP(unsigned char ecosystem, Entry const &info)
void saveOffer(ofstream &file, SHA256_CTX *shaCtx, string const &addr) const
string strMPProperty(unsigned int i)
A key allocated from the key pool.
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
void recordTX(const uint256 &txid, bool fValid, int nBlock, unsigned int type, uint64_t nValue)
Serialized script, used inside transaction inputs and outputs.
void * memcpy(void *a, const void *b, size_t c)
void Select(COutPoint &output)
std::string ToString() const
uint64_t global_MSC_RESERVED_total
static const int PROTOCOL_VERSION
md_Set * get_Indexes(md_PricesMap *p, XDOUBLE price)
static int mastercoreInitialized
void SetMultisig(int nRequired, const std::vector< CPubKey > &keys)
int getMPTransactionCountBlock(int block)
static boost::once_flag mp_debugPrintInitFlag
const std::string ExodusAddress()
bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
int getWatermark(uint256 &watermark)
A reference to a CKey: the Hash160 of its serialized public key.
std::string FormatIndivisibleMP(int64_t n)
const int msc_debug_tokens
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
int msc_initial_scan(int nHeight)
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
unsigned int peekNextSPID(unsigned char ecosystem)
static bool isAllowedOutputType(int whichType, int nBlock)
bool IsFullyValid() const
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
Retrieve a transaction (from memory pool, or from disk, if possible)
void incTokensUserCreated(uint64_t amount)
static string const watermarkKey
CMPCrowd * getCrowd(const string &address)
static int msc_file_load(const string &filename, int what, bool verifyHash=false)
const int msc_debug_verbose2
std::map< uint256, CWalletTx > mapWallet
std::string FormatMP(unsigned int property, int64_t n, bool fSign)
string FormatDivisibleMP(int64_t n, bool fSign)
static int64_t nMinRelayTxFee
Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) ...
int const MAX_STATE_HISTORY
void incTokensIssuerCreated(uint64_t amount)
static void clear_all_state()
static int load_most_relevant_state()
std::vector< CTransaction > vtx
#define MAX_SHA256_OBFUSCATION_TIMES
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
static boost::mutex * mutexDebugLog
static const int nBlockTop
int64_t GetAvailableCredit(bool fUseCache=true) const
The basic transaction that is broadcasted on the network and contained in blocks. ...
std::string getMasterCoreAlertString()
static int write_mp_crowdsales(ofstream &file, SHA256_CTX *shaCtx)
uint64_t calculate_and_update_devmsc(unsigned int nTime)
static const CCheckpointData data
int input_mp_crowdsale_string(const string &s)
int getMPTransactionCountTotal()
unsigned int eraseExpiredCrowdsale(CBlockIndex const *pBlockIndex)
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
int64_t GetBlockTime() const
static void shrinkDebugFile()
#define STR_SELLOFFER_ADDR_PROP_COMBO(x)
bool checkExpiredAlerts(unsigned int curBlock, uint64_t curTime)
int mastercore_shutdown()
unsigned int updateSP(unsigned int propertyID, Entry const &info)
static void mp_DebugPrintInit()
unsigned int getPropertyId() const
map< uint256, CBlockIndex * > mapBlockIndex
vector< unsigned char > ParseHex(const char *psz)
int64_t getMPbalance(const string &Address, unsigned int property, TallyType ttype)
int interpretPacket(CMPOffer *obj_o=NULL, CMPMetaDEx *mdex_o=NULL)
std::map< uint256, CMPPending > PendingMap
void swapByteOrder64(uint64_t &ull)
static void prepareObfuscatedHashes(const string &address, string(&ObfsHashes)[1+MAX_SHA256_OBFUSCATION_TIMES])
const unsigned char * end() const
int64_t getUserAvailableMPbalance(const string &Address, unsigned int property)
std::string getMySTOReceipts(string filterAddress)
std::map< string, CMPAccept > AcceptMap
static bool getOutputType(const CScript &scriptPubKey, txnouttype &whichTypeRet)
const int msc_debug_tradedb
uint64_t global_balance_money_maineco[100000]
int mp_LogPrintStr(const std::string &str)
bool isTransactionTypeAllowed(int txBlock, unsigned int txProperty, unsigned int txType, unsigned short version, bool bAllowNullProperty=false)
int atoi(const std::string &str)
uint256 GetBlockHash() const
void recordTrade(const uint256 txid1, const uint256 txid2, string address1, string address2, unsigned int prop1, unsigned int prop2, uint64_t amount1, uint64_t amount2, int blockNum)
const_iterator end() const
int logicMath_SendToOwners(FILE *fp=NULL)
int mastercore_handler_block_end(int nBlockNow, CBlockIndex const *pBlockIndex, unsigned int countMP)
unsigned int getType() const
const uint256 * phashBlock