-
Notifications
You must be signed in to change notification settings - Fork 91
/
mining.cpp
1433 lines (1254 loc) · 65 KB
/
mining.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) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2018-2022 The Veil developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <amount.h>
#include <chain.h>
#include <chainparams.h>
#include <consensus/consensus.h>
#include <consensus/params.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <validation.h>
#include <key_io.h>
#include <miner.h>
#include <net.h>
#include <policy/fees.h>
#include <pow.h>
#include <rpc/blockchain.h>
#include <rpc/mining.h>
#include <rpc/server.h>
#include <shutdown.h>
#include <txmempool.h>
#include <util/system.h>
#include <util/strencodings.h>
#include <validationinterface.h>
#include <warnings.h>
#include <memory>
#include <stdint.h>
#include <tinyformat.h>
// ProgPow
#include <crypto/ethash/lib/ethash/endianness.hpp>
#include <crypto/ethash/include/ethash/progpow.hpp>
#include "crypto/ethash/helpers.hpp"
#include "crypto/ethash/progpow_test_vectors.hpp"
// RandomX
#include <crypto/randomx/randomx.h>
#include <crypto/hash-ops.h>
std::map<std::string, CBlock> mapProgPowTemplates;
std::map<std::string, CBlock> mapRandomXTemplates;
unsigned int ParseConfirmTarget(const UniValue& value)
{
int target = value.get_int();
unsigned int max_target = ::feeEstimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
if (target < 1 || (unsigned int)target > max_target) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u - %u", 1, max_target));
}
return (unsigned int)target;
}
/**
* Return average network hashes per second based on the last 'lookup' blocks,
* or from the last difficulty change if 'lookup' is nonpositive.
* If 'height' is nonnegative, compute the estimate at the time when a given block was found.
*/
static UniValue GetNetworkHashPS(int lookup, int height, std::string type) {
CBlockIndex *pb = chainActive.Tip();
if (height >= 0 && height < chainActive.Height())
pb = chainActive[height];
// if after fork, set pb to fork height unless specifying pos or x16rt
if (pb == nullptr || !pb->nHeight)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 1)
lookup = 2;
CBlockIndex *pbLast = pb;
CBlockIndex *pbFirst = nullptr;
bool found = false;
while (pb->nHeight > 0)
{
// find the last of the algo
if (0 == type.compare("pos")) {
if (pb->IsProofOfStake()) found=true;
} else if (0 == type.compare("sha256d")) {
if (pb->GetBlockTime() < Params().PowUpdateTimestamp()) return 0;
if (pb->IsSha256DProofOfWork()) found=true;
} else if (0 == type.compare("randomx")) {
if (pb->GetBlockTime() < Params().PowUpdateTimestamp()) return 0;
if (pb->IsRandomXProofOfWork()) found=true;
} else if (0 == type.compare("progpow")) {
if (pb->GetBlockTime() < Params().PowUpdateTimestamp()) return 0;
if (pb->IsProgProofOfWork()) found=true;
} else if (0 == type.compare("xr16t")) {
if (pb->IsX16RTProofOfWork()) found=true;
} else {
// Unknown Algo
return 0;
}
if (found) {
pbLast = pb;
break;
}
pb = pb->pprev;
}
if (!found) return 0;
// find the nth previous
uint32_t nCountBlocks = 1;
while ((nCountBlocks < lookup) && (pb->nHeight > 1))
{
pb = pb->pprev;
if (0 == type.compare("pos")) {
if (pb->IsProofOfStake()) {
nCountBlocks++;
pbFirst = pb;
}
} else if (0 == type.compare("sha256d")) {
if (pb->IsSha256DProofOfWork()) {
nCountBlocks++;
pbFirst = pb;
}
} else if (0 == type.compare("randomx")) {
if (pb->IsRandomXProofOfWork()) {
nCountBlocks++;
pbFirst = pb;
}
} else if (0 == type.compare("progpow")) {
if (pb->IsProgProofOfWork()) {
nCountBlocks++;
pbFirst = pb;
}
} else { // xr16rt
if (pb->IsX16RTProofOfWork()) {
nCountBlocks++;
pbFirst = pb;
}
}
// Check if we should continue
if (((0 != type.compare("sha256d")) || (0 != type.compare("randomx")) || (0 != type.compare("progpow"))) &&
(pb->GetBlockTime() < Params().PowUpdateTimestamp()))
{
// Don't keep searching, abort now
break;
}
}
// only one was found
if (!pbFirst || !pbLast || (pbFirst == pbLast)) return 0;
int64_t minTime = pbFirst->GetBlockTime();
int64_t maxTime = pbLast->GetBlockTime();
// In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
if (minTime == maxTime)
return 0;
arith_uint256 workDiff = pbLast->nChainWork - pbFirst->nChainWork;
int64_t timeDiff = maxTime - minTime;
return workDiff.getdouble() / timeDiff;
}
static UniValue getnetworkhashps(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 3)
throw std::runtime_error(
"getnetworkhashps ( nblocks height algo )\n"
"\nReturns the estimated network hashes per second based on the last n blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
"Pass in [height] to estimate the network hash at the time when a certain block was found.\n"
"Pass in [algo] to estimate the network hash for a different algo then your wallet is set to.\n"
"\nArguments:\n"
"1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
"2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
"3. algo (string, optional, default="+GetMiningType(GetMiningAlgorithm(), false, false)+") Algo to calculate [randomx, sha256d, progpow, xr16t, pos].\n"
"\nResult:\n"
"x (numeric) Hashes per second estimated\n"
"\nExamples:\n"
+ HelpExampleCli("getnetworkhashps", "")
+ HelpExampleRpc("getnetworkhashps", "")
);
if (!(request.params[2].isNull())) {
std::string algo = request.params[2].get_str();
// Check if it's a mining algorithm
if (!SetMiningAlgorithm(algo, false))
// check that it's not one of the other two
if (algo.compare("pos") && algo.compare("xr16t"))
throw JSONRPCError(RPC_INVALID_PARAMETER,
strprintf("%s is not a supported mining type", algo));
}
return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120,
!request.params[1].isNull() ? request.params[1].get_int() : -1,
!request.params[2].isNull() ? request.params[2].get_str()
: GetMiningType(GetMiningAlgorithm(), false, false));
}
UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
{
static const int nInnerLoopCount = 0x10000;
int nHeightEnd = 0;
int nHeight = 0;
{ // Don't keep cs_main locked
LOCK(cs_main);
nHeight = chainActive.Height();
nHeightEnd = nHeight+nGenerate;
}
unsigned int nExtraNonce = 0;
UniValue blockHashes(UniValue::VARR);
InitRandomXLightCache(nHeight);
while (nHeight < nHeightEnd && !ShutdownRequested())
{
std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
if (!pblocktemplate.get())
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
CBlock *pblock = &pblocktemplate->block;
IncrementExtraNonce(pblock, chainActive.Height(), nExtraNonce);
// This will check if the key block needs to change and will take down the cache and vm, and spin up the new ones
CheckIfValidationKeyShouldChangeAndUpdate(GetKeyBlock(pblock->nHeight));
if (pblock->IsProgPow() && pblock->nTime >= Params().PowUpdateTimestamp()) {
uint256 mix_hash;
while (nMaxTries > 0 && pblock->nNonce64 < nInnerLoopCount &&
!CheckProofOfWork(ProgPowHash(*pblock, mix_hash), pblock->nBits,
Params().GetConsensus(), CBlockHeader::PROGPOW_BLOCK) && !ShutdownRequested()) {
++pblock->nNonce64;
--nMaxTries;
}
pblock->mixHash = mix_hash;
} else if (pblock->IsRandomX() && pblock->nTime >= Params().PowUpdateTimestamp()) {
char hash[RANDOMX_HASH_SIZE];
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(pblock->nBits, &fNegative, &fOverflow);
while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !ShutdownRequested()) {
// RandomX hash
uint256 hash_blob = pblock->GetRandomXHeaderHash();
randomx_calculate_hash(GetMyMachineValidating(), &hash_blob, sizeof uint256(), hash);
uint256 uint256Hash = RandomXHashToUint256(hash);
// Check proof of work matches claimed amount
if (UintToArith256(uint256Hash) < bnTarget)
break;
++pblock->nNonce;
--nMaxTries;
}
} else if (pblock->IsSha256D() && pblock->nTime >= Params().PowUpdateTimestamp()) {
while (nMaxTries > 0 && pblock->nNonce64 < nInnerLoopCount &&
!CheckProofOfWork(pblock->GetSha256DPoWHash(), pblock->nBits,
Params().GetConsensus(), CBlockHeader::SHA256D_BLOCK) && !ShutdownRequested()) {
++pblock->nNonce64;
--nMaxTries;
}
} else {
while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount &&
!CheckProofOfWork(pblock->GetX16RTPoWHash(), pblock->nBits, Params().GetConsensus())) {
++pblock->nNonce;
--nMaxTries;
}
}
if (nMaxTries == 0) {
break;
}
if ((pblock->nNonce == nInnerLoopCount) || (pblock->nNonce64 == nInnerLoopCount)) {
continue;
}
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
if (!ProcessNewBlock(Params(), shared_pblock, true, nullptr))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight;
blockHashes.push_back(pblock->GetHash().GetHex());
//mark script as important because it was used at least for one coinbase output if the script came from the wallet
if (keepScript)
{
coinbaseScript->KeepScript();
}
}
return blockHashes;
}
UniValue generateBlocks(bool fGenerate, int nThreads, std::shared_ptr<CReserveScript> coinbaseScript)
{
GenerateBitcoins(fGenerate, nThreads, coinbaseScript);
return UniValue(UniValue::VNULL);
}
static UniValue generatetoaddress(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
throw std::runtime_error(
"generatetoaddress nblocks address (maxtries)\n"
"\nMine blocks immediately to a specified address (before the RPC call returns)\n"
"\nArguments:\n"
"1. nblocks (numeric, required) How many blocks are generated immediately.\n"
"2. address (string, required) The address to send the newly generated veil to.\n"
"3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
"\nResult:\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks to myaddress\n"
+ HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
);
int nGenerate = request.params[0].get_int();
uint64_t nMaxTries = 1000000;
if (!request.params[2].isNull()) {
nMaxTries = request.params[2].get_int();
}
CTxDestination destination = DecodeDestination(request.params[1].get_str());
if (!IsValidDestination(destination)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
}
std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();
coinbaseScript->reserveScript = GetScriptForDestination(destination);
return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
}
static UniValue getmininginfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getmininginfo\n"
"\nReturns a json object containing mining-related information."
"\nResult:\n"
"{\n"
" \"blocks\": nnn, (numeric) The current block\n"
" \"currentblockweight\": nnn, (numeric) The last block weight\n"
" \"currentblocktx\": nnn, (numeric) The last block transaction\n"
" \"algorithm\": \"xxxx\", (string) Algorithm set to mine (progpow, randomx, sha256d)\n"
" \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
" \"networkhashps\": nnn, (numeric) The network hashes per second\n"
" \"hashspeed\": nnn, (numeric) The system hashes per second\n"
" \"pooledtx\": n (numeric) The size of the mempool\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"warnings\": \"...\" (string) any network and blockchain warnings\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmininginfo", "")
+ HelpExampleRpc("getmininginfo", "")
);
const Consensus::Params& ConsensusParams = Params().GetConsensus();
int nAlgo = GetMiningAlgorithm();
std::string sMiningAlgo = GetMiningType(nAlgo, false, false);
int nBlockType = CBlock::RANDOMX_BLOCK;
if (nAlgo == MINE_PROGPOW) nBlockType = CBlock::PROGPOW_BLOCK;
else if (nAlgo == MINE_SHA256D) nBlockType = CBlock::SHA256D_BLOCK;
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
double nDiff = GetDifficulty(GetNextWorkRequired(chainActive.Tip(), nullptr, ConsensusParams,
false, nBlockType));
obj.pushKV("blocks", (int)chainActive.Height());
obj.pushKV("currentblockweight", (uint64_t)nLastBlockWeight);
obj.pushKV("currentblocktx", (uint64_t)nLastBlockTx);
obj.pushKV("algorithm", sMiningAlgo);
obj.pushKV("difficulty", (double)nDiff);
obj.pushKV("networkhashps", getnetworkhashps(request));
obj.pushKV("hashspeed", GetHashSpeed());
obj.pushKV("hashspeed_recent", GetRecentHashSpeed());
obj.pushKV("pooledtx", (uint64_t)mempool.size());
obj.pushKV("chain", Params().NetworkIDString());
obj.pushKV("warnings", GetWarnings("statusbar"));
return obj;
}
static UniValue setminingalgo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"setminingalgo algorithm\n"
"\nChanges your mining algorithm to [algorithm]. Note that mining must be turned off when command is used. This will also have the side effect of clearing your mining statistics.\n"
"\nArguments:\n"
"1. algorithm (string, required) Algorithm to mine [progpow, randomx, sha256d].\n"
"\nResult:\n"
"{\n"
" \"success\": true|false, (boolean) Status of the switch\n"
" \"message\": \"text\", (text) Informational message about the switch\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("setminingalgo", "sha256d")
+ HelpExampleRpc("setminingalgo", "sha256d")
);
if (GenerateActive())
throw JSONRPCError(RPC_INVALID_PARAMETER, "mining must be stopped to change algorithm");
std::string sOldAlgo = GetMiningType(GetMiningAlgorithm(), false, false);
std::string sNewAlgo = request.params[0].get_str();
// Check if it's a mining algorithm
if (!SetMiningAlgorithm(sNewAlgo)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s is not a supported mining type", sNewAlgo));
}
ClearHashSpeed();
UniValue result(UniValue::VOBJ);
result.pushKV("success", true);
result.pushKV("message", strprintf("Mining algorithm changed from %s to %s", sOldAlgo, sNewAlgo));
return result;
}
// NOTE: Unlike wallet RPC (which use VEIL values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
static UniValue prioritisetransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 3)
throw std::runtime_error(
"prioritisetransaction <txid> <dummy value> <fee delta>\n"
"Accepts the transaction into mined blocks at a higher (or lower) priority\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id.\n"
"2. dummy (numeric, optional) API-Compatibility for previous API. Must be zero or null.\n"
" DEPRECATED. For forward compatibility use named arguments and omit this parameter.\n"
"3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
" Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
" The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
" considers the transaction as it would have paid a higher (or lower) fee.\n"
"\nResult:\n"
"true (boolean) Returns true\n"
"\nExamples:\n"
+ HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
+ HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
);
LOCK(cs_main);
uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
CAmount nAmount = request.params[2].get_int64();
if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
}
mempool.PrioritiseTransaction(hash, nAmount);
return true;
}
// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
static UniValue BIP22ValidationResult(const CValidationState& state)
{
if (state.IsValid())
return NullUniValue;
if (state.IsError())
throw JSONRPCError(RPC_VERIFY_ERROR, FormatStateMessage(state));
if (state.IsInvalid())
{
std::string strRejectReason = state.GetRejectReason();
if (strRejectReason.empty())
return "rejected";
return strRejectReason;
}
// Should be impossible
return "valid?";
}
static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
std::string s = vbinfo.name;
if (!vbinfo.gbt_force) {
s.insert(s.begin(), '!');
}
return s;
}
template<int nPoWType>
static UniValue getblocktemplate_impl(const std::string &strMode, const UniValue &lpval, const std::set<std::string> setClientRules, int64_t nMaxVersionPreVB) {
static unsigned int nTransactionsUpdatedLast;
if (!lpval.isNull())
{
// Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
uint256 hashWatchedChain;
std::chrono::steady_clock::time_point checktxtime;
unsigned int nTransactionsUpdatedLastLP;
if (lpval.isStr())
{
// Format: <hashBestChain><nTransactionsUpdatedLast>
std::string lpstr = lpval.get_str();
hashWatchedChain.SetHex(lpstr.substr(0, 64));
nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
}
else
{
// NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
hashWatchedChain = chainActive.Tip()->GetBlockHash();
nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
}
// Release the wallet and main lock while waiting
LEAVE_CRITICAL_SECTION(cs_main);
{
checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
WaitableLock lock(g_best_block_mutex);
while (g_best_block == hashWatchedChain && IsRPCRunning())
{
if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
{
// Timeout: Check transactions for update
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
break;
checktxtime += std::chrono::seconds(10);
}
}
}
ENTER_CRITICAL_SECTION(cs_main);
if (!IsRPCRunning())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
// TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
}
const struct VBDeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
// If the caller is indicating segwit support, then allow CreateNewBlock()
// to select witness transactions, after segwit activates (otherwise
// don't).
bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end();
// Update block
static CBlockIndex* pindexPrev;
static int64_t nStart;
static std::unique_ptr<CBlockTemplate> pblocktemplate;
// Cache whether the last invocation was with segwit support, to avoid returning
// a segwit-block to a non-segwit caller.
static bool fLastTemplateSupportsSegwit = true;
if (pindexPrev != chainActive.Tip() ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
fLastTemplateSupportsSegwit != fSupportsSegwit)
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = nullptr;
if constexpr (nPoWType == CBlockHeader::PROGPOW_BLOCK)
mapProgPowTemplates.clear();
if constexpr (nPoWType == CBlockHeader::RANDOMX_BLOCK)
mapRandomXTemplates.clear();
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = chainActive.Tip();
nStart = GetTime();
fLastTemplateSupportsSegwit = fSupportsSegwit;
// Get mining address if it is set
CScript script;
std::string sAddress = gArgs.GetArg("-miningaddress", "");
if (!sAddress.empty()) {
CTxDestination dest = DecodeDestination(sAddress);
if (IsValidDestination(dest)) {
script = GetScriptForDestination(dest);
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "-miningaddress is not a valid address. Please use a valid address");
}
// Disallow Stealth Addresses for now
CBitcoinAddress address(sAddress);
if (address.IsValidStealthAddress()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "-miningaddress must be a basecoin address");
}
} else {
script = CScript() << OP_TRUE;
}
// Create new block
pblocktemplate = BlockAssembler(Params()).CreateNewBlock(script, fSupportsSegwit, false, false, nPoWType);
if (!pblocktemplate)
throw JSONRPCError(RPC_VERIFY_ERROR, "Created block is rejected or otherwise unable to successfully create a new block");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
assert(pindexPrev);
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
const Consensus::Params& consensusParams = Params().GetConsensus();
// Update nTime
UpdateTime(pblock, consensusParams, pindexPrev);
pblock->nNonce = 0;
// NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
const bool fPreSegWit = false;
UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
UniValue mapaccumulatorhashes(UniValue::VOBJ);
for (auto& it : pblock->mapAccumulatorHashes)
mapaccumulatorhashes.pushKV(std::to_string(it.first), it.second.GetHex());
UniValue transactions(UniValue::VARR);
std::map<uint256, int64_t> setTxIndex;
int i = 0;
for (const auto& it : pblock->vtx) {
const CTransaction& tx = *it;
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
UniValue entry(UniValue::VOBJ);
entry.pushKV("data", EncodeHexTx(tx));
entry.pushKV("txid", txHash.GetHex());
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
UniValue deps(UniValue::VARR);
for (const CTxIn &in : tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.pushKV("depends", deps);
int index_in_template = i - 1;
entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]);
int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
if (fPreSegWit) {
assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
nTxSigOps /= WITNESS_SCALE_FACTOR;
}
entry.pushKV("sigops", nTxSigOps);
entry.pushKV("weight", GetTransactionWeight(tx));
transactions.push_back(entry);
}
UniValue aux(UniValue::VOBJ);
aux.pushKV("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()));
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
UniValue aMutable(UniValue::VARR);
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
UniValue result(UniValue::VOBJ);
result.pushKV("capabilities", aCaps);
UniValue aRules(UniValue::VARR);
UniValue vbavailable(UniValue::VOBJ);
for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
switch (state) {
case ThresholdState::DEFINED:
case ThresholdState::FAILED:
// Not exposed to GBT at all
break;
case ThresholdState::LOCKED_IN:
// Ensure bit is set in block version
pblock->nVersion |= VersionBitsMask(consensusParams, pos);
// FALL THROUGH to get vbavailable set...
case ThresholdState::STARTED:
{
const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
if (!vbinfo.gbt_force) {
// If the client doesn't support this, don't indicate it in the [default] version
pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
}
}
break;
}
case ThresholdState::ACTIVE:
{
// Add to rules only
const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
aRules.push_back(gbt_vb_name(pos));
if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
// Not supported by the client; make sure it's safe to proceed
if (!vbinfo.gbt_force) {
// If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
}
}
break;
}
}
}
result.pushKV("version", pblock->nVersion);
result.pushKV("rules", aRules);
result.pushKV("vbavailable", vbavailable);
result.pushKV("vbrequired", int(0));
if (nMaxVersionPreVB >= 2) {
// If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
// Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
// This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
// Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
aMutable.push_back("version/force");
}
result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
result.pushKV("transactions", transactions);
result.pushKV("coinbaseaux", aux);
result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vpout[0]->GetValue());
result.pushKV("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast));
result.pushKV("target", hashTarget.GetHex());
result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
result.pushKV("mutable", aMutable);
result.pushKV("noncerange", "00000000ffffffff");
int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
if (fPreSegWit) {
assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
nSigOpLimit /= WITNESS_SCALE_FACTOR;
}
result.pushKV("sigoplimit", nSigOpLimit);
result.pushKV("sizelimit", nSizeLimit);
if (!fPreSegWit) {
result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
}
result.pushKV("curtime", pblock->GetBlockTime());
result.pushKV("bits", strprintf("%08x", pblock->nBits));
result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment));
}
result.pushKV("accumulatorhashes", mapaccumulatorhashes);
result.pushKV("proofoffullnodehash", pblock->hashPoFN.GetHex());
result.pushKV("mining_disabled", (!CheckConsecutivePoW(*pblock , pindexPrev))? true : false );
if constexpr (nPoWType == CBlockHeader::PROGPOW_BLOCK) { // if (pblock->IsProgPow()) {
std::string address = gArgs.GetArg("-miningaddress", "");
if (IsValidDestinationString(address)) {
static std::string lastheader = "";
if (mapProgPowTemplates.count(lastheader)) {
if (pblock->nTime - 60 < mapProgPowTemplates.at(lastheader).nTime) {
result.pushKV("pprpcheader", lastheader);
result.pushKV("pprpcepoch", ethash::get_epoch_number(pblock->nHeight));
return result;
}
}
result.pushKV("pprpcheader", pblock->GetProgPowHeaderHash().GetHex());
result.pushKV("pprpcepoch", progpow::get_epoch_number(pblock->nHeight));
mapProgPowTemplates[pblock->GetProgPowHeaderHash().GetHex()] = *pblock;
lastheader = pblock->GetProgPowHeaderHash().GetHex();
}
}
if constexpr (nPoWType == CBlockHeader::RANDOMX_BLOCK) { // if (pblock->IsRandomX()) {
std::string address = gArgs.GetArg("-miningaddress", "");
if (IsValidDestinationString(address)) {
static std::string lastheader = "";
if (mapRandomXTemplates.count(lastheader)) {
if (pblock->nTime - 60 < mapRandomXTemplates.at(lastheader).nTime) {
result.pushKV("rxrpcheader", lastheader);
result.pushKV("rxrpcseed", GetKeyBlock(pblock->nHeight).GetHex());
return result;
}
}
CDataStream ssBlockHeader(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ssBlockHeader << CRandomXInput(*pblock);
std::string blockHeaderHex = HexStr(ssBlockHeader);
result.pushKV("rxrpcheader", blockHeaderHex);
result.pushKV("rxrpcseed", GetKeyBlock(pblock->nHeight).GetHex());
mapRandomXTemplates[blockHeaderHex] = *pblock;
lastheader = blockHeaderHex;
}
}
return result;
}
static UniValue getblocktemplate(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getblocktemplate ( TemplateRequest )\n"
"\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
"It returns data needed to construct a block to work on.\n"
"For full specification, see BIPs 22, 23, 9, and 145:\n"
" https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
" https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
" https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
" https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"
"\nArguments:\n"
"1. template_request (json object, optional) A json object in the following spec\n"
" {\n"
" \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
" \"algo\":\"randomx\" (string, optional) This must be set to \"progpow\", \"randomx\", \"sha256d\", or omitted\n"
" \"capabilities\":[ (array, optional) A list of strings\n"
" \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
" ,...\n"
" ],\n"
" \"rules\":[ (array, optional) A list of strings\n"
" \"support\" (string) client side supported softfork deployment\n"
" ,...\n"
" ]\n"
" }\n"
"\n"
"\nResult:\n"
"{\n"
" \"version\" : n, (numeric) The preferred block version\n"
" \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
" \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
" \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
" ,...\n"
" },\n"
" \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
" \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
" \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
" {\n"
" \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
" \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
" \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
" \"depends\" : [ (array) array of numbers \n"
" n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
" ,...\n"
" ],\n"
" \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
" \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n"
" \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
" }\n"
" ,...\n"
" ],\n"
" \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
" \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
" },\n"
" \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)\n"
" \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
" \"target\" : \"xxxx\", (string) The hash target\n"
" \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
" \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
" ,...\n"
" ],\n"
" \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
" \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
" \"sizelimit\" : n, (numeric) limit of block size\n"
" \"weightlimit\" : n, (numeric) limit of block weight\n"
" \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
" \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
" \"height\" : n (numeric) The height of the next block\n"
" \"pprpcheader\" : \"xxxx\" (string) The header hash that can be used by the local GPU miner to mine a progpow block (using -miningaddress) as the destination for the coinbase tx\n"
" \"pprpcepoch\" : n (numeric) The epoch of the progpow pprpcheader given to user to be used by the local GPU miner\n"
" \"rxrpcheader\" : \"xxxx\" (string) The header that can be used by the local CPU miner to mine a randomx block (using -miningaddress) as the destination for the coinbase tx\n"
" \"rxrpcseed\" : \"xxxx\" (string) The seed hash of the randomx rxrpcheader given to user to be used by the local CPU miner\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblocktemplate", "{\"rules\": [\"segwit\"]}")
+ HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
);
LOCK(cs_main);
std::string strMode = "template";
int nPoWType = GetMiningAlgorithm();
UniValue lpval = NullUniValue;
std::set<std::string> setClientRules;
int64_t nMaxVersionPreVB = -1;
if (!request.params[0].isNull())
{
const UniValue& oparam = request.params[0].get_obj();
const UniValue& modeval = find_value(oparam, "mode");
const UniValue& algoval = find_value(oparam, "algo");
if (modeval.isStr())
strMode = modeval.get_str();
else if (!modeval.isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (algoval.isStr()) {
std::string strAlgo = algoval.get_str();
if (strAlgo == "progpow")
nPoWType = MINE_PROGPOW;
else if (strAlgo == "randomx")
nPoWType = MINE_RANDOMX;
else if (strAlgo == "sha256d")
nPoWType = MINE_SHA256D;
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid algo");
}
else if (!algoval.isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid algo");
lpval = find_value(oparam, "longpollid");
if (strMode == "proposal")
{
const UniValue& dataval = find_value(oparam, "data");
if (!dataval.isStr())
throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
CBlock block;
if (!DecodeHexBlk(block, dataval.get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
uint256 hash = block.GetHash();
const CBlockIndex* pindex = LookupBlockIndex(hash);
if (pindex) {
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
return "duplicate-invalid";
return "duplicate-inconclusive";
}
CBlockIndex* const pindexPrev = chainActive.Tip();
// TestBlockValidity only supports blocks built on the current Tip
if (block.hashPrevBlock != pindexPrev->GetBlockHash())
return "inconclusive-not-best-prevblk";
CValidationState state;
TestBlockValidity(state, Params(), block, pindexPrev, false, true);
return BIP22ValidationResult(state);
}
const UniValue& aClientRules = find_value(oparam, "rules");
if (aClientRules.isArray()) {
for (unsigned int i = 0; i < aClientRules.size(); ++i) {
const UniValue& v = aClientRules[i];
setClientRules.insert(v.get_str());
}
} else {
// NOTE: It is important that this NOT be read if versionbits is supported
const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
if (uvMaxVersion.isNum()) {
nMaxVersionPreVB = uvMaxVersion.get_int64();
}
}
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Veil is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Veil is downloading blocks...");
switch (nPoWType) {
case MINE_PROGPOW:
return getblocktemplate_impl<CBlockHeader::PROGPOW_BLOCK>(strMode, lpval, setClientRules, nMaxVersionPreVB);
case MINE_SHA256D:
return getblocktemplate_impl<CBlockHeader::SHA256D_BLOCK>(strMode, lpval, setClientRules, nMaxVersionPreVB);
default:
return getblocktemplate_impl<CBlockHeader::RANDOMX_BLOCK>(strMode, lpval, setClientRules, nMaxVersionPreVB);
}
}
class submitblock_StateCatcher : public CValidationInterface
{
public:
uint256 hash;
bool found;
CValidationState state;
explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
protected:
void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
if (block.GetHash() != hash)
return;
found = true;
state = stateIn;
}
};
static UniValue pprpcsb(const JSONRPCRequest& request) {
if (request.fHelp || request.params.size() != 3) {
throw std::runtime_error(