-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathweb_server.cpp
More file actions
8275 lines (7427 loc) · 354 KB
/
Copy pathweb_server.cpp
File metadata and controls
8275 lines (7427 loc) · 354 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
// SPDX-License-Identifier: AGPL-3.0-or-later
#include "web_server.hpp"
#include "stratum_server.hpp"
#include <memory>
#include "address_utils.hpp"
#include "socket.hpp"
// Real coin daemon access (optional - only active when set_coin_node() is called)
#include <impl/ltc/coin/rpc.hpp>
#include <impl/ltc/coin/node_interface.hpp>
#include <core/coin/node_iface.hpp>
// Phase 4: embedded coin node interface
#include <impl/ltc/coin/template_builder.hpp>
#include <impl/ltc/share_messages.hpp>
#include <core/hash.hpp> // Hash(a,b) double-SHA256 for merkle computation
#include <core/random.hpp> // core::random::random_float for probabilistic fee
#include <core/target_utils.hpp> // chain::bits_to_target
#include <btclibs/util/strencodings.h> // ParseHex, HexStr
#include <crypto/scrypt.h> // scrypt_1024_1_1_256 for Litecoin PoW
#include <crypto/sha256.h> // CSHA256 for P2PK→P2PKH conversion
#include <crypto/ripemd160.h> // CRIPEMD160 for Hash160
#include <c2pool/merged/merged_mining.hpp> // Integrated merged mining
#include <impl/ltc/config_pool.hpp> // PoolConfig::is_testnet for donation addr
#include <iomanip>
#include <sstream>
#include <set>
#include <ctime>
#include <chrono>
#include <cmath>
#include <fstream>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <boost/algorithm/string.hpp>
#include "btclibs/base58.h"
#include "btclibs/bech32.h"
#include "filesystem.hpp"
namespace core {
static std::string to_hex(const std::vector<unsigned char>& data)
{
return HexStr(std::span<const unsigned char>(data.data(), data.size()));
}
/// MiningInterface Implementation
MiningInterface::MiningInterface(bool testnet, std::shared_ptr<IMiningNode> node, Blockchain blockchain)
: m_work_id_counter(1)
, m_testnet(testnet)
, m_blockchain(blockchain)
, m_node(node)
, m_address_validator(blockchain, testnet ? Network::TESTNET : Network::MAINNET)
, m_payout_manager(std::make_unique<c2pool::payout::PayoutManager>(1.0, 86400)) // 1% fee, 24h window
, m_solo_mode(false)
, m_solo_address("")
{
setup_methods();
}
void MiningInterface::setup_methods()
{
// Core mining methods - explicitly cast to MethodHandle
Add("getwork", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getwork();
}));
Add("submitwork", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.size() < 3) {
throw jsonrpccxx::JsonRpcException(-1, "submitwork requires 3 parameters");
}
return submitwork(params[0], params[1], params[2]);
}));
Add("getblocktemplate", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
nlohmann::json template_params = params.empty() ? nlohmann::json::array() : params;
return getblocktemplate(template_params);
}));
Add("submitblock", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.empty()) {
throw jsonrpccxx::JsonRpcException(-1, "submitblock requires hex data parameter");
}
return submitblock(params[0]);
}));
// Pool info methods
Add("getinfo", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getinfo();
}));
Add("getstats", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getstats();
}));
Add("getpeerinfo", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getpeerinfo();
}));
// Stratum methods
Add("mining.subscribe", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
std::string user_agent = params.empty() ? "" : params[0];
return mining_subscribe(user_agent);
}));
Add("mining.authorize", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.size() < 2) {
throw jsonrpccxx::JsonRpcException(-1, "mining.authorize requires username and password");
}
return mining_authorize(params[0], params[1]);
}));
Add("mining.submit", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.size() < 5) {
throw jsonrpccxx::JsonRpcException(-1, "mining.submit requires 5 parameters");
}
return mining_submit(params[0], params[1], "", params[2], params[3], params[4]);
}));
// Enhanced payout and coinbase methods
Add("validate_address", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.empty()) {
throw jsonrpccxx::JsonRpcException(-1, "validate_address requires address parameter");
}
return validate_address(params[0]);
}));
Add("build_coinbase", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.empty()) {
throw jsonrpccxx::JsonRpcException(-1, "build_coinbase requires parameters object");
}
return build_coinbase(params);
}));
Add("validate_coinbase", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.empty()) {
throw jsonrpccxx::JsonRpcException(-1, "validate_coinbase requires coinbase hex parameter");
}
return validate_coinbase(params[0]);
}));
Add("getblockcandidate", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getblockcandidate(params);
}));
Add("getpayoutinfo", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getpayoutinfo();
}));
Add("getminerstats", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getminerstats();
}));
Add("setmessageblob", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (params.empty()) {
throw jsonrpccxx::JsonRpcException(-1, "setmessageblob requires hex blob parameter");
}
return setmessageblob(params[0]);
}));
Add("getmessageblob", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
return getmessageblob();
}));
// Explorer JSON-RPC adapter — allows Python explorer to talk to c2pool
// as if it were a standard Bitcoin/Litecoin daemon.
Add("getblockchaininfo", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (has_explorer_chaininfo_fn())
return call_explorer_chaininfo(primary_chain_key());
return nlohmann::json{{"error", "explorer not enabled"}};
}));
Add("getblockhash", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (!has_explorer_blockhash_fn() || params.empty())
return nullptr;
uint32_t h = params[0].get<uint32_t>();
return call_explorer_blockhash(h, primary_chain_key());
}));
Add("getblock", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (!has_explorer_getblock_fn() || params.empty())
return nullptr;
std::string hash = params[0].get<std::string>();
return call_explorer_getblock(hash, primary_chain_key());
}));
Add("getmempoolinfo", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (has_explorer_mempoolinfo_fn())
return call_explorer_mempoolinfo(primary_chain_key());
return nlohmann::json::object();
}));
Add("getrawmempool", jsonrpccxx::MethodHandle([this](const nlohmann::json& params) -> nlohmann::json {
if (has_explorer_rawmempool_fn()) {
bool verbose = (!params.empty() && params[0].get<bool>());
return call_explorer_rawmempool(primary_chain_key(), verbose, 500);
}
return nlohmann::json::array();
}));
}
void MiningInterface::load_transition_blobs(const std::string& dir_path)
{
namespace fs = std::filesystem;
if (!fs::is_directory(dir_path)) return;
int loaded = 0;
for (const auto& entry : fs::directory_iterator(dir_path)) {
if (!entry.is_regular_file()) continue;
auto ext = entry.path().extension().string();
if (ext != ".hex") continue;
// Read hex file
std::ifstream f(entry.path());
if (!f) continue;
std::string hex_str;
std::getline(f, hex_str);
// Trim whitespace
while (!hex_str.empty() && (hex_str.back() == '\n' || hex_str.back() == '\r' || hex_str.back() == ' '))
hex_str.pop_back();
if (hex_str.empty()) continue;
auto blob = ParseHex(hex_str);
if (blob.empty()) continue;
auto unpacked = ltc::unpack_share_messages(blob.data(), blob.size());
if (!unpacked.decrypted) continue;
auto now = static_cast<uint32_t>(std::time(nullptr));
for (const auto& msg : unpacked.messages) {
// Decode payload as UTF-8 text, try JSON
std::string payload_text(msg.payload.begin(), msg.payload.end());
nlohmann::json payload_json;
try { payload_json = nlohmann::json::parse(payload_text); } catch (...) {}
if (msg.msg_type == ltc::MSG_TRANSITION_SIGNAL && m_cached_transition_message.is_null()) {
nlohmann::json tmsg = nlohmann::json::object();
if (payload_json.is_object()) {
tmsg["msg"] = payload_json.value("msg", "");
tmsg["url"] = payload_json.value("url", "");
tmsg["urgency"] = payload_json.value("urg", "info");
tmsg["from_ver"] = payload_json.value("from", "");
tmsg["to_ver"] = payload_json.value("to", "");
} else {
tmsg["msg"] = payload_text;
tmsg["urgency"] = "info";
}
tmsg["timestamp"] = msg.timestamp;
tmsg["verified"] = true;
tmsg["authority"] = (msg.wire_flags & ltc::FLAG_PROTOCOL_AUTHORITY) != 0;
m_cached_transition_message = tmsg;
++loaded;
} else if (msg.msg_type == ltc::MSG_POOL_ANNOUNCE || msg.msg_type == ltc::MSG_EMERGENCY) {
nlohmann::json ann = nlohmann::json::object();
ann["type"] = (msg.msg_type == ltc::MSG_EMERGENCY) ? "EMERGENCY" : "POOL_ANNOUNCE";
ann["type_id"] = msg.msg_type;
ann["timestamp"] = msg.timestamp;
ann["age"] = (now > msg.timestamp) ? static_cast<int>(now - msg.timestamp) : 0;
ann["verified"] = true;
ann["authority"] = (msg.wire_flags & ltc::FLAG_PROTOCOL_AUTHORITY) != 0;
if (payload_json.is_object()) {
ann["text"] = payload_json.value("msg", payload_json.value("text", ""));
ann["urgency"] = payload_json.value("urg", payload_json.value("urgency", "info"));
ann["url"] = payload_json.value("url", "");
} else {
ann["text"] = payload_text;
ann["urgency"] = (msg.msg_type == ltc::MSG_EMERGENCY) ? "alert" : "info";
}
m_cached_authority_announcements.push_back(ann);
++loaded;
}
}
}
if (loaded > 0)
LOG_INFO << "Messaging: loaded " << loaded << " transition message(s) from " << dir_path;
}
void MiningInterface::set_operator_message_blob(const std::vector<unsigned char>& blob)
{
std::lock_guard<std::mutex> lock(m_message_blob_mutex);
m_operator_message_blob = blob;
}
std::vector<unsigned char> MiningInterface::get_operator_message_blob() const
{
std::lock_guard<std::mutex> lock(m_message_blob_mutex);
return m_operator_message_blob;
}
// ─── Live coin-daemon integration ────────────────────────────────────────────
void MiningInterface::set_coin_node(core::coin::ICoinNode* node)
{
m_coin_node = node;
LOG_INFO << "MiningInterface: coin node " << (node ? "attached" : "detached");
}
void MiningInterface::set_on_block_submitted(std::function<void(const std::string&, int)> fn)
{
m_on_block_submitted = std::move(fn);
}
void MiningInterface::set_on_block_relay(std::function<void(const std::string&)> fn)
{
m_on_block_relay = std::move(fn);
}
void MiningInterface::set_rpc_submit_fallback(std::function<std::string(const std::string&)> fn)
{
m_rpc_submit_fallback = std::move(fn);
}
bool MiningInterface::has_merged_chain(uint32_t chain_id) const
{
if (!m_mm_manager) return false;
return m_mm_manager->get_chain_rpc(chain_id) != nullptr;
}
std::string MiningInterface::get_node_fee_hash160() const
{
// Extract hash160 from scriptPubKey (P2PKH, P2SH, or P2WPKH)
int h160_off = -1;
auto sz = m_node_fee_script.size();
if (sz == 25 && m_node_fee_script[0] == 0x76 &&
m_node_fee_script[1] == 0xa9 && m_node_fee_script[2] == 0x14)
h160_off = 3; // P2PKH
else if (sz == 23 && m_node_fee_script[0] == 0xa9 &&
m_node_fee_script[1] == 0x14)
h160_off = 2; // P2SH
else if (sz == 22 && m_node_fee_script[0] == 0x00 &&
m_node_fee_script[1] == 0x14)
h160_off = 2; // P2WPKH
if (h160_off < 0) return {};
static const char* HEX = "0123456789abcdef";
std::string h160;
h160.reserve(40);
for (int i = h160_off; i < h160_off + 20; ++i) {
h160 += HEX[m_node_fee_script[i] >> 4];
h160 += HEX[m_node_fee_script[i] & 0x0f];
}
return h160;
}
bool MiningInterface::check_merged_mining(const std::string& block_hex,
const std::string& extranonce1,
const std::string& extranonce2,
const JobSnapshot* job)
{
if (!m_mm_manager) return false;
// Extract 80-byte parent header (first 160 hex chars)
if (block_hex.size() < 160) return false;
std::string parent_header_hex = block_hex.substr(0, 160);
// Compute parent block hash (scrypt for LTC)
auto hdr_bytes = ParseHex(parent_header_hex);
uint256 parent_hash;
scrypt_1024_1_1_256(reinterpret_cast<const char*>(hdr_bytes.data()),
reinterpret_cast<char*>(parent_hash.data()));
// Build stripped coinbase tx (no witness) — use per-job parts when available
std::string coinbase_hex;
std::vector<std::string> merkle_branches_copy;
{
std::lock_guard<std::mutex> lock(m_work_mutex);
const std::string& cb1 = job ? job->coinb1 : m_cached_coinb1;
const std::string& cb2 = job ? job->coinb2 : m_cached_coinb2;
coinbase_hex = cb1 + extranonce1 + extranonce2 + cb2;
merkle_branches_copy = job ? job->merkle_branches : m_cached_merkle_branches;
}
auto before = m_mm_manager->get_discovered_blocks().size();
m_mm_manager->try_submit_merged_blocks(
parent_header_hex,
coinbase_hex,
merkle_branches_copy,
0, // coinbase is always at index 0
parent_hash);
auto after = m_mm_manager->get_discovered_blocks().size();
return after > before; // true if a merged block was found
}
// ─── Witness merkle root computation ──────────────────────────────────────────
// Compute the merkle root of a list of hashes (standard Bitcoin merkle tree).
static uint256 compute_witness_merkle_root(std::vector<uint256> hashes) {
if (hashes.empty()) return uint256();
while (hashes.size() > 1) {
if (hashes.size() % 2 == 1)
hashes.push_back(hashes.back());
std::vector<uint256> next;
next.reserve(hashes.size() / 2);
for (size_t i = 0; i + 1 < hashes.size(); i += 2)
next.push_back(Hash(hashes[i], hashes[i + 1]));
hashes = std::move(next);
}
return hashes[0];
}
// P2Pool witness nonce: '[Pool]' repeated 4 times = 32 bytes
static const unsigned char P2POOL_WITNESS_NONCE_BYTES[32] = {
0x5b, 0x50, 0x32, 0x50, 0x6f, 0x6f, 0x6c, 0x5d,
0x5b, 0x50, 0x32, 0x50, 0x6f, 0x6f, 0x6c, 0x5d,
0x5b, 0x50, 0x32, 0x50, 0x6f, 0x6f, 0x6c, 0x5d,
0x5b, 0x50, 0x32, 0x50, 0x6f, 0x6f, 0x6c, 0x5d,
};
// Compute the P2Pool witness commitment hex from a raw witness merkle root.
// Returns the full script hex: "6a24aa21a9ed" + SHA256d(root || '[Pool]'*4)
static std::string compute_p2pool_witness_commitment_hex(const uint256& witness_root) {
uint256 nonce;
std::memcpy(nonce.data(), P2POOL_WITNESS_NONCE_BYTES, 32);
uint256 commitment = Hash(witness_root, nonce);
return "6a24aa21a9ed" + HexStr(std::span<const unsigned char>(
reinterpret_cast<const unsigned char*>(commitment.data()), 32));
}
// ─── Merkle branch computation ────────────────────────────────────────────────
// Given the list of transaction hashes EXCLUDING the coinbase
// (i.e. from getblocktemplate tx list), compute the Stratum merkle_branches
// array that enables the miner to reconstruct the merkle root as:
// hash = coinbase_hash
// for b in branches: hash = Hash(hash, b)
/*static*/ std::vector<std::string>
MiningInterface::compute_merkle_branches(std::vector<std::string> tx_hashes_hex)
{
if (tx_hashes_hex.empty()) return {};
// Convert hex strings to uint256
std::vector<uint256> current;
current.reserve(tx_hashes_hex.size());
for (const auto& h : tx_hashes_hex) {
uint256 u;
u.SetHex(h);
current.push_back(u);
}
std::vector<std::string> branches;
// At each tree level: the first element of `current` is the sibling of our
// path node. Consume it as a branch, then build the next level from the rest.
while (!current.empty()) {
// Store in internal byte order (Stratum format: raw SHA256d output hex)
branches.push_back(HexStr(std::span<const unsigned char>(current[0].data(), 32)));
current.erase(current.begin()); // remove the sibling we just used
if (current.empty()) break;
// If the remaining list is odd, duplicate the last entry
if (current.size() % 2 == 1)
current.push_back(current.back());
// Pair and hash for the next level
std::vector<uint256> next;
next.reserve(current.size() / 2);
for (size_t i = 0; i + 1 < current.size(); i += 2)
next.push_back(Hash(current[i], current[i + 1]));
current = std::move(next);
}
return branches;
}
// ─── Merkle root reconstruction ──────────────────────────────────────────────
// Given a fully-assembled coinbase transaction in hex and the Stratum merkle
// branches, reconstruct the block's merkle root.
// coinbase_hash = dSHA256(coinbase_bytes)
// for each branch: coinbase_hash = dSHA256(coinbase_hash || branch)
/*static*/ uint256
MiningInterface::reconstruct_merkle_root(const std::string& coinbase_hex,
const std::vector<std::string>& merkle_branches)
{
auto coinbase_bytes = ParseHex(coinbase_hex);
uint256 hash = Hash(coinbase_bytes);
for (const auto& branch_hex : merkle_branches) {
// Branches are in internal byte order (Stratum format)
uint256 branch;
auto branch_bytes = ParseHex(branch_hex);
if (branch_bytes.size() == 32)
memcpy(branch.begin(), branch_bytes.data(), 32);
hash = Hash(hash, branch);
}
return hash;
}
// ─── Build full block from Stratum parameters ────────────────────────────────
// Assembles the block header + full transaction list from the cached template
// and the miner's Stratum submit data.
std::string
MiningInterface::build_block_from_stratum(const std::string& extranonce1,
const std::string& extranonce2,
const std::string& ntime,
const std::string& nonce,
const JobSnapshot* job) const
{
std::lock_guard<std::mutex> lock(m_work_mutex);
// When a JobSnapshot is provided, use its frozen template data.
// Otherwise fall back to the live m_cached_template (legacy/solo path).
const std::string& coinb1 = job ? job->coinb1 : m_cached_coinb1;
const std::string& coinb2 = job ? job->coinb2 : m_cached_coinb2;
if (coinb1.empty())
return {};
// Reconstruct coinbase: coinb1 + extranonce1 + extranonce2 + coinb2
std::string coinbase_hex = coinb1 + extranonce1 + extranonce2 + coinb2;
// Reconstruct merkle root using the job's branches (or the live cache)
const auto& branches = job ? job->merkle_branches : m_cached_merkle_branches;
uint256 merkle_root = reconstruct_merkle_root(coinbase_hex, branches);
// Block header fields — from the job snapshot or the live template
uint32_t version;
uint256 prev_hash;
std::string bits_hex;
bool segwit;
if (job) {
version = job->version ? job->version : 536870912U;
prev_hash.SetHex(job->gbt_prevhash.empty() ? std::string(64, '0') : job->gbt_prevhash);
bits_hex = job->nbits.empty() ? "1d00ffff" : job->nbits;
segwit = job->segwit_active;
} else {
if (!m_work_valid || m_cached_template.is_null())
return {};
version = m_cached_template.value("version", 536870912U);
prev_hash.SetHex(m_cached_template.value("previousblockhash", std::string(64, '0')));
bits_hex = m_cached_template.value("bits", std::string("1d00ffff"));
segwit = m_segwit_active;
}
// ntime and nonce from miner (hex strings, 4 bytes each, BE from Stratum)
auto ntime_bytes = ParseHex(ntime);
auto nonce_bytes = ParseHex(nonce);
auto bits_bytes = ParseHex(bits_hex);
// Stratum/GBT sends these as big-endian hex; block header needs little-endian
std::reverse(ntime_bytes.begin(), ntime_bytes.end());
std::reverse(nonce_bytes.begin(), nonce_bytes.end());
std::reverse(bits_bytes.begin(), bits_bytes.end());
std::ostringstream block;
// version LE
block << std::hex << std::setfill('0')
<< std::setw(2) << ((version ) & 0xff)
<< std::setw(2) << ((version >> 8) & 0xff)
<< std::setw(2) << ((version >> 16) & 0xff)
<< std::setw(2) << ((version >> 24) & 0xff);
// prev_hash (already internal byte order in uint256)
block << HexStr(std::span<const unsigned char>(prev_hash.data(), 32));
// merkle_root
block << HexStr(std::span<const unsigned char>(merkle_root.data(), 32));
// ntime LE
block << HexStr(std::span<const unsigned char>(ntime_bytes.data(), ntime_bytes.size()));
// nbits LE
block << HexStr(std::span<const unsigned char>(bits_bytes.data(), bits_bytes.size()));
// nonce LE
block << HexStr(std::span<const unsigned char>(nonce_bytes.data(), nonce_bytes.size()));
// Transaction count (varint) + coinbase + rest of transactions
const std::vector<std::string> tx_list = (job && job->tx_data) ? *job->tx_data : std::vector<std::string>{};
// If no job snapshot, collect tx data from the live template
std::vector<std::string> live_tx_data;
if (!job && m_cached_template.contains("transactions")) {
for (const auto& tx : m_cached_template["transactions"])
if (tx.contains("data"))
live_tx_data.push_back(tx["data"].get<std::string>());
}
const auto& txs_hex = job ? tx_list : live_tx_data;
uint64_t tx_count = 1 + txs_hex.size(); // coinbase + template txs
// Simple varint encoding
if (tx_count < 0xfd)
block << std::hex << std::setfill('0') << std::setw(2) << tx_count;
else
block << "fd" << std::hex << std::setfill('0')
<< std::setw(2) << (tx_count & 0xff)
<< std::setw(2) << ((tx_count >> 8) & 0xff);
// Coinbase transaction: coinb1 + extranonce1 + extranonce2 + coinb2 is the
// non-witness (stripped) serialization used for txid computation and the
// Stratum merkle tree. For segwit blocks the block body must contain the
// witness serialization which wraps the same data with marker/flag bytes
// and a coinbase witness stack (BIP141: 1 item of 32 bytes = P2Pool nonce).
if (segwit) {
// Non-witness: [version 4B][input_count 1B][inputs…][outputs…][locktime 4B]
// Witness: [version 4B][00 01][input_count 1B][inputs…][outputs…]
// [witness_stack][locktime 4B]
block << coinbase_hex.substr(0, 8) // version (4 bytes = 8 hex)
<< "0001" // segwit marker + flag
<< coinbase_hex.substr(8, coinbase_hex.size() - 16) // inputs + outputs
<< "01" // 1 stack item for the single coinbase input
<< "20" // 32 bytes
// P2Pool witness nonce: '[Pool]' * 4
<< "5b5032506f6f6c5d5b5032506f6f6c5d5b5032506f6f6c5d5b5032506f6f6c5d"
<< coinbase_hex.substr(coinbase_hex.size() - 8); // locktime
} else {
block << coinbase_hex;
}
// Remaining transactions from the template
for (const auto& tx_hex : txs_hex) {
block << tx_hex;
}
// MWEB extension block (Litecoin): append HogEx flag + MWEB data
const std::string& mweb_data = job ? job->mweb : m_cached_mweb;
if (!mweb_data.empty()) {
block << "01" << mweb_data;
} else if (segwit) {
// MWEB not yet bootstrapped — litecoind will reject with "mweb-missing".
// Return empty string to signal invalid block — caller should skip submission.
LOG_WARNING << "[EMB-LTC] Block built WITHOUT MWEB — skipping submission"
<< " (MWEB state not yet bootstrapped from P2P full block)";
return {};
}
return block.str();
}
// ─── Coinbase parts construction ─────────────────────────────────────────────
// Encode an integer as a minimal CScriptNum (sign-magnitude, little-endian)
// prefixed by a 1-byte push-data length. Used for BIP34 block height.
static std::string encode_height_pushdata(int height)
{
std::ostringstream os;
if (height == 0) {
os << "0100"; // PUSH1 [0x00]
return os.str();
}
std::vector<uint8_t> bytes;
uint32_t v = static_cast<uint32_t>(height);
while (v > 0) {
bytes.push_back(static_cast<uint8_t>(v & 0xFF));
v >>= 8;
}
// If MSB is set, add a 0x00 sign byte (positive)
if (bytes.back() & 0x80)
bytes.push_back(0x00);
// PUSHDATA opcode = len, then the data bytes (already little-endian)
os << std::hex << std::setfill('0') << std::setw(2) << bytes.size();
for (uint8_t b : bytes)
os << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(b);
return os.str();
}
// Encode a uint64 amount as 8 little-endian hex bytes
static std::string encode_le64(uint64_t v)
{
std::ostringstream os;
for (int i = 0; i < 8; ++i)
os << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>((v >> (i * 8)) & 0xFF);
return os.str();
}
// Build a P2PKH output script OP_DUP OP_HASH160 <hash160> OP_EQUALVERIFY OP_CHECKSIG
// `hash160_hex` must be 40 hex chars (20 bytes).
// Returns the (length-prefixed) complete output script hex.
static std::string p2pkh_script(const std::string& hash160_hex)
{
// 1976a914{hash160}88ac
std::ostringstream s;
s << "19" << "76a914" << hash160_hex << "88ac";
return s.str();
}
/*static*/ uint256 MiningInterface::compute_the_state_root(
const std::vector<std::pair<std::string,uint64_t>>& pplns_outputs,
uint32_t chain_length, uint32_t block_height, uint32_t bits)
{
// THE State Root = MerkleRoot(L-1, L0, L+1, epoch_meta)
// L-1 and L+1 are zero placeholders until THE activates.
// Layer 0: SHA256d of sorted PPLNS output table
uint256 layer_0;
{
PackStream ps;
for (const auto& [script, amount] : pplns_outputs)
{
ps << static_cast<uint64_t>(amount);
uint8_t len = static_cast<uint8_t>(std::min(script.size() / 2, size_t(255)));
ps << len;
}
auto span = ps.get_span();
if (span.size() > 0)
layer_0 = Hash(std::span<const unsigned char>(
reinterpret_cast<const unsigned char*>(span.data()), span.size()));
}
// Epoch metadata: SHA256d(chain_length || block_height || bits)
uint256 epoch_meta;
{
PackStream ps;
ps << chain_length;
ps << block_height;
ps << bits;
auto span = ps.get_span();
epoch_meta = Hash(std::span<const unsigned char>(
reinterpret_cast<const unsigned char*>(span.data()), span.size()));
}
// Layer -1 and +1: zero (placeholders)
uint256 layer_m1; // zero
uint256 layer_p1; // zero
// 4-leaf Merkle tree: hash pairs, then hash the pair of pairs
// Concatenate each pair into a 64-byte buffer and SHA256d
auto hash_pair = [](const uint256& a, const uint256& b) -> uint256 {
unsigned char buf[64];
std::memcpy(buf, a.data(), 32);
std::memcpy(buf + 32, b.data(), 32);
return Hash(std::span<const unsigned char>(buf, 64));
};
uint256 left = hash_pair(layer_m1, layer_0);
uint256 right = hash_pair(layer_p1, epoch_meta);
return hash_pair(left, right);
}
/*static*/ std::pair<std::string, std::string>
MiningInterface::build_coinbase_parts(
const nlohmann::json& tmpl,
uint64_t coinbase_value,
const std::vector<std::pair<std::string,uint64_t>>& outputs,
bool raw_scripts,
const std::vector<uint8_t>& mm_commitment,
const std::string& witness_commitment_hex,
const std::string& ref_hash_hex,
const uint256& the_state_root,
const std::string& coinbase_text)
{
// P2Pool-compatible coinbase split: extranonce goes into last_txout_nonce,
// NOT into the scriptSig. This way:
// - scriptSig is fixed (no miner-variable data) → share.m_coinbase is deterministic
// - hash_link prefix (everything before last 44 bytes) matches generate_transaction
// - en1+en2 fill the 8-byte last_txout_nonce in OP_RETURN (part of hash_link suffix)
//
// coinb1 = everything up to and including ref_hash in the OP_RETURN output
// coinb2 = locktime only ("00000000")
// coinbase = coinb1 + extranonce1(4B) + extranonce2(4B) + coinb2
//
// The en1+en2 become the P2Pool last_txout_nonce (8 bytes).
//
// Output ordering (must match generate_share_transaction()):
// 1. Segwit witness commitment (if present) — value=0
// 2. PPLNS payout outputs (sorted by amount asc, script asc) + donation last
// 3. OP_RETURN commitment (0x6a28 + ref_hash + last_txout_nonce) — value=0
const int height = tmpl.value("height", 1);
const std::string height_hex = encode_height_pushdata(height);
const int height_bytes = static_cast<int>(height_hex.size()) / 2;
// Dynamic tag: "/c2pool/" (default) or operator --coinbase-text
// When operator provides text, /c2pool/ tag is replaced — c2pool is
// always identified by the combined donation address in coinbase outputs.
const std::string default_tag = "/c2pool/";
const std::string& tag_text = coinbase_text.empty() ? default_tag : coinbase_text;
static const char* HEXC = "0123456789abcdef";
std::string tag_hex;
tag_hex.reserve(tag_text.size() * 2);
for (char c : tag_text) {
uint8_t b = static_cast<uint8_t>(c);
tag_hex += HEXC[b >> 4];
tag_hex += HEXC[b & 0x0f];
}
const int tag_bytes = static_cast<int>(tag_text.size());
// AuxPoW merged mining commitment
std::string mm_hex;
if (!mm_commitment.empty()) {
static const char* HEX = "0123456789abcdef";
mm_hex.reserve(mm_commitment.size() * 2);
for (uint8_t b : mm_commitment) {
mm_hex += HEX[b >> 4];
mm_hex += HEX[b & 0x0f];
}
}
const int mm_bytes = static_cast<int>(mm_commitment.size());
// THE state root: 32 bytes embedded in scriptSig (V37 prep — zero cost)
// Layout: [height][mm_commit]["/c2pool/"][the_state_root(32)][optional operator text]
std::string state_root_hex;
const int state_root_bytes = the_state_root.IsNull() ? 0 : 32;
if (state_root_bytes > 0) {
static const char* HEX = "0123456789abcdef";
state_root_hex.reserve(64);
for (int i = 0; i < 32; ++i) {
unsigned char c = the_state_root.data()[i];
state_root_hex += HEX[c >> 4];
state_root_hex += HEX[c & 0x0f];
}
}
// ScriptSig: height + mm_commitment + tag + state_root (NO extranonce!)
// Each element (mm, tag) gets a 1-byte push opcode prefix (matching create_push_script)
// state_root is raw (no push opcode, like coinbaseflags in p2pool)
const int mm_push_overhead = (mm_bytes > 0) ? 1 : 0;
const int tag_push_overhead = (tag_bytes > 0) ? 1 : 0;
const int script_total = height_bytes + mm_push_overhead + mm_bytes
+ tag_push_overhead + tag_bytes + state_root_bytes;
// Build coinb1: entire coinbase TX up to and including ref_hash in OP_RETURN
std::ostringstream coinb1;
coinb1 << "01000000" // version
<< "01" // 1 input
<< "0000000000000000000000000000000000000000000000000000000000000000"
<< "ffffffff" // previous index
<< std::hex << std::setfill('0') << std::setw(2) << script_total
<< height_hex;
// scriptSig elements with push opcodes (matching p2pool's create_push_script):
// Each datum gets its own length-prefix push opcode.
auto emit_push = [&](std::ostringstream& os, const std::string& data_hex) {
size_t len = data_hex.size() / 2;
if (len > 0 && len < 76)
os << std::hex << std::setfill('0') << std::setw(2) << len;
os << data_hex;
};
if (!mm_hex.empty()) emit_push(coinb1, mm_hex);
if (!tag_hex.empty()) emit_push(coinb1, tag_hex);
// state_root appended raw (like p2pool's coinbaseflags)
if (!state_root_hex.empty())
coinb1 << state_root_hex;
coinb1 << "ffffffff"; // sequence = 0xFFFFFFFF
// Count outputs: [segwit?] + PPLNS + OP_RETURN
size_t num_outputs = outputs.size();
if (!witness_commitment_hex.empty()) ++num_outputs;
if (!ref_hash_hex.empty()) ++num_outputs;
// Varint-encode output count
if (num_outputs < 0xfd)
coinb1 << std::hex << std::setfill('0') << std::setw(2) << num_outputs;
else
coinb1 << "fd" << std::hex << std::setfill('0')
<< std::setw(2) << (num_outputs & 0xff)
<< std::setw(2) << ((num_outputs >> 8) & 0xff);
// Output 1: Segwit witness commitment (FIRST, matching generate_share_transaction)
if (!witness_commitment_hex.empty()) {
coinb1 << encode_le64(0); // 0 satoshis
size_t wc_len = witness_commitment_hex.size() / 2;
coinb1 << std::hex << std::setfill('0') << std::setw(2) << wc_len;
coinb1 << witness_commitment_hex;
{
static int wc_log = 0;
if (wc_log++ < 5)
LOG_INFO << "[WC-COINBASE] witness_commitment(" << wc_len << ")=" << witness_commitment_hex.substr(0, 80);
}
}
// Outputs 2..N: PPLNS payouts + donation (already sorted by caller)
for (const auto& [addr, amount] : outputs) {
coinb1 << encode_le64(amount);
if (raw_scripts) {
size_t script_len = addr.size() / 2;
coinb1 << std::hex << std::setfill('0') << std::setw(2) << script_len;
coinb1 << addr;
} else {
coinb1 << p2pkh_script(addr);
}
}
// Output N+1: OP_RETURN commitment (LAST, matching generate_share_transaction)
// Script = 6a(OP_RETURN) + 28(PUSH_40) + ref_hash(32) + nonce(8)
// Total script = 42 bytes = 0x2a
// The nonce(8) bytes are filled by en1+en2 (between coinb1 and coinb2)
if (!ref_hash_hex.empty()) {
coinb1 << encode_le64(0); // 0 satoshis
coinb1 << "2a"; // script length = 42
coinb1 << "6a28"; // OP_RETURN + PUSH_40
coinb1 << ref_hash_hex; // 32 bytes = 64 hex chars
// nonce (8 bytes) = en1+en2 goes HERE (between coinb1 and coinb2)
}
// coinb2 is just locktime
std::string coinb2 = "00000000";
return { coinb1.str(), coinb2 };
}
MiningInterface::CoinbaseResult
MiningInterface::build_connection_coinbase(
const uint256& prev_share_hash,
const std::string& extranonce1_hex,
const std::vector<unsigned char>& payout_script,
const std::vector<std::pair<uint32_t, std::vector<unsigned char>>>& merged_addrs) const
{
// ── Lock hierarchy: m_work_mutex (1) > sessions_mutex_ (2) > MM::m_mutex (3) ──
//
// This function is called from StratumSession::send_notify_work which may be
// invoked by notify_all() after it releases sessions_mutex_.
// Internally, ref_hash_fn needs get_local_addr_rates() (sessions_mutex_) and
// MM needs its own m_mutex.
//
// Architecture: snapshot-then-compute (matches p2pool's single-threaded model).
// Phase 1: Snapshot all work state under m_work_mutex (brief hold)
// Phase 2: Gather external data WITHOUT any lock (addr_rates, MM commitment)
// Phase 3: Compute everything from snapshot (ref_hash, coinbase parts) — lock-free
// Phase 4: Brief re-lock to write back PPLNS cache + build final result
// ── Phase 1: Snapshot work state under m_work_mutex ──
// All reads from m_cached_* fields happen here. The lock is released before
// any callback that might acquire other mutexes.
struct WorkStateSnapshot {
nlohmann::json tmpl;
std::vector<std::pair<std::string, uint64_t>> pplns_outputs;
uint256 pplns_best_share;
bool raw_scripts{false};
std::string witness_commitment;
uint256 witness_root;
std::vector<uint8_t> mm_commitment;
std::vector<CachedMergedHeaderInfo> merged_header_infos;
bool segwit_active{false};
std::string mweb;
std::string coinbase_text;
std::vector<unsigned char> donation_script;
std::vector<std::string> merkle_branches;
pplns_fn_t pplns_fn;
ref_hash_fn_t ref_hash_fn;
bool needs_pplns_recompute{false};
int64_t share_version{36};
};
WorkStateSnapshot ws;
{
std::lock_guard<std::mutex> lock(m_work_mutex);
if (!m_work_valid || m_cached_template.is_null())
return {};
ws.tmpl = m_cached_template;
ws.pplns_outputs = m_cached_pplns_outputs;
ws.pplns_best_share = m_cached_pplns_best_share;
ws.raw_scripts = m_cached_raw_scripts;
ws.witness_commitment = m_cached_witness_commitment;
ws.witness_root = m_cached_witness_root;
ws.mm_commitment = m_cached_mm_commitment;
ws.merged_header_infos = m_last_merged_header_infos;
ws.segwit_active = m_segwit_active;
ws.mweb = m_cached_mweb;
ws.coinbase_text = m_coinbase_text;
ws.donation_script = m_donation_script;
ws.share_version = m_cached_share_version;
ws.merkle_branches = m_cached_merkle_branches;
ws.pplns_fn = m_pplns_fn;
ws.ref_hash_fn = m_ref_hash_fn;
ws.needs_pplns_recompute = !prev_share_hash.IsNull()
&& ws.pplns_fn
&& prev_share_hash != ws.pplns_best_share;
}
// ── m_work_mutex RELEASED ──
// From here on, NO mutex is held. All callbacks (PPLNS, ref_hash, MM, addr_rates)
// can freely acquire their own locks without deadlock risk.
if (!ws.ref_hash_fn)
return {};
// ── Phase 2: PPLNS recomputation (lock-free — callbacks may acquire their own locks) ──
// CRITICAL: If frozen prev_share_hash differs from the share used for cached PPLNS,
// recompute PPLNS from the frozen share. This ensures the coinbase amounts match
// what generate_share_transaction will compute during verification.
// (Matches p2pool's closure pattern: coinbase is frozen at template time.)
static const char* HX = "0123456789abcdef";
if (prev_share_hash.IsNull())
{
// Genesis: no PPLNS walk possible. p2pool puts 100% of subsidy to donation.
ws.pplns_outputs.clear();
uint64_t subsidy = ws.tmpl.value("coinbasevalue", uint64_t(0));
std::string donation_hex;
for (unsigned char b : ws.donation_script) { donation_hex += HX[b >> 4]; donation_hex += HX[b & 0x0f]; }
ws.pplns_outputs.push_back({donation_hex, subsidy});
ws.raw_scripts = true;
ws.pplns_best_share = prev_share_hash;
}
else if (ws.needs_pplns_recompute)
{
uint32_t nbits = 0;
if (ws.tmpl.contains("bits"))
nbits = static_cast<uint32_t>(std::stoul(
ws.tmpl["bits"].get<std::string>(), nullptr, 16));
uint256 block_target = chain::bits_to_target(nbits);
uint64_t subsidy = ws.tmpl.value("coinbasevalue", uint64_t(0));
auto expected = ws.pplns_fn(prev_share_hash, block_target, subsidy, ws.donation_script);
if (!expected.empty()) {
ws.pplns_outputs.clear();
std::string donation_hex;
for (unsigned char b : ws.donation_script) { donation_hex += HX[b >> 4]; donation_hex += HX[b & 0x0f]; }
std::pair<std::string, uint64_t> donation_entry;
bool found_donation = false;
for (const auto& [script_bytes, amount] : expected) {
uint64_t sat = static_cast<uint64_t>(amount);
std::string hex;
for (unsigned char b : script_bytes) { hex += HX[b >> 4]; hex += HX[b & 0x0f]; }
if (hex == donation_hex) { donation_entry = {hex, sat}; found_donation = true; }