-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfound_block_test.go
More file actions
502 lines (437 loc) · 14.3 KB
/
found_block_test.go
File metadata and controls
502 lines (437 loc) · 14.3 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
package main
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/btcsuite/btcd/wire"
)
// TestFoundBlockSubmission_BtcdCompat verifies that a valid block found by a
// miner can be built and submitted successfully, and that the serialized block
// parses correctly with btcd's wire.MsgBlock.
func TestFoundBlockSubmission_BtcdCompat(t *testing.T) {
// Track submitblock calls
var submitCalls int
var submittedBlockHex string
// Mock RPC server that accepts submitblock
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read body: %v", err)
return
}
var req rpcRequest
if err := json.Unmarshal(body, &req); err != nil {
t.Fatalf("unmarshal request: %v", err)
return
}
if req.Method == "submitblock" {
submitCalls++
if params, ok := req.Params.([]any); ok && len(params) > 0 {
if blockHex, ok := params[0].(string); ok {
submittedBlockHex = blockHex
}
}
// Return success
w.Header().Set("Content-Type", "application/json")
resp := rpcResponse{Result: nil, Error: nil, ID: req.ID}
_ = json.NewEncoder(w).Encode(resp)
} else {
t.Errorf("unexpected RPC method: %s", req.Method)
}
}))
defer server.Close()
rpc := &RPCClient{
url: server.URL,
user: "test",
pass: "test",
metrics: nil,
client: server.Client(),
lp: server.Client(),
nextID: 1,
}
// Create a test job
job := &Job{
JobID: "btcd-test-job",
Template: GetBlockTemplateResult{
Height: 100,
CurTime: 1700000000,
Mintime: 0,
Bits: "1d00ffff", // Very easy difficulty for testing
Previous: "0000000000000000000000000000000000000000000000000000000000000000",
CoinbaseValue: 50 * 1e8,
},
Extranonce2Size: 4,
TemplateExtraNonce2Size: 8,
PayoutScript: []byte{0x76, 0xa9, 0x14}, // Mock P2PKH prefix
WitnessCommitment: "",
CoinbaseMsg: "goPool-test",
ScriptTime: 0,
Transactions: nil,
MerkleBranches: nil,
CoinbaseValue: 50 * 1e8,
}
// Build a block
extranonce1 := []byte{0x01, 0x02, 0x03, 0x04}
extranonce2 := []byte{0xaa, 0xbb, 0xcc, 0xdd}
ntimeHex := fmt.Sprintf("%08x", job.Template.CurTime)
nonceHex := "12345678"
version := int32(0x20000000)
blockHex, headerHash, header, merkleRoot, err := buildBlock(job, extranonce1, extranonce2, ntimeHex, nonceHex, version)
if err != nil {
t.Fatalf("buildBlock error: %v", err)
}
if len(blockHex) == 0 || len(headerHash) != 32 || len(header) != 80 || len(merkleRoot) != 32 {
t.Fatalf("unexpected block artifacts")
}
// Submit the block
var submitRes any
err = rpc.callCtx(context.Background(), "submitblock", []any{blockHex}, &submitRes)
if err != nil {
t.Fatalf("submitblock error: %v", err)
}
// Verify submitblock was called
if submitCalls != 1 {
t.Fatalf("expected 1 submitblock call, got %d", submitCalls)
}
// Verify the submitted block parses with btcd
raw, err := hex.DecodeString(submittedBlockHex)
if err != nil {
t.Fatalf("decode submitted block: %v", err)
}
var msgBlock wire.MsgBlock
if err := msgBlock.Deserialize(bytes.NewReader(raw)); err != nil {
t.Fatalf("btcd MsgBlock deserialize error: %v", err)
}
// Verify block structure
if msgBlock.Header.Version != version {
t.Errorf("header version mismatch: got %d, want %d", msgBlock.Header.Version, version)
}
if len(msgBlock.Transactions) != 1 {
t.Errorf("expected 1 transaction (coinbase only), got %d", len(msgBlock.Transactions))
}
// Verify merkle root matches
if !bytes.Equal(msgBlock.Header.MerkleRoot.CloneBytes(), merkleRoot) {
t.Errorf("merkle root mismatch: header=%x computed=%x",
msgBlock.Header.MerkleRoot.CloneBytes(), merkleRoot)
}
t.Logf("Successfully submitted block at height %d with hash %x", job.Template.Height, headerHash)
}
// TestFoundBlockSubmission_DualPayout tests block submission with dual-payout
// (pool fee + worker payout) and verifies the coinbase outputs are correct.
func TestFoundBlockSubmission_DualPayout(t *testing.T) {
cfg := Config{
PoolFeePercent: 2.0,
}
var submittedBlockHex string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var req rpcRequest
_ = json.Unmarshal(body, &req)
if req.Method == "submitblock" {
if params, ok := req.Params.([]any); ok && len(params) > 0 {
if blockHex, ok := params[0].(string); ok {
submittedBlockHex = blockHex
}
}
w.Header().Set("Content-Type", "application/json")
resp := rpcResponse{Result: nil, Error: nil, ID: req.ID}
_ = json.NewEncoder(w).Encode(resp)
}
}))
defer server.Close()
rpc := &RPCClient{
url: server.URL,
client: server.Client(),
lp: server.Client(),
nextID: 1,
}
poolScript := []byte{0x51} // OP_TRUE for pool
workerScript := []byte{0x52} // OP_2 for worker
totalValue := int64(50 * 1e8)
feePercent := cfg.PoolFeePercent
job := &Job{
Template: GetBlockTemplateResult{
Height: 200,
CurTime: 1700000100,
Bits: "1d00ffff",
Previous: "0000000000000000000000000000000000000000000000000000000000000000",
CoinbaseValue: totalValue,
},
TemplateExtraNonce2Size: 8,
}
extranonce1 := []byte{0x01, 0x02, 0x03, 0x04}
extranonce2 := []byte{0xaa, 0xbb, 0xcc, 0xdd}
ntimeHex := fmt.Sprintf("%08x", job.Template.CurTime)
nonceHex := "87654321"
version := int32(0x20000000)
// Build dual-payout coinbase
cbTx, cbTxid, err := serializeDualCoinbaseTx(
job.Template.Height,
extranonce1,
extranonce2,
job.TemplateExtraNonce2Size,
poolScript,
workerScript,
totalValue,
feePercent,
job.WitnessCommitment,
job.Template.CoinbaseAux.Flags,
job.CoinbaseMsg,
job.ScriptTime,
)
if err != nil {
t.Fatalf("serializeDualCoinbaseTx error: %v", err)
}
merkleRoot := computeMerkleRootFromBranches(cbTxid, job.MerkleBranches)
header, err := buildBlockHeaderFromHex(version, job.Template.Previous, merkleRoot, ntimeHex, job.Template.Bits, nonceHex)
if err != nil {
t.Fatalf("buildBlockHeader error: %v", err)
}
// Assemble full block
var blockBuf bytes.Buffer
blockBuf.Write(header)
writeVarInt(&blockBuf, 1) // tx count
blockBuf.Write(cbTx)
blockHex := hex.EncodeToString(blockBuf.Bytes())
// Submit
var submitRes any
err = rpc.callCtx(context.Background(), "submitblock", []any{blockHex}, &submitRes)
if err != nil {
t.Fatalf("submitblock error: %v", err)
}
// Parse and verify dual outputs
raw, err := hex.DecodeString(submittedBlockHex)
if err != nil {
t.Fatalf("decode submitted block: %v", err)
}
var msgBlock wire.MsgBlock
if err := msgBlock.Deserialize(bytes.NewReader(raw)); err != nil {
t.Fatalf("btcd MsgBlock deserialize error: %v", err)
}
if len(msgBlock.Transactions) != 1 {
t.Fatalf("expected 1 transaction, got %d", len(msgBlock.Transactions))
}
coinbase := msgBlock.Transactions[0]
if len(coinbase.TxOut) != 2 {
t.Fatalf("expected 2 outputs in dual-payout coinbase, got %d", len(coinbase.TxOut))
}
// Verify split
poolFee := int64(math.Round(float64(totalValue) * feePercent / 100.0))
workerValue := totalValue - poolFee
var (
gotPoolValue *int64
gotWorkerValue *int64
gotPoolScript []byte
gotWorkerScript []byte
)
for _, o := range coinbase.TxOut {
switch {
case bytes.Equal(o.PkScript, poolScript):
v := o.Value
gotPoolValue = &v
gotPoolScript = o.PkScript
case bytes.Equal(o.PkScript, workerScript):
v := o.Value
gotWorkerValue = &v
gotWorkerScript = o.PkScript
}
}
if gotPoolValue == nil {
t.Fatalf("pool output not found by script")
}
if gotWorkerValue == nil {
t.Fatalf("worker output not found by script")
}
if *gotPoolValue != poolFee {
t.Errorf("pool output value mismatch: got %d, want %d", *gotPoolValue, poolFee)
}
if *gotWorkerValue != workerValue {
t.Errorf("worker output value mismatch: got %d, want %d", *gotWorkerValue, workerValue)
}
if !bytes.Equal(gotPoolScript, poolScript) {
t.Errorf("pool script mismatch")
}
if !bytes.Equal(gotWorkerScript, workerScript) {
t.Errorf("worker script mismatch")
}
t.Logf("Successfully submitted dual-payout block: pool=%d sats (%.2f%%), worker=%d sats",
poolFee, feePercent, workerValue)
}
// TestFoundBlockSubmission_PogoloCompat verifies compatibility with pogolo by
// testing that the block structure, merkle branches, and coinbase construction
// match what pogolo would produce.
func TestFoundBlockSubmission_PogoloCompat(t *testing.T) {
// Create a job similar to what pogolo would create
txid1, _ := hex.DecodeString("1111111111111111111111111111111111111111111111111111111111111111")
txid2, _ := hex.DecodeString("2222222222222222222222222222222222222222222222222222222222222222")
txids := [][]byte{txid1, txid2}
merkleBranches := buildMerkleBranches(txids)
job := &Job{
JobID: "pogolo-compat-test",
Template: GetBlockTemplateResult{
Height: 300,
CurTime: 1700000200,
Bits: "1d00ffff",
Previous: "0000000000000000000000000000000000000000000000000000000000000000",
CoinbaseValue: 50 * 1e8,
},
Extranonce2Size: 4,
TemplateExtraNonce2Size: 8,
PayoutScript: []byte{0x76, 0xa9, 0x14}, // P2PKH prefix
WitnessCommitment: "",
CoinbaseMsg: "goPool",
ScriptTime: 0,
Transactions: nil, // Would contain actual txs
MerkleBranches: merkleBranches,
CoinbaseValue: 50 * 1e8,
}
extranonce1 := []byte{0x01, 0x02, 0x03, 0x04}
extranonce2 := []byte{0xaa, 0xbb, 0xcc, 0xdd}
ntimeHex := fmt.Sprintf("%08x", job.Template.CurTime)
nonceHex := "abcdef01"
version := int32(0x20000000)
blockHex, _, header, merkleRoot, err := buildBlock(job, extranonce1, extranonce2, ntimeHex, nonceHex, version)
if err != nil {
t.Fatalf("buildBlock error: %v", err)
}
// Parse with btcd to verify structure
raw, err := hex.DecodeString(blockHex)
if err != nil {
t.Fatalf("decode blockHex: %v", err)
}
var msgBlock wire.MsgBlock
if err := msgBlock.Deserialize(bytes.NewReader(raw)); err != nil {
t.Fatalf("btcd deserialize error: %v", err)
}
// Verify header is exactly 80 bytes
if len(header) != 80 {
t.Errorf("header length must be 80 bytes, got %d", len(header))
}
// Verify merkle root is 32 bytes
if len(merkleRoot) != 32 {
t.Errorf("merkle root must be 32 bytes, got %d", len(merkleRoot))
}
// Verify coinbase has correct structure
coinbase := msgBlock.Transactions[0]
// Coinbase must have at least one input
if len(coinbase.TxIn) != 1 {
t.Errorf("coinbase must have exactly 1 input, got %d", len(coinbase.TxIn))
}
// Coinbase input must reference null hash
nullHash := make([]byte, 32)
if !bytes.Equal(coinbase.TxIn[0].PreviousOutPoint.Hash[:], nullHash) {
t.Errorf("coinbase input must reference null hash")
}
// Verify height is encoded in coinbase scriptSig (BIP 34)
scriptSig := coinbase.TxIn[0].SignatureScript
if len(scriptSig) < 1 {
t.Errorf("coinbase scriptSig must contain height")
}
// First byte(s) should encode the height
heightScript := serializeNumberScript(job.Template.Height)
if !bytes.HasPrefix(scriptSig, heightScript) {
t.Logf("Warning: height encoding may not match expected format")
t.Logf("Expected prefix: %x", heightScript)
t.Logf("Got scriptSig: %x", scriptSig)
}
t.Logf("Block structure compatible with pogolo/btcd at height %d", job.Template.Height)
}
// TestFoundBlockSubmission_WithPendingLog verifies that failed submissions
// are logged to SQLite for later replay.
func TestFoundBlockSubmission_WithPendingLog(t *testing.T) {
tmpDir := t.TempDir()
// Set up the shared DB for this test
dbPath := filepath.Join(tmpDir, "state", "workers.db")
db, err := openStateDB(dbPath)
if err != nil {
t.Fatalf("openStateDB: %v", err)
}
t.Cleanup(func() { db.Close() })
cleanup := setSharedStateDBForTest(db)
t.Cleanup(cleanup)
// Mock RPC server that fails submitblock
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var req rpcRequest
_ = json.Unmarshal(body, &req)
if req.Method == "submitblock" {
// Return an error
w.Header().Set("Content-Type", "application/json")
resp := rpcResponse{
Result: nil,
Error: &rpcError{Code: -1, Message: "rejected by network"},
ID: req.ID,
}
_ = json.NewEncoder(w).Encode(resp)
}
}))
defer server.Close()
rpc := &RPCClient{
url: server.URL,
client: server.Client(),
lp: server.Client(),
nextID: 1,
}
job := &Job{
JobID: "pending-test-job",
Template: GetBlockTemplateResult{
Height: 400,
CurTime: 1700000300,
Bits: "1d00ffff",
Previous: "0000000000000000000000000000000000000000000000000000000000000000",
CoinbaseValue: 50 * 1e8,
},
Extranonce2Size: 4,
TemplateExtraNonce2Size: 8,
PayoutScript: []byte{0x51},
CoinbaseValue: 50 * 1e8,
}
extranonce1 := []byte{0x01, 0x02, 0x03, 0x04}
extranonce2 := []byte{0xaa, 0xbb, 0xcc, 0xdd}
ntimeHex := fmt.Sprintf("%08x", job.Template.CurTime)
nonceHex := "deadbeef"
version := int32(0x20000000)
blockHex, headerHash, _, _, err := buildBlock(job, extranonce1, extranonce2, ntimeHex, nonceHex, version)
if err != nil {
t.Fatalf("buildBlock error: %v", err)
}
// Try to submit (will fail)
var submitRes any
err = rpc.callCtx(context.Background(), "submitblock", []any{blockHex}, &submitRes)
if err == nil {
t.Fatal("expected submitblock to fail, but it succeeded")
}
// Log the pending submission
workerName := "test-worker"
hashHex := hex.EncodeToString(headerHash)
rec := pendingSubmissionRecord{
Timestamp: time.Now().UTC(),
Height: job.Template.Height,
Hash: hashHex,
Worker: workerName,
BlockHex: blockHex,
RPCError: err.Error(),
RPCURL: server.URL,
PayoutAddr: workerName,
Status: "pending",
}
appendPendingSubmissionRecord(rec)
// Use the shared DB that was set up earlier
var status string
if err := db.QueryRow("SELECT status FROM pending_submissions WHERE submission_key = ?", hashHex).Scan(&status); err != nil {
t.Fatalf("query pending submission: %v", err)
}
if status != "pending" {
t.Errorf("expected status 'pending', got '%s'", status)
}
t.Logf("Failed block submission logged to pending log for height %d", job.Template.Height)
}