-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathminer.cpp
More file actions
1737 lines (1521 loc) · 59.1 KB
/
miner.cpp
File metadata and controls
1737 lines (1521 loc) · 59.1 KB
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-2014 The Bitcoin developers
// Original code was distributed under the MIT software license.
// Copyright (c) 2014-2019 Coin Sciences Ltd
// MultiChain code distributed under the GPLv3 license, see COPYING file.
#include "miner/miner.h"
#include "structs/amount.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "structs/hash.h"
#include "core/main.h"
#include "net/net.h"
#include "structs/base58.h"
#include "chain/pow.h"
#include "utils/timedata.h"
#include "utils/util.h"
#include "utils/utilmoneystr.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include "multichain/multichain.h"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
using namespace std;
bool CanMineWithLockedBlock();
bool IsTxBanned(uint256 txid);
int LastForkedHeight();
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest priority or fee rate, so we might consider
// transactions that depend on transactions that aren't yet in the block.
// The COrphan class keeps track of these 'temporary orphans' while
// CreateBlock is figuring out which transactions to include.
//
class COrphan
{
public:
const CTransaction* ptx;
set<uint256> setDependsOn;
CFeeRate feeRate;
double dPriority;
COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
{
}
};
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
// We want to sort transactions by priority and fee rate, so:
typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
bool UpdateTime(CBlockHeader* pblock, const CBlockIndex* pindexPrev)
{
/* MCHN START */
uint32_t original_nTime=pblock->nTime;
uint32_t original_nBits=pblock->nBits;
/* MCHN END */
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
// Updating time can change work required on testnet:
if (Params().AllowMinDifficultyBlocks())
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
/* MCHN START */
if((original_nTime != pblock->nTime) || (original_nBits != pblock->nBits))
{
return true;
}
return false;
/* MCHN END */
}
/* MCHN START */
bool CreateBlockSignature(CBlock *block,uint32_t hash_type,CWallet *pwallet,uint256 *cachedMerkleRoot)
{
if(Params().DisallowUnsignedBlockNonce())
{
if(hash_type != BLOCKSIGHASH_NO_SIGNATURE)
{
return true;
}
}
else
{
if(hash_type != BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE)
{
return true;
}
}
int coinbase_tx,op_return_output;
uint256 hash_to_verify;
vector<uint256> cachedMerkleBranch;
cachedMerkleBranch.clear();
std::vector<unsigned char> vchSigOut;
std::vector<unsigned char> vchPubKey;
block->nMerkleTreeType=MERKLETREE_FULL;
block->nSigHashType=BLOCKSIGHASH_NONE;
if(!mc_gState->m_NetworkParams->IsProtocolMultichain())
{
block->hashMerkleRoot=block->BuildMerkleTree();
return true;
}
if(block->vSigner[0] == 0)
{
return false;
}
coinbase_tx=-1;
op_return_output=-1;
for (unsigned int i = 0; i < block->vtx.size(); i++)
{
if(coinbase_tx<0)
{
const CTransaction &tx = block->vtx[i];
if (block->vtx[i].IsCoinBase())
{
coinbase_tx=i;
for (unsigned int j = 0; j < tx.vout.size(); j++)
{
const CScript& script1 = tx.vout[j].scriptPubKey;
if(script1.IsUnspendable())
{
op_return_output=j;
}
}
}
}
}
if(coinbase_tx<0)
{
block->nSigHashType=BLOCKSIGHASH_INVALID;
return false;
}
if((hash_type == BLOCKSIGHASH_HEADER) && (op_return_output >= 0))
{
block->nSigHashType=BLOCKSIGHASH_INVALID;
return false;
}
// if(op_return_output >= 0)
{
CMutableTransaction tx=block->vtx[coinbase_tx];
tx.vout.clear();
for(int i=0;i<(int)block->vtx[coinbase_tx].vout.size();i++)
{
if((i != op_return_output) &&
((block->vtx[coinbase_tx].vout[i].nValue != 0) || (mc_gState->m_Permissions->m_Block == 0)))
{
tx.vout.push_back(block->vtx[coinbase_tx].vout[i]);
}
}
block->vtx[coinbase_tx]=tx;
}
switch(hash_type)
{
case BLOCKSIGHASH_HEADER:
block->nMerkleTreeType=MERKLETREE_NO_COINBASE_OP_RETURN;
block->nSigHashType=BLOCKSIGHASH_HEADER;
hash_to_verify=block->GetHash();
break;
case BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE:
case BLOCKSIGHASH_NO_SIGNATURE:
block->nMerkleTreeType=MERKLETREE_NO_COINBASE_OP_RETURN;
if(hash_type == BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE)
{
block->hashMerkleRoot=block->BuildMerkleTree();
block->nNonce=0;
}
else
{
if(*cachedMerkleRoot != 0)
{
block->hashMerkleRoot=*cachedMerkleRoot;
}
else
{
block->hashMerkleRoot=block->BuildMerkleTree();
*cachedMerkleRoot=block->hashMerkleRoot;
}
}
hash_to_verify=block->GetHash();
block->nMerkleTreeType=MERKLETREE_FULL;
break;
default:
block->nSigHashType=BLOCKSIGHASH_INVALID;
return false;
}
CMutableTransaction tx=block->vtx[coinbase_tx];
tx.vout.clear();
for(int i=0;i<(int)block->vtx[coinbase_tx].vout.size();i++)
{
tx.vout.push_back(block->vtx[coinbase_tx].vout[i]);
}
CTxOut txOut;
txOut.nValue = 0;
txOut.scriptPubKey = CScript() << OP_RETURN;
size_t elem_size;
const unsigned char *elem;
vchPubKey=std::vector<unsigned char> (block->vSigner+1, block->vSigner+1+block->vSigner[0]);
CPubKey pubKeyOut(vchPubKey);
CKey key;
if(!pwallet->GetKey(pubKeyOut.GetID(), key))
{
return false;
}
vector<unsigned char> vchSig;
key.Sign(hash_to_verify, vchSig);
mc_Script *lpScript;
lpScript=new mc_Script;
lpScript->SetBlockSignature(vchSig.data(),vchSig.size(),hash_type,block->vSigner+1,block->vSigner[0]);
for(int element=0;element < lpScript->GetNumElements();element++)
{
elem = lpScript->GetData(element,&elem_size);
if(elem)
{
txOut.scriptPubKey << vector<unsigned char>(elem, elem + elem_size);
}
}
delete lpScript;
tx.vout.push_back(txOut);
block->vtx[coinbase_tx]=tx;
switch(hash_type)
{
case BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE:
block->hashMerkleRoot=block->BuildMerkleTree();
break;
case BLOCKSIGHASH_NO_SIGNATURE:
block->hashMerkleRoot=block->CheckMerkleBranch(tx.GetHash(),block->GetMerkleBranch(0),0);
break;
}
return true;
}
/* MCHN END */
/* MCHN START */
//CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn,CWallet *pwallet,CPubKey *ppubkey,int *canMine,CBlockIndex** ppPrev)
/* MCHN END */
{
// Create new block
auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
if(!pblocktemplate.get())
return NULL;
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (Params().MineBlocksOnDemand())
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
// Create coinbase tx
CMutableTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
/* MCHN START */
txNew.vout.resize(1);
int prevCanMine=MC_PTP_MINE;
if(canMine)
{
prevCanMine=*canMine;
}
/* MCHN END */
txNew.vout[0].scriptPubKey = scriptPubKeyIn;
// Add dummy coinbase tx as first transaction
pblock->vtx.push_back(CTransaction());
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOps.push_back(-1); // updated at end
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
// unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
// nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Collect memory pool transactions into the block
CAmount nFees = 0;
bool fPreservedMempoolOrder=true;
{
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
const int nHeight = pindexPrev->nHeight + 1;
if(ppPrev)
{
*ppPrev=pindexPrev;
}
CCoinsViewCache view(pcoinsTip);
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
bool fPrintPriority = GetBoolArg("-printpriority", false);
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
/* MCHN START */
// mempool records are processed in the order they were accepted
set <uint256> setAdded;
/*
for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
mi != mempool.mapTx.end(); ++mi)
{
const CTransaction& tx = mi->second.GetTx();
*/
double orderPriority=mempool.mapTx.size();
mempool.defragmentHashList();
for(int pos=0;pos<mempool.hashList->m_Count;pos++)
{
uint256 hash;
hash=*(uint256*)mempool.hashList->GetRow(pos);
if(!mempool.exists(hash))
{
LogPrint("mchn","mchn-miner: Tx not found in the mempool: %s\n",hash.GetHex().c_str());
fPreservedMempoolOrder=false;
continue;
}
if(IsTxBanned(hash))
{
LogPrint("mchn","mchn-miner: Banned Tx: %s\n",hash.GetHex().c_str());
fPreservedMempoolOrder=false;
continue;
}
const CTransaction& tx = mempool.mapTx[hash].GetTx();
/* MCHN END */
if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight))
{
LogPrint("mchn","mchn-miner: Coinbase or not final tx found: %s\n",tx.GetHash().GetHex().c_str());
fPreservedMempoolOrder=false;
continue;
}
COrphan* porphan = NULL;
double dPriority = 0;
CAmount nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
if (!view.HaveCoins(txin.prevout.hash))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
LogPrintf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
/* MCHN START */
if(setAdded.count(txin.prevout.hash) == 0)
{
/* MCHN END */
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
/* MCHN START */
}
/* MCHN END */
nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
continue;
}
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
assert(coins);
CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = nHeight - coins->nHeight;
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs)
{
LogPrint("mchn","mchn-miner: Missing inputs for %s\n",tx.GetHash().GetHex().c_str());
fPreservedMempoolOrder=false;
continue;
}
// Priority is sum(valuein * age) / modified_txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority = tx.ComputePriority(dPriority, nTxSize);
/* MCHN START */
// Priority ignored - txs are processed in the order they were accepted
dPriority=orderPriority;
orderPriority-=1.;
// uint256 hash = tx.GetHash();
/* MCHN END */
mempool.ApplyDeltas(hash, dPriority, nTotalIn);
CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
/* MCHN START */
/* MCHN END */
if (porphan)
{
LogPrint("mchn","mchn-miner: Orphan %s\n",tx.GetHash().GetHex().c_str());
porphan->dPriority = dPriority;
porphan->feeRate = feeRate;
fPreservedMempoolOrder=false;
}
else
/* MCHN START */
{
setAdded.insert(tx.GetHash());
vecPriority.push_back(TxPriority(dPriority, feeRate, &tx));
}
// vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
/* MCHN END */
}
// Collect transactions into block
uint64_t nBlockSize = 1000;
uint64_t nBlockTx = 0;
int nBlockSigOps = 40;
// bool fSortedByFee = (nBlockPrioritySize <= 0);
/* MCHN START */
TxPriorityCompare comparer(false);
// TxPriorityCompare comparer(fSortedByFee);
bool overblocksize_logged=false;
/* MCHN END */
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
CFeeRate feeRate = vecPriority.front().get<1>();
const CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
{
if(!overblocksize_logged)
{
overblocksize_logged=true;
LogPrint("mchn","mchn-miner: Over block size: %s\n",tx.GetHash().GetHex().c_str());
}
continue;
}
// Legacy limits on sigOps:
unsigned int nTxSigOps = GetLegacySigOpCount(tx);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
{
LogPrint("mchn","mchn-miner: Over sigop count 1: %s\n",tx.GetHash().GetHex().c_str());
continue;
}
// Skip free transactions if we're past the minimum block size:
const uint256& hash = tx.GetHash();
double dPriorityDelta = 0;
CAmount nFeeDelta = 0;
mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
/* MCHN
if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritise by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
*/
if (!view.HaveInputs(tx))
{
LogPrint("mchn","mchn-miner: No inputs for %s\n",tx.GetHash().GetHex().c_str());
continue;
}
CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
nTxSigOps += GetP2SHSigOpCount(tx, view);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
{
LogPrint("mchn","mchn-miner: Over sigop count 2: %s\n",tx.GetHash().GetHex().c_str());
continue;
}
// Note that flags: we don't want to set mempool/IsStandard()
// policy here, but we still have to ensure that the block we
// create only contains transactions that are valid in new blocks.
CValidationState state;
if(!fPreservedMempoolOrder)
{
/* MCHN START */
// if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))// May fail if send permission was lost
if (!CheckInputs(tx, state, view, false, 0, true))
/* MCHN END */
{
LogPrint("mchn","mchn-miner: CheckInput failure %s\n",tx.GetHash().GetHex().c_str());
continue;
}
}
CTxUndo txundo;
UpdateCoins(tx, state, view, txundo, nHeight);
// Added
pblock->vtx.push_back(tx);
pblocktemplate->vTxFees.push_back(nTxFees);
pblocktemplate->vTxSigOps.push_back(nTxSigOps);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fPrintPriority)
{
LogPrintf("priority %.1f fee %s txid %s\n",
dPriority, feeRate.ToString(), tx.GetHash().ToString());
}
// Add transactions that depend on this one to the priority queue
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
/* MCHN START */
// If block was dropped, this happens too many times
// LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
/* MCHN END */
// Compute final coinbase transaction.
txNew.vout[0].nValue = GetBlockValue(nHeight, nFees);
txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
pblock->vSigner[0]=ppubkey->size();
memcpy(pblock->vSigner+1,ppubkey->begin(),pblock->vSigner[0]);
pblock->vtx[0] = txNew;
pblocktemplate->vTxFees[0] = -nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
pblock->nNonce = 0;
pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
/* MCHN START */
bool testValidity=true;
// If this node cannot mine for some reason (permission or diversity, block is not tested for validity to avoid exception
if(mc_gState->m_NetworkParams->IsProtocolMultichain())
{
if(canMine)
{
// const unsigned char *pubkey_hash=(unsigned char *)Hash160(ppubkey->begin(),ppubkey->end()).begin();
// *canMine=mc_gState->m_Permissions->CanMine(NULL,pubkey_hash);
uint160 pubkey_hash=Hash160(ppubkey->begin(),ppubkey->end());
*canMine=mc_gState->m_Permissions->CanMine(NULL,&pubkey_hash);
if((*canMine & MC_PTP_MINE) == 0)
{
if(prevCanMine & MC_PTP_MINE)
{
LogPrintf("mchn: MultiChainMiner: cannot mine now, waiting...\n");
}
testValidity=false;
}
else
{
if((prevCanMine & MC_PTP_MINE) == 0)
{
LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
LogPrintf("mchn: MultiChainMiner: Starting mining...\n");
}
}
}
}
else
{
LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
}
if(GetBoolArg("-avoidtestingblockvalidity",true))
{
testValidity=false;
}
if(testValidity)
{
/* MCHN END */
CValidationState state;
if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
throw std::runtime_error("CreateNewBlock() : TestBlockValidity failed");
/* MCHN START */
}
/* MCHN END */
}
return pblocktemplate.release();
}
/* MCHN START */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
{
return CreateNewBlock(scriptPubKeyIn,NULL,NULL,NULL,NULL);
}
/* MCHN END */
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce,CWallet *pwallet)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = txCoinbase;
/* MCHN START */
CreateBlockSignature(pblock,BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE,pwallet,NULL);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
/* MCHN END */
}
#ifdef ENABLE_WALLET
//////////////////////////////////////////////////////////////////////////////
//
// Internal miner
//
double dHashesPerSec = 0.0;
int64_t nHPSTimerStart = 0;
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// The nonce is usually preserved between calls, but periodically or if the
// nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
// zero.
//
bool static ScanHash(CBlock *pblock, uint32_t& nNonce, uint256 *phash,uint16_t success_and_mask,CWallet *pwallet)
{
// Write the first 76 bytes of the block header to a double-SHA256 state.
CHash256 hasher;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pblock->GetBlockHeader();
// ss << *pblock;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
uint256 cachedMerkleRoot=0;
while (true) {
nNonce++;
if(Params().DisallowUnsignedBlockNonce())
{
pblock->nNonce=nNonce;
CreateBlockSignature(pblock,BLOCKSIGHASH_NO_SIGNATURE,pwallet,&cachedMerkleRoot);
*phash=pblock->GetHash();
}
else
{
// Write the last 4 bytes of the block header (the nonce) to a copy of
// the double-SHA256 state, and compute the result.
CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash);
}
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
/*
if (((uint16_t*)phash)[15] == 0)
return true;
*/
if( (((uint16_t*)phash)[15] & success_and_mask) == 0)
{
if(Params().DisallowUnsignedBlockNonce())
{
pblock->hashMerkleRoot=pblock->BuildMerkleTree();
}
return true;
}
// If nothing found after trying for a while, return -1
if ((nNonce & 0xffff) == 0)
{
// if ((nNonce & 0xff) == 0)
if(Params().DisallowUnsignedBlockNonce())
{
pblock->hashMerkleRoot=pblock->BuildMerkleTree();
}
return false;
}
if ((nNonce & 0xfff) == 0)
boost::this_thread::interruption_point();
}
}
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
{
CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey))
return NULL;
CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
return CreateNewBlock(scriptPubKey);
}
/* MCHN START */
// Block should be mined for specific keys, not just any from pool
CBlockTemplate* CreateNewBlockWithDefaultKey(CWallet *pwallet,int *canMine,const set<CTxDestination>* addresses,CBlockIndex** ppPrev)
{
CPubKey pubkey;
bool key_found;
{
LOCK(cs_main);
key_found=pwallet->GetKeyFromAddressBook(pubkey,MC_PTP_MINE,addresses);
}
if(!key_found)
{
if(canMine)
{
if(*canMine & MC_PTP_MINE)
{
*canMine=0;
LogPrintf("mchn: Cannot find address having mining permission\n");
}
}
return NULL;
}
// const unsigned char *pubkey_hash=(unsigned char *)Hash160(pubkey.begin(),pubkey.end()).begin();
unsigned char pubkey_hash[20];
uint160 pkhash=Hash160(pubkey.begin(),pubkey.end());
memcpy(pubkey_hash,&pkhash,20);
CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << vector<unsigned char>(pubkey_hash, pubkey_hash + 20) << OP_EQUALVERIFY << OP_CHECKSIG;
return CreateNewBlock(scriptPubKey,pwallet,&pubkey,canMine,ppPrev);
}
/* MCHN END */
bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
if(fDebug)LogPrint("mchnminor","%s\n", pblock->ToString());
if(fDebug)LogPrint("mcminer","mchn-miner: generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
// Found a solution
{
LOCK(cs_main);
if(mc_gState->m_NodePausedState & MC_NPS_MINING)
{
return error("MultiChainMiner : mining is paused, generated block is dropped");
}
if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
{
return error("MultiChainMiner : generated block is stale");
}
}
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
CValidationState state;
if (!ProcessNewBlock(state, NULL, pblock))
return error("MultiChainMiner : ProcessNewBlock, block not accepted");
return true;
}
set <CTxDestination> LastActiveMiners(CBlockIndex* pindexTip, CPubKey *kLastMiner, int nMinerPoolSize)
{
int nRelativeWindowSize=5;
int nTotalMiners=mc_gState->m_Permissions->GetMinerCount();
int nActiveMiners=mc_gState->m_Permissions->GetActiveMinerCount();
int nDiversityMiners=0;
int nWindowSize;
CBlockIndex* pindex;
set <CTxDestination> sMiners;
if(mc_gState->m_NetworkParams->IsProtocolMultichain() == 0)
{
return sMiners;
}
if(MCP_ANYONE_CAN_MINE == 0)
{
nDiversityMiners=nTotalMiners-nActiveMiners;
}
nWindowSize=nRelativeWindowSize*nMinerPoolSize+nDiversityMiners;
pindex=pindexTip;
for(int i=0;i<nWindowSize;i++)
{
if((int)sMiners.size() < nMinerPoolSize)
{
if(pindex)
{
if(!pindex->kMiner.IsValid())
{
CBlock block;
if(ReadBlockFromDisk(block,pindex))
{
if(block.vSigner[0])
{
pindex->kMiner.Set(block.vSigner+1, block.vSigner+1+block.vSigner[0]);
pindex->nStatus |= BLOCK_HAVE_MINER_PUBKEY;
}
}
}
if(pindex->kMiner.IsValid())
{
CKeyID addr=pindex->kMiner.GetID();
if(mc_gState->m_Permissions->CanMine(NULL,addr.begin()))
{
if(sMiners.find(addr) == sMiners.end())
{
sMiners.insert(addr);
}
}
}
if(pindex == pindexTip)
{
*kLastMiner=pindex->kMiner;
}
pindex=pindex->pprev;
}
}
}
return sMiners;
}
int GetMaxActiveMinersCount()
{
if(mc_gState->m_NetworkParams->IsProtocolMultichain())
{
if(MCP_ANYONE_CAN_MINE)
{
return 1048576;
}
else
{
return mc_gState->m_Permissions->GetActiveMinerCount();
}
}
else
{
return 1024;
}
}
double GetMinerAndExpectedMiningStartTime(CWallet *pwallet,CPubKey *lpkMiner,set <CTxDestination> *lpsMinerPool,double *lpdMiningStartTime,double *lpdActiveMiners,uint256 *lphLastBlockHash,int *lpnMemPoolSize,double wAvBlockTime)
{
int nMinerPoolSizeMin=4;
int nMinerPoolSizeMax=16;
double dRelativeSpread=1.;
double dRelativeMinerPoolSize=0.25;
double dAverageCreateBlockTime=2;
double dAverageCreateBlockTimeShift=0;
double dMinerDriftMin=mc_gState->m_NetworkParams->ParamAccuracy();