forked from Bitcoin-ABC/bitcoin-abc
/
mining.cpp
1278 lines (1148 loc) · 55.3 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-2018 The Bitcoin Core 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 <blockvalidity.h>
#include <chain.h>
#include <chainparams.h>
#include <config.h>
#include <consensus/activation.h>
#include <consensus/consensus.h>
#include <consensus/params.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <fs.h>
#include <gbtlight.h>
#include <key_io.h>
#include <miner.h>
#include <net.h>
#include <policy/policy.h>
#include <pow.h>
#include <rpc/blockchain.h>
#include <rpc/mining.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <shutdown.h>
#include <txmempool.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <validation.h>
#include <validationinterface.h>
#include <warnings.h>
#include <univalue.h>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <list>
#include <memory>
/**
* 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) {
CBlockIndex *pb = ::ChainActive().Tip();
if (height >= 0 && height < ::ChainActive().Height()) {
pb = ::ChainActive()[height];
}
if (pb == nullptr || !pb->nHeight) {
return 0;
}
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0) {
lookup = pb->nHeight %
Params().GetConsensus().DifficultyAdjustmentInterval() +
1;
}
// If lookup is larger than chain, then set it to chain length.
if (lookup > pb->nHeight) {
lookup = pb->nHeight;
}
CBlockIndex *pb0 = pb;
int64_t minTime = pb0->GetBlockTime();
int64_t maxTime = minTime;
for (int i = 0; i < lookup; i++) {
pb0 = pb0->pprev;
int64_t 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;
}
arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
int64_t timeDiff = maxTime - minTime;
return workDiff.getdouble() / timeDiff;
}
static UniValue getnetworkhashps(const Config &config,
const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() > 2) {
throw std::runtime_error(
"getnetworkhashps ( nblocks height )\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 speed at the time when a "
"certain block was found.\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"
"\nResult:\n"
"x (numeric) Hashes per second estimated\n"
"\nExamples:\n" +
HelpExampleCli("getnetworkhashps", "") +
HelpExampleRpc("getnetworkhashps", ""));
}
LOCK(cs_main);
return GetNetworkHashPS(
!request.params[0].isNull() ? request.params[0].get_int() : 120,
!request.params[1].isNull() ? request.params[1].get_int() : -1);
}
UniValue generateBlocks(const Config &config,
std::shared_ptr<CReserveScript> coinbaseScript,
int nGenerate, uint64_t nMaxTries, bool keepScript) {
static const int nInnerLoopCount = 0x100000;
int nHeightEnd = 0;
int nHeight = 0;
{
// Don't keep cs_main locked.
LOCK(cs_main);
nHeight = ::ChainActive().Height();
nHeightEnd = nHeight + nGenerate;
}
const uint64_t nExcessiveBlockSize = config.GetMaxBlockSize();
unsigned int nExtraNonce = 0;
UniValue blockHashes(UniValue::VARR);
while (nHeight < nHeightEnd && !ShutdownRequested()) {
std::unique_ptr<CBlockTemplate> pblocktemplate(
BlockAssembler(config, g_mempool)
.CreateNewBlock(coinbaseScript->reserveScript));
if (!pblocktemplate.get()) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
}
CBlock *pblock = &pblocktemplate->block;
{
LOCK(cs_main);
IncrementExtraNonce(pblock, ::ChainActive().Tip(),
nExcessiveBlockSize, nExtraNonce);
}
while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount &&
!CheckProofOfWork(pblock->GetHash(), pblock->nBits,
config.GetChainParams().GetConsensus())) {
++pblock->nNonce;
--nMaxTries;
}
if (nMaxTries == 0) {
break;
}
if (pblock->nNonce == nInnerLoopCount) {
continue;
}
std::shared_ptr<const CBlock> shared_pblock =
std::make_shared<const CBlock>(*pblock);
if (!ProcessNewBlock(config, 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;
}
static UniValue generatetoaddress(const Config &config,
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 bitcoin 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(), config.GetChainParams());
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(config, coinbaseScript, nGenerate, nMaxTries, false);
}
static UniValue getmininginfo(const Config &config,
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"
" \"currentblocksize\": nnn, (numeric) The last block size\n"
" \"currentblocktx\": nnn, (numeric) The last block "
"transaction\n"
" \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
" \"networkhashps\": nnn, (numeric) The network 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", ""));
}
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.reserve(8);
obj.pushKV("blocks", int(::ChainActive().Height()), false);
obj.pushKV("currentblocksize", uint64_t(nLastBlockSize), false);
obj.pushKV("currentblocktx", uint64_t(nLastBlockTx), false);
obj.pushKV("difficulty", double(GetDifficulty(::ChainActive().Tip())), false);
obj.pushKV("networkhashps", getnetworkhashps(config, request), false);
obj.pushKV("pooledtx", uint64_t(g_mempool.size()), false);
obj.pushKV("chain", config.GetChainParams().NetworkIDString(), false);
obj.pushKV("warnings", GetWarnings("statusbar"), false);
return obj;
}
// NOTE: Unlike wallet RPC (which use BCH values), mining RPCs follow GBT (BIP
// 22) in using satoshi amounts
static UniValue prioritisetransaction(const Config &config,
const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 3) {
throw std::runtime_error(
"prioritisetransaction \"txid\" dummy 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"
" 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);
TxId txid(ParseHashV(request.params[0], "txid"));
Amount nAmount = request.params[2].get_int64() * SATOSHI;
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.");
}
g_mempool.PrioritiseTransaction(txid, nAmount);
return true;
}
// NOTE: Assumes a conclusive result; if result is inconclusive, it must be
// handled by caller
static UniValue BIP22ValidationResult(const Config &config,
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?";
}
/// Namespace for private data used by getblocktemplatelight and submitblocklight
namespace gbtl {
namespace {
// for use with unordered_map below
struct TrivialJobIdHasher {
std::size_t operator()(const JobId &jobId) const noexcept {
constexpr auto size = sizeof(std::size_t);
static_assert(JobId::size() >= size, "sizeof(JobId) must be >= sizeof(size_t)");
// this is faster than calling jobId.GetUint64(), especially for 32-bit.
// note: we must use memcpy to guarantee aligned access.
std::size_t ret;
std::memcpy(&ret, jobId.begin(), size);
return ret;
}
};
/// Lock for the below two data structures
Mutex gJobIdMut;
/// Cache of transactions for block templates returned from getblocktemplatelight, used by submitblocklight
std::unordered_map<JobId, std::vector<CTransactionRef>, TrivialJobIdHasher> gJobIdTxCache GUARDED_BY(gJobIdMut);
/// This list allows us to implement an LRU cache. We remove items when this grows too large.
std::list<JobId> gJobIdList GUARDED_BY(gJobIdMut);
/// Bytes used as header and footer for the getblocktemplatelight data files we write out.
const std::string kDataFileMagic = "GBT";
} // namespace
} // namespace gbtl
static UniValue getblocktemplatecommon(bool fLight, const Config &config, const JSONRPCRequest &request) {
const bool wrongParamSize = fLight ? request.params.size() > 2 : request.params.size() > 1;
if (request.fHelp || wrongParamSize) {
const std::string name = fLight ? "getblocktemplatelight" : "getblocktemplate";
const auto lightExtraArgs = fLight ? " \"additional_txs\"" : "";
const auto lightExtraArgDesc =
fLight
? "2. additional_txs (json array of strings, optional) Hex encoded transactions"
" to add to the block (each tx must be unique and valid)\n"
: "";
const auto resultsKeysMiscDesc =
fLight
? " \"job_id\" : \"xxxx\", (string) Job identifier as a hexadecimal hash160,"
" which is to be used as a parameter in a subsequent call to submitblocklight\n"
" \"merkle\" : [ \"xxxx\", ... ], (array) Hashes encoded in little-endian hexadecimal\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\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 (i.e., not including the block subsidy); "
"if this key is not present, fee is unknown and clients MUST NOT "
"assume there isn't one\n"
" \"sigops\" : n, (numeric) total "
"sigcheck count, as counted for purposes of block limits; if "
"this key is not present, sigcheck count is unknown and clients "
"MUST NOT assume it is zero\n"
" \"required\" : true|false (boolean) if provided "
"and true, this transaction must be in the final block\n"
" }\n"
" ,...\n"
" ],\n";
throw std::runtime_error(
name + " ( \"template_request\"" + lightExtraArgs +" )\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 BIP22 and BIP23:\n"
" "
"https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
" "
"https://github.com/bitcoin/bips/blob/master/bip-0023.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 BIP23), 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"
" }\n"
+ lightExtraArgDesc +
"\n"
"\nResult:\n"
"{\n"
" \"version\" : n, (numeric) The preferred "
"block version\n"
" \"previousblockhash\" : \"xxxx\", (string) The hash of "
"current highest block\n"
+ resultsKeysMiscDesc +
" \"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 sigchecks "
"in blocks\n"
" \"sizelimit\" : n, (numeric) limit of block "
"size\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"
"}\n"
"\nExamples:\n" +
HelpExampleCli(name, "") +
HelpExampleRpc(name, ""));
}
const auto t0 = GetTimeMicros(); // perf. info, used iff logging BCLog::RPC
LOCK(cs_main);
std::string strMode = "template";
const UniValue *lpval = &NullUniValue;
std::set<std::string> setClientRules;
if (!request.params[0].isNull()) {
const UniValue &oparam = request.params[0].get_obj();
const UniValue &modeval = oparam["mode"];
if (modeval.isStr()) {
strMode = modeval.get_str();
} else if (modeval.isNull()) {
/* Do nothing */
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
lpval = &oparam["longpollid"];
if (strMode == "proposal") {
const UniValue &dataval = 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");
}
const BlockHash hash = block.GetHash();
const CBlockIndex *pindex = LookupBlockIndex(hash);
if (pindex) {
if (pindex->IsValid(BlockValidity::SCRIPTS)) {
return "duplicate";
}
if (pindex->nStatus.isInvalid()) {
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, config.GetChainParams(), block, pindexPrev,
BlockValidationOptions(config)
.withCheckPoW(false)
.withCheckMerkleRoot(true));
return BIP22ValidationResult(config, state);
}
}
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,
"Bitcoin is not connected!");
}
if (IsInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Bitcoin is downloading blocks...");
}
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>
const std::string &lpstr = lpval->get_str();
hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
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);
WAIT_LOCK(g_best_block_mutex, lock);
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 (g_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?
}
struct LightResult {
const gbtl::JobId jobId;
const UniValue merkle;
};
// Update block
static CBlockIndex *pindexPrev;
static int64_t nStart;
static std::unique_ptr<CBlockTemplate> pblocktemplate;
static std::unique_ptr<LightResult> plightresult; // fLight mode only, cached result associated with pblocktemplate
if (pindexPrev != ::ChainActive().Tip() ||
(g_mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
GetTime() - nStart > 5)) {
// Clear pindexPrev so future calls make a new block, despite any
// failures from here on
pindexPrev = nullptr;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = g_mempool.GetTransactionsUpdated();
CBlockIndex *pindexPrevNew = ::ChainActive().Tip();
nStart = GetTime();
// Create new block
CScript scriptDummy = CScript() << OP_TRUE;
pblocktemplate =
BlockAssembler(config, g_mempool).CreateNewBlock(scriptDummy);
plightresult.reset();
if (!pblocktemplate) {
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
}
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
assert(pindexPrev);
// pointer for convenience
CBlock *pblock = &pblocktemplate->block;
// Temporary tx vector which is only used if we are in fLight mode and we have `additional_txs` specified by the
// client. This vector is the set of tx's in pblock *plus* `additional_txs` for this invocation.
// We use a std::unique_ptr here because it's lighter weight to construct than an empty std::vector would be. (The
// common case here is that this vector is unused, since `additional_txs` is an advanced feature).
using TxRefVector = std::vector<CTransactionRef>;
std::unique_ptr<TxRefVector> tmpBlockTxsWithAdditionalTxs;
// Below normally points to pblock->vtx -- *unless* we are in fLight mode and we have "additional_txs", in which
// case it points to the above vector (which will be made valid in that case).
TxRefVector *pvtx = &pblock->vtx;
if (fLight && request.params.size() > 1) {
// GBTLight only -- append transactions to be added from `additional_txs`. Note the contract with client code is
// these must be valid and unique. As a performance-saving measure we do not check them for validity or
// uniqueness.
//
// Also note: We do *NOT* append additional_txs to pblock! This would mean additional_txs get added each time
// we are called. However, pblock sticks around as global state for 5 seconds. `additional_txs` is a
// per-invocation parameter, and should not affect global state. So, instead, we must use the `pvtx` pointer
// above which will end up pointing to a private copy of pblock's tx data which we will create below.
const UniValue &injectedTxsHex = request.params[1].get_array(); // throws error to client if not array
const auto size = injectedTxsHex.size();
if (size) {
// copy pblock's txs since we need a private copy to modify the set of txs for this invocation
tmpBlockTxsWithAdditionalTxs = std::make_unique<TxRefVector>();
pvtx = tmpBlockTxsWithAdditionalTxs.get();
pvtx->reserve(pblock->vtx.size() + size); // final size is template tx's + additional_txs
pvtx->insert(pvtx->end(), pblock->vtx.begin(), pblock->vtx.end());
// next, inject additional_txs
for (size_t idx = 0; idx < size; ++idx) {
CMutableTransaction tx;
if (DecodeHexTx(tx, injectedTxsHex[idx].get_str())) {
pvtx->push_back(MakeTransactionRef(std::move(tx)));
} else {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR,
strprintf("additional_txs transaction %d decode failure", idx));
}
}
LogPrint(BCLog::RPC, "added %d additional_txs to block template\n", size);
const Consensus::Params &consensusParams = config.GetChainParams().GetConsensus();
if (IsMagneticAnomalyEnabled(consensusParams, pindexPrev)) {
auto start = pvtx->front()->IsCoinBase() ? std::next(pvtx->begin()) : pvtx->begin();
std::sort(start, pvtx->end(),
[](const CTransactionRef &a, const CTransactionRef &b) -> bool {
return a->GetId() < b->GetId();
});
}
// From this point forward the fLight code below must operate on the pvtx (private copy) of the tx set,
// and not pblock->vtx.
}
}
// Update nTime
UpdateTime(pblock, config.GetChainParams().GetConsensus(), pindexPrev);
pblock->nNonce = 0;
UniValue aCaps(UniValue::VARR);
aCaps.push_back("proposal");
uint160 jobId; // fLight version only, ends up in results["job_id"]
UniValue merkle(UniValue::VARR); // fLight version only, ends up in results["merkle"]
UniValue transactions(UniValue::VARR); // !fLight version only, ends up in results["transactions"]
if (fLight) {
assert(pvtx && (!tmpBlockTxsWithAdditionalTxs || pvtx == tmpBlockTxsWithAdditionalTxs.get()));
if (plightresult && pvtx == &pblock->vtx) {
// use cached light result since we know it's for this tx set (no additional_txs and result is valid)
LogPrint(BCLog::RPC, "Using cached merkle result\n");
jobId = plightresult->jobId; // copy jobId
merkle = plightresult->merkle; // copy UniValue
} else {
// merkle cached result not available (new template) or we have additional_txs and can't use cached result
LogPrint(BCLog::RPC, "Calculating new merkle result\n");
std::vector<uint256> vtxIdsNoCoinbase; // txs without coinbase
// we reserve 1 more than we need, because makeMerkleBranch may use a little more space
vtxIdsNoCoinbase.reserve(pvtx->size());
for (const auto &tx : *pvtx) {
if (tx->IsCoinBase())
continue;
vtxIdsNoCoinbase.push_back(tx->GetId());
}
// make merkleSteps and merkle branch
const auto merkleSteps = gbtl::MakeMerkleBranch(std::move(vtxIdsNoCoinbase));
merkle.reserve(merkleSteps.size());
// hash source is Hash160(hashPrevBlock + concatenation_of_all_merkle_step_hashes)
std::vector<uint8_t> hashSource;
hashSource.reserve(pblock->hashPrevBlock.size() + merkleSteps.size()*32);
hashSource.insert(hashSource.end(), pblock->hashPrevBlock.begin(), pblock->hashPrevBlock.end());
for (const auto &h : merkleSteps) {
merkle.push_back(h.GetHex()); // push UniValue
hashSource.insert(hashSource.end(), h.begin(), h.end()); // add to hash source
}
// Compute the jobId -- we will return this jobId to the client and also generate a cache entry based on it
// towards the end of this function.
jobId = Hash160(hashSource.begin(), hashSource.end());
// Finally, cache the merkle results if they were calculated from the tx's in pblock (no additional_txs).
if (pvtx == &pblock->vtx) {
plightresult.reset(new LightResult{jobId, merkle});
LogPrint(BCLog::RPC, "Saved merkle result\n");
}
}
} else {
// regular (!fLight) mode
transactions.reserve(pblock->vtx.size());
int index_in_template = 0;
for (const auto &it : pblock->vtx) {
const CTransaction &tx = *it;
if (tx.IsCoinBase()) {
index_in_template++;
continue;
}
UniValue entry(UniValue::VOBJ);
entry.pushKV("data", EncodeHexTx(tx), false);
entry.pushKV("txid", tx.GetId().GetHex(), false);
entry.pushKV("hash", tx.GetHash().GetHex(), false);
entry.pushKV("fee", pblocktemplate->entries[index_in_template].fees / SATOSHI, false);
int64_t nTxSigOps = pblocktemplate->entries[index_in_template].sigOpCount;
entry.pushKV("sigops", nTxSigOps, false);
transactions.push_back(std::move(entry));
index_in_template++;
}
}
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");
if (!fLight) {
aMutable.push_back("transactions");
} else {
aMutable.push_back("job_id");
aMutable.push_back("merkle");
}
aMutable.push_back("prevblock");
UniValue result(UniValue::VOBJ);
result.pushKV("capabilities", std::move(aCaps), false);
result.pushKV("version", pblock->nVersion, false);
result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex(), false);
if (!fLight) {
result.pushKV("transactions", std::move(transactions), false);
} else {
result.pushKV("job_id", jobId.GetHex(), false);
result.pushKV("merkle", std::move(merkle), false);
}
result.pushKV("coinbaseaux", std::move(aux), false);
result.pushKV("coinbasevalue", int64_t(pblock->vtx[0]->vout[0].nValue / SATOSHI), false);
result.pushKV("longpollid",
::ChainActive().Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast),
false);
result.pushKV("target", hashTarget.GetHex(), false);
result.pushKV("mintime", int64_t(pindexPrev->GetMedianTimePast()) + 1, false);
result.pushKV("mutable", std::move(aMutable), false);
result.pushKV("noncerange", "00000000ffffffff", false);
result.pushKV("sigoplimit", GetMaxBlockSigChecksCount(config.GetMaxBlockSize()), false);
result.pushKV("sizelimit", config.GetMaxBlockSize(), false);
result.pushKV("curtime", pblock->GetBlockTime(), false);
result.pushKV("bits", strprintf("%08x", pblock->nBits), false);
result.pushKV("height", int64_t(pindexPrev->nHeight) + 1, false);
if (fLight) {
// Note: this must be called with cs_main held (which is the case here)
gbtl::CacheAndSaveTxsToFile(jobId, pvtx);
}
LogPrint(BCLog::RPC, "getblocktemplatecommon: took %f secs\n", (GetTimeMicros() - t0) / 1e6);
return result;
}
static UniValue getblocktemplate(const Config &config, const JSONRPCRequest &request) {
return getblocktemplatecommon(false, config, request);
}
static UniValue getblocktemplatelight(const Config &config, const JSONRPCRequest &request) {
return getblocktemplatecommon(true, config, request);
}
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;
}
};
/// If jobId is not nullptr, we are in `submitblocklight` mode, otherwise we are in regular `submitblock` mode.
static UniValue submitblockcommon(const Config &config, const JSONRPCRequest &request,
const gbtl::JobId *jobId = nullptr) {
const auto t0 = GetTimeMicros(); // perf. logging, only used if BCLog::RPC
std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
CBlock &block = *blockptr;
if (!DecodeHexBlk(block, request.params[0].get_str())) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
auto tDeserTx = jobId ? GetTimeMicros() : 0; // for perf. logging iff BCLog::RPC is enabled
if (jobId) {
// submitblocklight version, client just sends header + coinbase and we add the rest
// of the tx's from a tx cache created previously in getblocktemplatelight
if (block.vtx.size() != 1 || !block.vtx[0]->IsCoinBase()) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block must contain a single coinbase tx (light version)");
}
if (!gbtl::GetTxsFromCache(*jobId, block)) {
// not found in in-memory cache, try our getblocktemplatelight job file cache
gbtl::LoadTxsFromFile(*jobId, block); // throws on failure
}
tDeserTx = GetTimeMicros() - tDeserTx; // perf.
} else {
// regular version -- requires full block from client
if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
}
}
const BlockHash hash = block.GetHash();
{
LOCK(cs_main);
const CBlockIndex *pindex = LookupBlockIndex(hash);
if (pindex) {
if (pindex->IsValid(BlockValidity::SCRIPTS)) {
return "duplicate";
}
if (pindex->nStatus.isInvalid()) {
return "duplicate-invalid";
}
}
}
bool new_block;
submitblock_StateCatcher sc(block.GetHash());
RegisterValidationInterface(&sc);
bool accepted =
ProcessNewBlock(config, blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block);
// We are only interested in BlockChecked which will have been dispatched
// in-thread, so no need to sync before unregistering.
UnregisterValidationInterface(&sc);
// Sync to ensure that the catcher's slots aren't executing when it goes out
// of scope and is deleted.
SyncWithValidationInterfaceQueue();
if (!new_block && accepted) {
return "duplicate";
}
if (!sc.found) {
return "inconclusive";
}
const auto result = BIP22ValidationResult(config, sc.state);
if (jobId) {
LogPrint(BCLog::RPC, "SubmitBlock (light) deserialize duration: %f seconds\n", tDeserTx / 1e6);
}
LogPrint(BCLog::RPC, "SubmitBlock total duration: %f seconds\n", (GetTimeMicros() - t0) / 1e6);
return result;
}
static UniValue submitblock(const Config &config, const JSONRPCRequest &request) {
// We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
"submitblock \"hexdata\" ( \"dummy\" )\n"
"\nAttempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
"\nArguments\n"
"1. \"hexdata\" (string, required) the hex-encoded block "
"data to submit\n"
"2. \"dummy\" (optional) dummy value, for compatibility "
"with BIP22. This value is ignored.\n"
"\nResult:\n"
"\nExamples:\n" +
HelpExampleCli("submitblock", "\"mydata\"") +
HelpExampleRpc("submitblock", "\"mydata\""));
}
return submitblockcommon(config, request);
}
static UniValue submitblocklight(const Config &config, const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 2) {
throw std::runtime_error(
"submitblocklight \"hexdata\" \"job_id\"\n"
"\nAttempts to submit a new block to the network, based on a previous call to getblocktemplatelight.\n"
"\nArguments\n"
"1. \"hexdata\" (string, required) The hex-encoded block data to submit. The block must have "
"exactly 1 transaction (coinbase). Additional transactions (if any) are appended from the light template.\n"
"2. \"job_id\" (string, required) Identifier of the light template from which to retrieve the "
"non-coinbase transactions. This job_id must be obtained from a previous call to getblocktemplatelight.\n"
"\nResult:\n"
"\nExamples:\n" +
HelpExampleCli("submitblocklight", "\"mydata\" \"myjobid\"") +
HelpExampleRpc("submitblocklight", "\"mydata\", \"myjobid\""));
}
const auto jobIdStr = request.params[1].get_str();
gbtl::JobId jobId; // uint160
if (!ParseHashStr(jobIdStr, jobId)) {
throw std::runtime_error("job_id must be a 40 character hexadecimal string (not '" + jobIdStr + "')");
}
return submitblockcommon(config, request, &jobId);
}
static UniValue submitheader(const Config &config,
const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error("submitheader \"hexdata\"\n"
"\nDecode the given hexdata as a header and "
"submit it as a candidate chain tip if valid."
"\nThrows when the header is invalid.\n"
"\nArguments\n"
"1. \"hexdata\" (string, required) the "
"hex-encoded block header data\n"
"\nResult:\n"
"None"
"\nExamples:\n" +
HelpExampleCli("submitheader", "\"aabbcc\"") +
HelpExampleRpc("submitheader", "\"aabbcc\""));
}
CBlockHeader h;
if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR,