forked from gridcoin/Gridcoin-master
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
8810 lines (7014 loc) · 268 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "alert.h"
#include "checkpoints.h"
#include "db.h"
#include "txdb.h"
#include "net.h"
#include <math.h> /* pow */
#include "init.h"
#include "ui_interface.h"
#include "checkqueue.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <ctime>
#include <openssl/md5.h>
#include <boost/lexical_cast.hpp>
#include "global_objects_noui.hpp"
#include "bitcoinrpc.h"
#include "hashgroestl.h"
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/algorithm/string/join.hpp>
//Resend Unsent Tx
#include <leveldb/env.h>
#include <leveldb/cache.h>
#include <leveldb/filter_policy.h>
using namespace std;
using namespace boost;
//
// Global state
//
volatile bool bNetAveragesLoaded;
volatile bool bAllowBackToBack;
volatile bool bRestartGridcoinMiner;
volatile bool bForceUpdate;
int miningAlgo = ALGO_SHA256D;
leveldb::DB *txdb; // global pointer for LevelDB object instance
extern void PobSleep(int milliseconds);
extern bool CheckWorkCPU(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
extern double Lederstrumpf(double RAC, double NetworkRAC);
extern double cdbl(std::string s, int place);
extern double GetBlockValueByHash(uint256 hash);
extern void WriteAppCache(std::string key, std::string value);
extern std::string AppCache(std::string key);
void RestartGridcoin3();
void StartPostOnBackgroundThread(int height, MiningCPID miningcpid, uint256 hashmerkleroot, double nNonce, double subsidy, unsigned int nVersion, std::string message);
extern void LoadCPIDsInBackground();
bool SubmitGridcoinCPUWork(CBlock* pblock, CReserveKey& reservekey, double nonce);
CBlock* getwork_cpu(MiningCPID miningcpid, bool& succeeded,CReserveKey& reservekey);
extern int GetBlockType(uint256 prevblockhash);
extern void PoBGPUMiner(CBlock* pblock, MiningCPID& miningcpid);
extern bool GetTransactionFromMemPool(const uint256 &hash, CTransaction &txOut);
extern unsigned int DiffBytes(double PoBDiff);
extern int Races(int iMax1000);
int ReindexWallet();
std::string cached_getblocks_args = "";
extern bool AESSkeinHash(unsigned int diffbytes, double rac, uint256 scrypthash, std::string& out_skein, std::string& out_aes512);
std::string DefaultGetblocksCommand();
extern int TestAESHash(double rac, unsigned int diffbytes, uint256 scrypt_hash, std::string aeshash);
CClientUIInterface uiDog;
std::string DefaultBoincHashArgs();
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
double nPoolMiningCounter = 0;
extern double CreditCheck(std::string cpid, std::string projectname);
extern void ThreadCPIDs();
extern std::string GetGlobalStatus();
CBlockIndex* GetBlockIndex2(uint256 blockhash, int& out_height);
extern void printbool(std::string comment, bool boo);
extern void PobSleep(int milliseconds);
extern bool OutOfSyncByAge();
extern bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown);
extern std::vector<std::string> split(std::string s, std::string delim);
extern bool ProjectIsValid(std::string project);
extern std::string SerializeBoincBlock(std::string cpid, std::string projectname, std::string AESSkein, double RAC,
double PoBDifficulty, unsigned int diffbytes, std::string enccpid, std::string encaes, double nonce, double NetworkRAC);
extern MiningCPID DeserializeBoincBlock(std::string block);
extern void InitializeCPIDs();
extern void ResendWalletTransactions2();
double GetPoBDifficulty();
double GetNetworkAvgByProject(std::string projectname);
extern bool IsCPIDValid(std::string cpid, std::string ENCboincpubkey);
extern void FindMultiAlgorithmSolution(CBlock* pblock, uint256 hash, uint256 hashTaget, double miningrac);
extern bool CheckProofOfBoinc(CBlock* pblock, bool bOKToBeInChain, bool ConnectingBlock = false);
extern std::string getfilecontents(std::string filename);
extern std::string ToOfficialName(std::string proj);
extern bool LessVerbose(int iMax1000);
std::string GetPoolKey(std::string sMiningProject,double dMiningRAC,
std::string ENCBoincpublickey,std::string xcpid, std::string messagetype,
uint256 blockhash, double subsidy, double nonce, int height, int blocktype);
extern bool GetBlockNew(uint256 blockhash, int& out_height, CBlock& blk, bool bForceDiskRead);
extern std::string ExtractXML(std::string XMLdata, std::string key, std::string key_end);
extern void ShutdownGridcoinMiner();
extern bool OutOfSync();
extern MiningCPID GetNextProject();
extern void GetNextGPUProject(bool force);
extern void HarvestCPIDs(bool cleardata);
extern bool TallyNetworkAverages();
bool FindRAC(bool CheckingWork,std::string TargetCPID, std::string TargetProjectName, double pobdiff,
bool bCreditNodeVerification, std::string& out_errors, int& out_position);
bool FindTransactionSlow(uint256 txhashin, CTransaction& txout, std::string& out_errors);
std::string msCurrentRAC = "";
std::string md4(std::string hi);
std::string GetBoincDataDir();
static boost::thread_group* minerThreads = NULL;
static boost::thread_group* cpidThreads = NULL;
extern void FlushGridcoinBlockFile(bool fFinalize);
map<uint256, CBlockIndex*> mapBlockIndex;
//////////////////////////////////////////////////////////
//Gridcoin Genesis Block
//////////////////////////////////////////////////////////
uint256 hashGenesisBlock("0x2e463ddc588a5900589c75234510c536ce58ec94dafd07157c4be0b3bb9f1f0a");
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Gridcoin: starting difficulty is 1 / 2^12
///////////////////////////////
// Standard Boinc Projects ////
///////////////////////////////
CBlockIndex* pindexGenesisBlock = NULL;
//CPU Projects:
std::string msMiningProject = "";
std::string msMiningCPID = "";
std::string msENCboincpublickey = "";
double mdMiningRAC =0;
double mdMiningNetworkRAC = 0;
std::string msMiningErrors = "";
//GPU Projects:
std::string msGPUMiningProject = "";
std::string msGPUMiningCPID = "";
std::string msGPUENCboincpublickey = "";
std::string msGPUboinckey = "";
double mdGPUMiningRAC = 0;
double mdGPUMiningNetworkRAC = 0;
// Stats for Main Screen:
double mdLastPoBDifficulty = 0;
double mdLastDifficulty = 0;
std::string msGlobalStatus = "";
double boincmagnitude = 0;
// CPU Miner threads global vars
volatile double nGlobalNonce = 0;
volatile double nGlobalHashCounter = 0;
volatile double nGlobalSolutionNonce = 0;
int nBestHeight = -1;
int nBestAccepted = -1;
uint256 nBestChainWork = 0;
uint256 nBestInvalidWork = 0;
uint256 hashBestChain = 0;
//Optimizing internal cpu miner:
uint256 GlobalhashMerkleRoot = 0;
uint256 GlobalSolutionPowHash = 0;
MiningCPID GlobalCPUMiningCPID;
CBlockIndex* pindexBest = NULL;
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
int64 nTimeBestReceived = 0;
int nScriptCheckThreads = 0;
bool fImporting = false;
bool fReindex = false;
bool fBenchmark = false;
bool fTxIndex = false;
unsigned int nCoinCacheSize = 5000;
// Gridcoin status *************
int nBoincUtilization = 0;
double nMinerPaymentCount = 0;
int nPrint = 0;
std::string sBoincMD5 = "";
std::string sBoincBA = "";
std::string sRegVer = "";
std::string sBoincDeltaOverTime = "";
std::string sMinedHash = "";
std::string sSourceBlock = "";
std::string sDefaultWalletAddress = "";
std::map<std::string, MiningEntry> minerpayments;
std::map<std::string, MiningEntry> cpuminerpayments;
std::map<std::string, MiningEntry> cpupow;
std::map<std::string, MiningEntry> cpuminerpaymentsconsolidated;
std::map<std::string, StructCPID> mvCPIDs; //Contains the project stats at the user level
std::map<std::string, StructCPID> mvCreditNode; //Contains the verified stats at the user level
std::map<std::string, StructCPID> mvNetwork; //Contains the project stats at the network level
std::map<std::string, StructCPID> mvNetworkCPIDs; //Contains CPID+Projects at the network level
std::map<std::string, StructCPID> mvCreditNodeCPIDProject; //Contains verified CPID+Projects;
std::map<std::string, StructCPIDCache> mvCPIDCache; //Contains cached blocknumbers for CPID+Projects;
std::map<std::string, StructCPIDCache> mvAppCache; //Contains cached blocknumbers for CPID+Projects;
std::map<std::string, StructBlockCache> mvBlockCache; //Contains Cached Blocks
std::map<std::string, StructCPID> mvBoincProjects; // Contains all of the allowed boinc projects;
std::map<std::string, int> mvTimers; // Contains event timers that reset after max ms duration iterator is exceeded
extern CBigNum ReturnProofOfWorkLimit(int algo);
extern void RestartGridcoinMiner();
extern std::string RetrieveMd5(std::string s1);
extern std::string RacStringFromDiff(double RAC, unsigned int diffbytes);
extern std::string aes_complex_hash(uint256 scrypt_hash);
std::map<int, int> blockcache;
bool bDebugMode = false;
bool bPoolMiningMode = false;
bool bBoincSubsidyEligible = false;
bool bCPUMiningMode = false;
// ********************************
/** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
int64 CTransaction::nMinTxFee = 2000000;
/** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
int64 CTransaction::nMinRelayTxFee = 2000000;
CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
map<uint256, CTransaction> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "Gridcoin Signed Message:\n";
double dHashesPerSec = 0.0;
int64 nHPSTimerStart = 0;
// Settings
int64 nTransactionFee = 0;
int64 nMinimumInputValue = DUST_HARD_LIMIT;
//////////////////////////////////////////////////////////////////////////////
//
// Gridcoin dispatching functions
//
// These functions dispatch to one or all registered wallets
/////////////////////////////////////////////////////////////////////////////
double GetNetworkHashPS2(int lookup, int height) {
CBlockIndex *pb = pindexBest;
if (height >= 0 && height < nBestHeight)
pb = FindBlockByHeight(height);
if (pb == NULL || !pb->nHeight)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pb->nHeight % 2016 + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pb->nHeight)
lookup = pb->nHeight;
CBlockIndex *pb0 = pb;
int64 minTime = pb0->GetBlockTime();
int64 maxTime = minTime;
for (int i = 0; i < lookup; i++) {
pb0 = pb0->pprev;
int64 time = pb0->GetBlockTime();
minTime = std::min(time, minTime);
maxTime = std::max(time, maxTime);
}
// In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
if (minTime == maxTime)
return 0;
uint256 workDiff = pb->nChainWork - pb0->nChainWork;
int64 timeDiff = maxTime - minTime;
return (double)(workDiff.getdouble() / timeDiff);
}
std::string GetGlobalStatus()
{
std::string status = "";
mdLastDifficulty = GetDifficulty();
status = "Blocks: " + RoundToString((double)nBestHeight,0) + "; Difficulty: " + RoundToString(mdLastDifficulty,3)
+ "; Net Hp/s: " + RoundToString(GetNetworkHashPS2(120, -1),2)
+ "; PoB Difficulty: " + RoundToString(mdLastPoBDifficulty,3)
+ "; <br>"
+ "CPU Status: " + msMiningErrors
+ "; Boinc Magnitude: " + RoundToString(boincmagnitude,3) + ";<br>CPU Project: " + msMiningProject;
msGlobalStatus = status;
return status;
}
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void static ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
std::string AppCache(std::string key)
{
StructCPIDCache setting = mvAppCache["cache"+key];
if (!setting.initialized)
{
setting.initialized=true;
setting.xml = "";
mvAppCache.insert(map<string,StructCPIDCache>::value_type("cache"+key,setting));
mvAppCache["cache"+key]=setting;
}
if (setting.xml != "")
{
//printf("AppCachehit on %s",setting.xml.c_str());
}
return setting.xml;
}
void WriteAppCache(std::string key, std::string value)
{
StructCPIDCache setting = mvAppCache["cache"+key];
if (!setting.initialized)
{
setting.initialized=true;
setting.xml = "";
mvAppCache.insert(map<string,StructCPIDCache>::value_type("cache"+key,setting));
mvAppCache["cache"+key]=setting;
}
setting.xml = value;
mvAppCache["cache"+key]=setting;
}
void ResendWalletTransactions2()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendTheWalletTransactions2(true);
}
std::string DefaultGetblocksCommand()
{
if (cached_getblocks_args != "") return cached_getblocks_args;
std::string boinc1 = GetArg("-boincblocks", "boincblocksargs");
std::string boinc2 = GetBlocksCommand;
if (boinc1 != "boincblocksargs")
{
cached_getblocks_args = boinc1;
return boinc1;
}
cached_getblocks_args = boinc2;
return boinc2;
}
void CWallet::ResendTheWalletTransactions2(bool fForce)
{
if (!fForce)
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
static int64_t nNextTime;
if (GetTime() < nNextTime)
return;
bool fFirst = (nNextTime == 0);
nNextTime = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
static int64_t nLastTime;
if (nTimeBestReceived < nLastTime)
return;
nLastTime = GetTime();
}
// Rebroadcast any of our txes that aren't in a block yet
printf("ResendWalletTransactions()\n");
{
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that
// it should have gotten in already by now.
if (fForce || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
wtx.RelayWalletTransaction();
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// CCoinsView implementations
//
bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) { return false; }
bool CCoinsView::SetCoins(const uint256 &txid, const CCoins &coins) { return false; }
bool CCoinsView::HaveCoins(const uint256 &txid) { return false; }
CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::SetCoins(const uint256 &txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(const uint256 &txid) { return base->HaveCoins(txid); }
CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) {
if (cacheCoins.count(txid)) {
coins = cacheCoins[txid];
return true;
}
if (base->GetCoins(txid, coins)) {
cacheCoins[txid] = coins;
return true;
}
return false;
}
std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(const uint256 &txid) {
std::map<uint256,CCoins>::iterator it = cacheCoins.lower_bound(txid);
if (it != cacheCoins.end() && it->first == txid)
return it;
CCoins tmp;
if (!base->GetCoins(txid,tmp))
return cacheCoins.end();
std::map<uint256,CCoins>::iterator ret = cacheCoins.insert(it, std::make_pair(txid, CCoins()));
tmp.swap(ret->second);
return ret;
}
CCoins &CCoinsViewCache::GetCoins(const uint256 &txid) {
std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
assert(it != cacheCoins.end());
return it->second;
}
bool CCoinsViewCache::SetCoins(const uint256 &txid, const CCoins &coins) {
cacheCoins[txid] = coins;
return true;
}
bool CCoinsViewCache::HaveCoins(const uint256 &txid) {
return FetchCoins(txid) != cacheCoins.end();
}
CBlockIndex *CCoinsViewCache::GetBestBlock() {
if (pindexTip == NULL)
pindexTip = base->GetBestBlock();
return pindexTip;
}
bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
pindexTip = pindex;
return true;
}
bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
cacheCoins[it->first] = it->second;
pindexTip = pindex;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, pindexTip);
if (fOk)
cacheCoins.clear();
return fOk;
}
unsigned int CCoinsViewCache::GetCacheSize() {
return cacheCoins.size();
}
/** CCoinsView that brings transactions from a memorypool into view.
It does not check for spendings by memory pool transactions. */
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) {
if (base->GetCoins(txid, coins))
return true;
if (mempool.exists(txid)) {
const CTransaction &tx = mempool.lookup(txid);
coins = CCoins(tx, MEMPOOL_HEIGHT);
return true;
}
return false;
}
bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) {
return mempool.exists(txid) || base->HaveCoins(txid);
}
CCoinsViewCache *pcoinsTip = NULL;
CBlockTreeDB *pblocktree = NULL;
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz > 5000)
{
printf("ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString().c_str());
return false;
}
mapOrphanTransactions[hash] = tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
mapOrphanTransactions.size());
return true;
}
void WriteStringToFile(const boost::filesystem::path &path, std::string sOut)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%s\r\n", sOut.c_str());
fclose(file);
}
}
std::vector<std::string> &split_bychar(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split_bychar(const std::string &s, char delim)
{
std::vector<std::string> elems;
split_bychar(s, delim, elems);
return elems;
}
std::vector<std::string> split(std::string s, std::string delim)
{
size_t pos = 0;
std::string token;
std::vector<std::string> elems;
while ((pos = s.find(delim)) != std::string::npos)
{
token = s.substr(0, pos);
elems.push_back(token);
s.erase(0, pos + delim.length());
}
elems.push_back(s);
return elems;
}
int64 CCoinsViewCache::GetValueIn(const CTransaction& tx)
{
if (tx.IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += GetOutputFor(tx.vin[i]).nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx)
{
if (!tx.IsCoinBase()) {
// first check whether information about the prevout hash is available
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
if (!HaveCoins(prevout.hash))
return false;
}
// then check whether the actual outputs are available
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins &coins = GetCoins(prevout.hash);
if (!coins.IsAvailable(prevout.n))
return false;
}
}
return true;
}
const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
{
const CCoins &coins = view.GetCoins(input.prevout.hash);
assert(coins.IsAvailable(input.prevout.n));
return coins.vout[input.prevout.n];
}
const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input)
{
const CCoins &coins = GetCoins(input.prevout.hash);
assert(coins.IsAvailable(input.prevout.n));
return coins.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
nResult += GetOutputFor(vin[i], inputs).nValue;
return nResult;
}
std::string ExtractXML(std::string XMLdata, std::string key, std::string key_end)
{
std::string extraction = "";
string::size_type loc = XMLdata.find( key, 0 );
if( loc != string::npos )
{
string::size_type loc_end = XMLdata.find( key_end, loc+3);
if (loc_end != string::npos )
{
extraction = XMLdata.substr(loc+(key.length()),loc_end-loc-(key.length()));
}
}
return extraction;
}
std::string RetrieveMd5(std::string s1)
{
try
{
///////////////////////////s1:
const char* chIn = s1.c_str();
unsigned char digest2[16];
//const unsigned char * pszBlah = reinterpret_cast<const unsigned char *> (s1.c_str());
MD5((unsigned char*)chIn, strlen(chIn), (unsigned char*)&digest2);
char mdString2[33];
for(int i = 0; i < 16; i++) sprintf(&mdString2[i*2], "%02x", (unsigned int)digest2[i]);
std::string xmd5(mdString2);
return xmd5;
}
catch (std::exception &e)
{
printf("MD5 INVALID!");
return "";
}
}
double Round(double d, int place)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(place) << d ;
double r = lexical_cast<double>(ss.str());
return r;
}
double cdbl(std::string s, int place)
{
if (s=="") s="0";
double r = lexical_cast<double>(s);
double d = Round(r,place);
return d;
}
std::string get_file_contents(const char *filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in)
{
printf("loading file to string %s","test");
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
}
std::ifstream::pos_type filesize2(const char* filename)
{
std::ifstream in(filename, std::ifstream::in | std::ifstream::binary);
in.seekg(0, std::ifstream::end);
return in.tellg();
}
std::string deletefile(std::string filename)
{
std::string buffer;
std::string line;
ifstream myfile;
printf("loading file to string %s",filename.c_str());
filesystem::path path = filename;
if (!filesystem::exists(path)) {
printf("the file does not exist %s",path.string().c_str());
return "-1";
}
int deleted = remove(filename.c_str());
if (deleted != 0) return "Error deleting.";
return "";
}
std::string getfilecontents(std::string filename)
{
std::string buffer;
std::string line;
ifstream myfile;
printf("loading file to string %s",filename.c_str());
filesystem::path path = filename;
if (!filesystem::exists(path)) {
printf("the file does not exist %s",path.string().c_str());
return "-1";
}
if (false) {
std::string destname = filename+".copy";
ifstream source(filename.c_str(), ios::binary);
ofstream dest(destname.c_str(), ios::binary);
istreambuf_iterator<char> begin_source(source);
istreambuf_iterator<char> end_source;
ostreambuf_iterator<char> begin_dest(dest);
copy(begin_source, end_source, begin_dest);
source.close();
dest.close();
}
FILE *file = fopen(filename.c_str(), "rb");
CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
int fileSize = GetFilesize(filein);
filein.fclose();