generated from bitcoin-sv/template
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsigma_test.go
More file actions
499 lines (457 loc) · 14.8 KB
/
sigma_test.go
File metadata and controls
499 lines (457 loc) · 14.8 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
package bitcom
import (
"encoding/base64"
"os"
"strings"
"testing"
"github.com/bsv-blockchain/go-sdk/script"
"github.com/bsv-blockchain/go-sdk/transaction"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestDecode verifies the Sigma protocol decoding functionality
func TestDecodeSIGMA(t *testing.T) {
// Reset global state before starting the test
resetTestState()
t.Run("nil bitcom", func(t *testing.T) {
// Reset global state before each subtest
resetTestState()
// Test nil Bitcom
var nilBitcom *Bitcom
result := DecodeSIGMA(nilBitcom)
require.NotNil(t, result, "Result should be an empty slice, not nil")
require.Empty(t, result, "Result should be an empty slice for nil Bitcom")
})
t.Run("empty protocols", func(t *testing.T) {
// Reset global state before each subtest
resetTestState()
// Test Bitcom with empty protocols
emptyBitcom := &Bitcom{
Protocols: []*BitcomProtocol{},
}
result := DecodeSIGMA(emptyBitcom)
require.NotNil(t, result, "Result should be an empty slice, not nil")
require.Empty(t, result, "Result should be an empty slice for Bitcom with empty protocols")
})
tests := []struct {
name string
bitcom *Bitcom
expected []*Sigma
}{
{
name: "no sigma protocols",
bitcom: &Bitcom{
Protocols: []*BitcomProtocol{
{
Protocol: "1PuQa7K62MiKCtssSLKy1kh56WWU7MtUR5",
Script: []byte("some data"),
Pos: 0,
},
{
Protocol: "19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut",
Script: []byte("more data"),
Pos: 0,
},
},
},
expected: []*Sigma{},
},
{
name: "valid Sigma protocol with minimum fields",
bitcom: &Bitcom{
Protocols: []*BitcomProtocol{
{
Protocol: SIGMAPrefix,
Script: func() []byte {
s := &script.Script{}
_ = s.AppendPushData([]byte(string(AlgoECDSA)))
_ = s.AppendPushData([]byte("1AddressBTC12345678"))
_ = s.AppendPushData([]byte("signature1234567890"))
return *s
}(),
Pos: 0,
},
},
},
expected: []*Sigma{
{
Algorithm: AlgoECDSA,
SignerAddress: "1AddressBTC12345678",
SignatureValue: base64.StdEncoding.EncodeToString([]byte("signature1234567890")),
Valid: true, // We now trust transaction signatures without message
},
},
},
{
name: "valid Sigma protocol with all fields",
bitcom: &Bitcom{
Protocols: []*BitcomProtocol{
{
Protocol: SIGMAPrefix,
Script: func() []byte {
s := &script.Script{}
_ = s.AppendPushData([]byte(string(AlgoSHA256ECDSA)))
_ = s.AppendPushData([]byte("1AddressBTC12345678"))
_ = s.AppendPushData([]byte("abcdef1234567890"))
_ = s.AppendPushData([]byte("Hello, world!")) // This is now the message field directly
_ = s.AppendPushData([]byte("random-nonce-123"))
return *s
}(),
Pos: 0,
},
},
},
expected: []*Sigma{
{
Algorithm: AlgoSHA256ECDSA,
SignerAddress: "1AddressBTC12345678",
SignatureValue: base64.StdEncoding.EncodeToString([]byte("abcdef1234567890")),
Message: "Hello, world!",
Nonce: "random-nonce-123",
},
},
},
{
name: "multiple Sigma protocols",
bitcom: &Bitcom{
Protocols: []*BitcomProtocol{
{
Protocol: SIGMAPrefix,
Script: func() []byte {
s := &script.Script{}
_ = s.AppendPushData([]byte(string(AlgoECDSA)))
_ = s.AppendPushData([]byte("1Address1"))
_ = s.AppendPushData([]byte("signature1"))
return *s
}(),
Pos: 0,
},
{
Protocol: SIGMAPrefix,
Script: func() []byte {
s := &script.Script{}
_ = s.AppendPushData([]byte(string(AlgoSHA256ECDSA)))
_ = s.AppendPushData([]byte("1Address2"))
_ = s.AppendPushData([]byte("signature2"))
return *s
}(),
Pos: 0,
},
},
},
expected: []*Sigma{
{
Algorithm: AlgoECDSA,
SignerAddress: "1Address1",
SignatureValue: base64.StdEncoding.EncodeToString([]byte("signature1")),
Valid: true, // We now trust transaction signatures without message
},
{
Algorithm: AlgoSHA256ECDSA,
SignerAddress: "1Address2",
SignatureValue: base64.StdEncoding.EncodeToString([]byte("signature2")),
Valid: true, // We now trust transaction signatures without message
},
},
},
{
name: "invalid Sigma protocol (missing fields)",
bitcom: &Bitcom{
Protocols: []*BitcomProtocol{
{
Protocol: SIGMAPrefix,
Script: func() []byte {
s := &script.Script{}
_ = s.AppendPushData([]byte(string(AlgoECDSA)))
// Missing address and signature
return *s
}(),
Pos: 0,
},
},
},
expected: []*Sigma{},
},
{
name: "Sigma with message field",
bitcom: &Bitcom{
Protocols: []*BitcomProtocol{
{
Protocol: SIGMAPrefix,
Script: func() []byte {
s := &script.Script{}
_ = s.AppendPushData([]byte(string(AlgoECDSA)))
_ = s.AppendPushData([]byte("1AddressBTC12345678"))
_ = s.AppendPushData([]byte("binary-signature-data"))
_ = s.AppendPushData([]byte("This is the message"))
return *s
}(),
Pos: 0,
},
},
},
expected: []*Sigma{
{
Algorithm: AlgoECDSA,
SignerAddress: "1AddressBTC12345678",
SignatureValue: base64.StdEncoding.EncodeToString([]byte("binary-signature-data")),
Message: "This is the message",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := DecodeSIGMA(tt.bitcom)
if tt.name == "multiple Sigma protocols" {
t.Logf("Expected %d Sigmas, got %d Sigmas", len(tt.expected), len(result))
t.Logf("Result: %+v", result)
}
require.Len(t, result, len(tt.expected))
if len(tt.expected) > 0 {
for i, expectedSigma := range tt.expected {
if i >= len(result) {
t.Fatalf("Missing expected Sigma at index %d", i)
continue
}
resultSigma := result[i]
require.Equal(t, expectedSigma.Algorithm, resultSigma.Algorithm)
require.Equal(t, expectedSigma.SignerAddress, resultSigma.SignerAddress)
require.Equal(t, expectedSigma.SignatureValue, resultSigma.SignatureValue)
require.Equal(t, expectedSigma.Message, resultSigma.Message)
require.Equal(t, expectedSigma.Nonce, resultSigma.Nonce)
}
}
})
}
}
// TestGetSignatureBytes tests the GetSignatureBytes function
func TestGetSignatureBytes(t *testing.T) {
tests := []struct {
name string
sigma *Sigma
expected []byte
shouldSucceed bool
}{
{
name: "regular signature",
sigma: &Sigma{
SignatureValue: base64.StdEncoding.EncodeToString([]byte("test-signature")),
},
expected: []byte("test-signature"),
shouldSucceed: true,
},
{
name: "empty signature",
sigma: &Sigma{
SignatureValue: "",
},
expected: nil,
shouldSucceed: true,
},
{
name: "invalid base64",
sigma: &Sigma{
SignatureValue: "not-valid-base64!@#",
},
expected: nil,
shouldSucceed: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := tt.sigma.GetSignatureBytes()
if tt.shouldSucceed {
require.NoError(t, err)
require.Equal(t, tt.expected, result)
} else {
require.Error(t, err)
}
})
}
}
// TestDecodeWithSigmaTestVector verifies that the Sigma protocol can properly decode
// the test vector from 34adf92c766e11a656d3ff3508df7b1a31405821bf734bc9bef9fb43fcf701f9.hex
func TestDecodeWithSigmaTestVector(t *testing.T) {
// Load the hex data from the file
hexData, err := os.ReadFile("testdata/34adf92c766e11a656d3ff3508df7b1a31405821bf734bc9bef9fb43fcf701f9.hex")
require.NoError(t, err, "Failed to read hex data from file")
// Create a transaction from the bytes
tx, err := transaction.NewTransactionFromHex(strings.TrimSpace(string(hexData)))
require.NoError(t, err, "Failed to create transaction from bytes")
// Verify transaction ID matches expected
expectedTxID := "34adf92c766e11a656d3ff3508df7b1a31405821bf734bc9bef9fb43fcf701f9"
require.Equal(t, expectedTxID, tx.TxID().String(), "Transaction ID should match expected value")
// Extract the OP_RETURN output from the transaction
// The Sigma protocol data should be in an OP_RETURN output
t.Logf("Transaction has %d outputs", len(tx.Outputs))
// Inspect all outputs to find where the OP_RETURN data is located
var bitcomData *Bitcom
for i, output := range tx.Outputs {
// Use bitcom to decode each output's script
decodedBitcom := Decode(output.LockingScript)
if decodedBitcom != nil && len(decodedBitcom.Protocols) > 0 {
t.Logf("Output %d has %d BitCom protocols", i, len(decodedBitcom.Protocols))
// Debug: print all protocols in this output
for j, proto := range decodedBitcom.Protocols {
t.Logf(" Protocol %d: %s, Script length: %d", j, proto.Protocol, len(proto.Script))
t.Logf(" Script hex: %x", proto.Script)
}
// Check if any protocol is Sigma
for _, proto := range decodedBitcom.Protocols {
if proto.Protocol == SIGMAPrefix {
bitcomData = decodedBitcom
t.Logf("Found Sigma protocol in output %d", i)
break
}
}
if bitcomData != nil {
break
}
}
}
require.NotNil(t, bitcomData, "No BitCom data with Sigma protocol found in transaction")
// Decode the Sigma data
sigmaData := DecodeSIGMA(bitcomData)
// Debug: print BitCom protocols to understand the issue
t.Logf("BitCom has %d protocols", len(bitcomData.Protocols))
for i, proto := range bitcomData.Protocols {
t.Logf("Protocol %d: %s, Script length: %d", i, proto.Protocol, len(proto.Script))
if proto.Protocol == SIGMAPrefix {
t.Logf("SIGMA protocol found at index %d, Script: %x", i, proto.Script)
}
}
// Debug the actual protocol value vs our constant
t.Logf("SIGMAPrefix constant value: %q", SIGMAPrefix)
t.Logf("Actual protocol value: %q", bitcomData.Protocols[1].Protocol)
require.NotEmpty(t, sigmaData, "Decoded Sigma data should not be empty")
// Expected values according to the information provided
expectedVIN := 0
expectedAddress := "12KP5KzkBwtsc1UrTrsBCJzgqKn8UqaYQq"
expectedAlgorithm := "BSM"
expectedSignature := "H6hhGMaMJ0wkQUjcm2155LyBLc/f6+pRHLcUpUoqssj+dEcqr5yH2scBKSY0Z9RgHd066xRbLCBMPDu29Bu8vPc="
// Log decoded data for inspection
for i, sigma := range sigmaData {
t.Logf("Sigma[%d]: %+v", i, sigma)
}
// Verify that there is at least one signature that matches the expected values
var found bool
for _, sigma := range sigmaData {
if sigma.SignerAddress == expectedAddress &&
sigma.Algorithm == SignatureAlgorithm(expectedAlgorithm) &&
sigma.SignatureValue == expectedSignature &&
sigma.VIN == expectedVIN {
found = true
t.Logf("Successfully verified Sigma signature: Address=%s, Algorithm=%s, Signature=%s, VIN=%d",
sigma.SignerAddress, sigma.Algorithm, sigma.SignatureValue, sigma.VIN)
break
}
}
require.True(t, found, "Did not find a Sigma signature matching the expected values")
}
func TestVerify(t *testing.T) {
tests := []struct {
name string
sigmaSignature *Sigma
expectValid bool
}{
{
name: "Valid BSM signature",
sigmaSignature: &Sigma{
Algorithm: AlgoBSM,
SignerAddress: "1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz",
// This is a valid signature for the message "Hello, World!" from address 1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz
SignatureValue: "H89DSY12iMmrF16T4aDPwFcqrtuGxyoT69yTBH4GqXyzNZ+POVhxV5FLAvHdwKmJ0IhQT/w7JQpTg0XBZ5zeJ+c=",
Message: "Hello, World!",
},
expectValid: true,
},
{
name: "Invalid BSM signature (wrong signature)",
sigmaSignature: &Sigma{
Algorithm: AlgoBSM,
SignerAddress: "1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz",
// This is an invalid signature
SignatureValue: "H00000012iMmrF16T4aDPwFcqrtuGxyoT69yTBH4GqXyzNZ+POVhxV5FLAvHdwKmJ0IhQT/w7JQpTg0XBZ5zeJ+c=",
Message: "Hello, World!",
},
expectValid: false,
},
{
name: "Invalid BSM signature (wrong address)",
sigmaSignature: &Sigma{
Algorithm: AlgoBSM,
SignerAddress: "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", // Wrong address
// This is a valid signature for the message "Hello, World!" from address 1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz
SignatureValue: "H89DSY12iMmrF16T4aDPwFcqrtuGxyoT69yTBH4GqXyzNZ+POVhxV5FLAvHdwKmJ0IhQT/w7JQpTg0XBZ5zeJ+c=",
Message: "Hello, World!",
},
expectValid: false,
},
{
name: "Invalid BSM signature (wrong message)",
sigmaSignature: &Sigma{
Algorithm: AlgoBSM,
SignerAddress: "1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz",
// This is a valid signature for the message "Hello, World!" from address 1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz
SignatureValue: "H89DSY12iMmrF16T4aDPwFcqrtuGxyoT69yTBH4GqXyzNZ+POVhxV5FLAvHdwKmJ0IhQT/w7JQpTg0XBZ5zeJ+c=",
Message: "Modified message",
},
expectValid: false,
},
{
name: "Missing required data",
sigmaSignature: &Sigma{
Algorithm: AlgoBSM,
SignerAddress: "", // Missing address
SignatureValue: "", // Missing signature
Message: "", // Missing message
},
expectValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.sigmaSignature.Verify()
if tt.expectValid {
require.NoError(t, err, "Verification should succeed")
assert.True(t, tt.sigmaSignature.Valid, "Signature should be marked as valid")
} else {
if tt.sigmaSignature.SignerAddress == "" || tt.sigmaSignature.SignatureValue == "" || tt.sigmaSignature.Message == "" {
require.Error(t, err, "Verification should fail due to missing data")
} else {
require.Error(t, err, "Verification should fail")
assert.False(t, tt.sigmaSignature.Valid, "Signature should be marked as invalid")
}
}
})
}
}
func TestDecodeSigmaWithVerification(t *testing.T) {
// Create a simple Sigma bitcom protocol with a valid signature
s := &script.Script{}
_ = s.AppendPushData([]byte("BSM"))
_ = s.AppendPushData([]byte("1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz"))
// Decode the valid signature from base64
sigBytes, err := base64.StdEncoding.DecodeString("H89DSY12iMmrF16T4aDPwFcqrtuGxyoT69yTBH4GqXyzNZ+POVhxV5FLAvHdwKmJ0IhQT/w7JQpTg0XBZ5zeJ+c=")
require.NoError(t, err)
_ = s.AppendPushData(sigBytes)
_ = s.AppendPushData([]byte("Hello, World!")) // Message
// Create a BitCom protocol
bc := &Bitcom{
Protocols: []*BitcomProtocol{
{
Protocol: SIGMAPrefix,
Script: *s,
},
},
}
// Decode and verify
sigmas := DecodeSIGMA(bc)
require.Len(t, sigmas, 1, "Should decode one Sigma signature")
// Check that it was validated correctly
assert.True(t, sigmas[0].Valid, "Signature should be marked as valid")
assert.Equal(t, "BSM", string(sigmas[0].Algorithm))
assert.Equal(t, "1EXhSbGFiEAZCE5eeBvUxT6cBVHhrpPWXz", sigmas[0].SignerAddress)
assert.Equal(t, "Hello, World!", sigmas[0].Message)
}