-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbip85_test.go
More file actions
1019 lines (871 loc) · 30.5 KB
/
Copy pathbip85_test.go
File metadata and controls
1019 lines (871 loc) · 30.5 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
package bip85
import (
"bytes"
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"errors"
"strings"
"testing"
btcec "github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
)
// specMasterXprv is the master key used for ALL BIP85 spec test vectors.
const specMasterXprv = "xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb"
// --- Spec vector tests (GATE) ---
func TestSpecVector1_CoreHMAC(t *testing.T) {
key, err := ParseKey(specMasterXprv)
if err != nil {
t.Fatalf("ParseKey: %v", err)
}
defer key.Zero()
path, err := ParsePath("m/83696968'/0'/0'")
if err != nil {
t.Fatalf("ParsePath: %v", err)
}
dk, entropy, err := DeriveKeyAndEntropy(key, path)
if err != nil {
t.Fatalf("DeriveKeyAndEntropy: %v", err)
}
wantKey := "cca20ccb0e9a90feb0912870c3323b24874b0ca3d8018c4b96d0b97c0e82ded0"
wantEntropy := "efecfbccffea313214232d29e71563d941229afb4338c21f9517c41aaa0d16f00b83d2a09ef747e7a64e8e2bd5a14869e693da66ce94ac2da570ab7ee48618f7"
if got := hex.EncodeToString(dk); got != wantKey {
t.Errorf("derived key:\n got: %s\n want: %s", got, wantKey)
}
if got := hex.EncodeToString(entropy); got != wantEntropy {
t.Errorf("entropy:\n got: %s\n want: %s", got, wantEntropy)
}
}
func TestSpecVector2_CoreHMAC(t *testing.T) {
key, err := ParseKey(specMasterXprv)
if err != nil {
t.Fatalf("ParseKey: %v", err)
}
defer key.Zero()
path, err := ParsePath("m/83696968'/0'/1'")
if err != nil {
t.Fatalf("ParsePath: %v", err)
}
dk, entropy, err := DeriveKeyAndEntropy(key, path)
if err != nil {
t.Fatalf("DeriveKeyAndEntropy: %v", err)
}
wantKey := "503776919131758bb7de7beb6c0ae24894f4ec042c26032890c29359216e21ba"
wantEntropy := "70c6e3e8ebee8dc4c0dbba66076819bb8c09672527c4277ca8729532ad711872218f826919f6b67218adde99018a6df9095ab2b58d803b5b93ec9802085a690e"
if got := hex.EncodeToString(dk); got != wantKey {
t.Errorf("derived key:\n got: %s\n want: %s", got, wantKey)
}
if got := hex.EncodeToString(entropy); got != wantEntropy {
t.Errorf("entropy:\n got: %s\n want: %s", got, wantEntropy)
}
}
// --- API consistency tests ---
func TestDeriveEntropy_MatchesDeriveKeyAndEntropy(t *testing.T) {
key, err := ParseKey(specMasterXprv)
if err != nil {
t.Fatalf("ParseKey: %v", err)
}
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
entropy, err := DeriveEntropy(key, path)
if err != nil {
t.Fatalf("DeriveEntropy: %v", err)
}
_, entropy2, err := DeriveKeyAndEntropy(key, path)
if err != nil {
t.Fatalf("DeriveKeyAndEntropy: %v", err)
}
if !bytes.Equal(entropy, entropy2) {
t.Error("DeriveEntropy and DeriveKeyAndEntropy returned different entropy")
}
if len(entropy) != 64 {
t.Errorf("entropy length: got %d, want 64", len(entropy))
}
}
func TestDeriveEntropyFromString(t *testing.T) {
path, _ := ParsePath("m/83696968'/0'/0'")
entropy, err := DeriveEntropyFromString(specMasterXprv, path)
if err != nil {
t.Fatalf("DeriveEntropyFromString: %v", err)
}
wantEntropy := "efecfbccffea313214232d29e71563d941229afb4338c21f9517c41aaa0d16f00b83d2a09ef747e7a64e8e2bd5a14869e693da66ce94ac2da570ab7ee48618f7"
if got := hex.EncodeToString(entropy); got != wantEntropy {
t.Errorf("entropy:\n got: %s\n want: %s", got, wantEntropy)
}
}
// --- Leading zero regression (vector #14) ---
func TestLeadingZeroDerivedKey(t *testing.T) {
masterXprv := "xprv9s21ZrQH143K33feVLZmQbPSTS3sF2gaBBVRk3oCtKjpmVVtuUhXy7Yt8UfQVUyqhmmJoEouLRMReJZw3n4rtQ4FJNsyE7NTghC5QFroQQ9"
key, err := ParseKey(masterXprv)
if err != nil {
t.Fatalf("ParseKey: %v", err)
}
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
dk, entropy, err := DeriveKeyAndEntropy(key, path)
if err != nil {
t.Fatalf("DeriveKeyAndEntropy: %v", err)
}
// Key starts with 0x00 - tests leading zero preservation.
wantKey := "004085fd27c49b5b7617721f4855b6c2a1e65733499df5cc7b53916eb4782d31"
wantEntropy := "22bfc5db7e3cf685f2f1c9d475570254198b0193f7f6603a6170aabb9480e1782b56ef536747a0f7ccefbe82d13ef46591c7370f5043ff6a1fd5a85d9f129726"
if got := hex.EncodeToString(dk); got != wantKey {
t.Errorf("derived key (leading zero):\n got: %s\n want: %s", got, wantKey)
}
if got := hex.EncodeToString(entropy); got != wantEntropy {
t.Errorf("entropy (leading zero):\n got: %s\n want: %s", got, wantEntropy)
}
}
// --- 12-word master key regression (vector #15) ---
func TestDifferentMasterKey_12Word(t *testing.T) {
// 12-word mnemonic-derived master key from regression.json vector 15.
masterXprv := "xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu"
key, err := ParseKey(masterXprv)
if err != nil {
t.Fatalf("ParseKey: %v", err)
}
defer key.Zero()
// BIP39 15-word path through the core engine.
path, _ := ParsePath("m/83696968'/39'/0'/15'/0'")
_, entropy, err := DeriveKeyAndEntropy(key, path)
if err != nil {
t.Fatalf("DeriveKeyAndEntropy: %v", err)
}
wantEntropy := "5dc4f27a1bbcabfbed28723f2ac282194ec617dd549ac10bc0365ee77457ffb6912561ff590a85e8917326c0f6470eee3c9958b40b205d097fd341b23685201d"
if got := hex.EncodeToString(entropy); got != wantEntropy {
t.Errorf("entropy (12word master):\n got: %s\n want: %s", got, wantEntropy)
}
}
// --- Path parsing tests ---
func TestParsePath_Valid(t *testing.T) {
tests := []struct {
input string
wantLen int
wantStr string
}{
{"m/83696968'/0'/0'", 3, "m/83696968'/0'/0'"},
{"m/83696968h/0h/0h", 3, "m/83696968'/0'/0'"},
{"m/83696968H/0H/0H", 3, "m/83696968'/0'/0'"},
{"m/83696968p/0p/0p", 3, "m/83696968'/0'/0'"},
{"m/83696968'/39'/0'/12'/0'", 5, "m/83696968'/39'/0'/12'/0'"},
{" m/83696968'/0'/0' ", 3, "m/83696968'/0'/0'"},
{"m/83696968'/128169'/64'/0'", 4, "m/83696968'/128169'/64'/0'"},
{"m/83696968'/128169'/32'/2147483647'", 4, "m/83696968'/128169'/32'/2147483647'"},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
p, err := ParsePath(tt.input)
if err != nil {
t.Fatalf("ParsePath(%q): %v", tt.input, err)
}
if p.Len() != tt.wantLen {
t.Errorf("Len: got %d, want %d", p.Len(), tt.wantLen)
}
if p.String() != tt.wantStr {
t.Errorf("String: got %q, want %q", p.String(), tt.wantStr)
}
})
}
}
func TestParsePath_Invalid(t *testing.T) {
tests := []struct {
input string
wantErr error
}{
{"", ErrInvalidPath},
{"m/", ErrInvalidPath},
{"83696968'/0'/0'", ErrInvalidPath},
{"m/83696968'/0'/0", ErrNonHardenedComponent},
{"m/83696968/0'/0'", ErrNonHardenedComponent},
{"m/44'/0'/0'", ErrInvalidPath},
{"m/83696968'", ErrIncompletePath},
{"m/83696968'/0'/abc'", ErrInvalidPath},
{"m/83696968'/0'//0'", ErrInvalidPath},
{"m/83696968'/2147483648'", ErrInvalidPath},
{"m/83696968'/-1'", ErrInvalidPath},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
_, err := ParsePath(tt.input)
if err == nil {
t.Fatalf("ParsePath(%q): expected error, got nil", tt.input)
}
if !errors.Is(err, tt.wantErr) {
t.Errorf("ParsePath(%q): got %v, want %v", tt.input, err, tt.wantErr)
}
})
}
}
// --- Path builder tests ---
func TestPathBuilders(t *testing.T) {
tests := []struct {
name string
path Path
wantStr string
wantLen int
}{
{"CorePath", CorePath(0, 0), "m/83696968'/0'/0'", 3},
{"BIP39Path", BIP39Path(0, 12, 0), "m/83696968'/39'/0'/12'/0'", 5},
{"WIFPath", WIFPath(0), "m/83696968'/2'/0'", 3},
{"XPRVPath", XPRVPath(0), "m/83696968'/32'/0'", 3},
{"HexPath", HexPath(32, 0), "m/83696968'/128169'/32'/0'", 4},
{"Base64Path", Base64Path(21, 0), "m/83696968'/707764'/21'/0'", 4},
{"Base85Path", Base85Path(12, 0), "m/83696968'/707785'/12'/0'", 4},
{"RSAPath", RSAPath(2048, 0), "m/83696968'/828365'/2048'/0'", 4},
{"DicePath", DicePath(6, 10, 0), "m/83696968'/89101'/6'/10'/0'", 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.path.String() != tt.wantStr {
t.Errorf("String: got %q, want %q", tt.path.String(), tt.wantStr)
}
if tt.path.Len() != tt.wantLen {
t.Errorf("Len: got %d, want %d", tt.path.Len(), tt.wantLen)
}
})
}
}
func TestPathBuilders_E2E(t *testing.T) {
// Verify that path builders produce entropy matching ParsePath paths.
key, err := ParseKey(specMasterXprv)
if err != nil {
t.Fatalf("ParseKey: %v", err)
}
defer key.Zero()
built := CorePath(0, 0)
parsed, _ := ParsePath("m/83696968'/0'/0'")
e1, err := DeriveEntropy(key, built)
if err != nil {
t.Fatalf("DeriveEntropy(built): %v", err)
}
e2, err := DeriveEntropy(key, parsed)
if err != nil {
t.Fatalf("DeriveEntropy(parsed): %v", err)
}
if !bytes.Equal(e1, e2) {
t.Error("built path and parsed path produce different entropy")
}
}
// --- Error path tests ---
func TestDeriveEntropy_NilKey(t *testing.T) {
path, _ := ParsePath("m/83696968'/0'/0'")
_, err := DeriveEntropy(nil, path)
if !errors.Is(err, ErrNilKey) {
t.Errorf("got: %v, want: %v", err, ErrNilKey)
}
}
func TestDeriveEntropy_PublicKey(t *testing.T) {
xpub := "xpub661MyMwAqRbcEpFyaVwRcfeeAtFKbH3UnesyJDSbkBQw15pyoHMA6bTEcsSY1NQ8Yxfme29GEXRdj9fWwnPrAG7wX9VbT3GUh9d4GMhawAT"
_, err := ParseKey(xpub)
if !errors.Is(err, ErrPublicKeyNotAllowed) {
t.Errorf("got: %v, want: %v", err, ErrPublicKeyNotAllowed)
}
}
func TestDeriveEntropy_EmptyKey(t *testing.T) {
_, err := ParseKey("")
if !errors.Is(err, ErrInvalidKey) {
t.Errorf("got: %v, want: %v", err, ErrInvalidKey)
}
}
func TestDeriveEntropy_InvalidXprv(t *testing.T) {
_, err := ParseKey("xprv_clearly_invalid_string")
if !errors.Is(err, ErrInvalidKey) {
t.Errorf("got: %v, want: %v", err, ErrInvalidKey)
}
}
func TestDeriveEntropy_WhitespaceXprv(t *testing.T) {
path, _ := ParsePath("m/83696968'/0'/0'")
// Whitespace-padded xprv should parse identically.
entropy1, err := DeriveEntropyFromString(specMasterXprv, path)
if err != nil {
t.Fatal(err)
}
entropy2, err := DeriveEntropyFromString(" "+specMasterXprv+" \n", path)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(entropy1, entropy2) {
t.Error("whitespace-trimmed xprv produced different entropy")
}
}
// --- Property tests ---
func TestDeriveEntropy_Determinism(t *testing.T) {
key, err := ParseKey(specMasterXprv)
if err != nil {
t.Fatal(err)
}
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
e1, err := DeriveEntropy(key, path)
if err != nil {
t.Fatalf("first call: %v", err)
}
e2, err := DeriveEntropy(key, path)
if err != nil {
t.Fatalf("second call: %v", err)
}
if !bytes.Equal(e1, e2) {
t.Error("not deterministic: same input produced different output")
}
}
func TestDeriveEntropy_IndexIndependence(t *testing.T) {
key, err := ParseKey(specMasterXprv)
if err != nil {
t.Fatal(err)
}
defer key.Zero()
p0, _ := ParsePath("m/83696968'/0'/0'")
p1, _ := ParsePath("m/83696968'/0'/1'")
e0, err := DeriveEntropy(key, p0)
if err != nil {
t.Fatalf("index 0: %v", err)
}
e1, err := DeriveEntropy(key, p1)
if err != nil {
t.Fatalf("index 1: %v", err)
}
if bytes.Equal(e0, e1) {
t.Error("different indexes produced identical entropy")
}
}
func TestDeriveEntropy_AppIndependence(t *testing.T) {
key, err := ParseKey(specMasterXprv)
if err != nil {
t.Fatal(err)
}
defer key.Zero()
p39, _ := ParsePath("m/83696968'/39'/0'/12'/0'")
p2, _ := ParsePath("m/83696968'/2'/0'")
e39, err := DeriveEntropy(key, p39)
if err != nil {
t.Fatalf("app 39: %v", err)
}
e2, err := DeriveEntropy(key, p2)
if err != nil {
t.Fatalf("app 2: %v", err)
}
if bytes.Equal(e39, e2) {
t.Error("different app codes produced identical entropy")
}
}
// --- secp256k1 validation tests ---
func TestValidateSecp256k1Key(t *testing.T) {
// Valid key (from spec vector 1).
validKey, _ := hex.DecodeString("cca20ccb0e9a90feb0912870c3323b24874b0ca3d8018c4b96d0b97c0e82ded0")
if err := ValidateSecp256k1Key(validKey); err != nil {
t.Errorf("valid key rejected: %v", err)
}
// Zero key.
zeroKey := make([]byte, 32)
if err := ValidateSecp256k1Key(zeroKey); !errors.Is(err, ErrInvalidKeyRange) {
t.Errorf("zero key: got %v, want ErrInvalidKeyRange", err)
}
// Key >= curve order.
orderKey, _ := hex.DecodeString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141")
if err := ValidateSecp256k1Key(orderKey); !errors.Is(err, ErrInvalidKeyRange) {
t.Errorf("order key: got %v, want ErrInvalidKeyRange", err)
}
// Wrong length.
if err := ValidateSecp256k1Key([]byte{0x01}); !errors.Is(err, ErrInvalidKeyRange) {
t.Errorf("short key: got %v, want ErrInvalidKeyRange", err)
}
}
// --- Option tests ---
func TestWithHMACKey_Nil(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
_, err := DeriveEntropy(key, path, WithHMACKey(nil))
if !errors.Is(err, ErrInvalidHMACKey) {
t.Errorf("got: %v, want: %v", err, ErrInvalidHMACKey)
}
}
func TestWithHMACKey_Empty(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
_, err := DeriveEntropy(key, path, WithHMACKey([]byte{}))
if !errors.Is(err, ErrInvalidHMACKey) {
t.Errorf("got: %v, want: %v", err, ErrInvalidHMACKey)
}
}
func TestWithHMACKey_Custom(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
// Custom HMAC key should produce different entropy.
standard, err := DeriveEntropy(key, path)
if err != nil {
t.Fatalf("standard: %v", err)
}
custom, err := DeriveEntropy(key, path, WithHMACKey([]byte("custom-key")))
if err != nil {
t.Fatalf("custom HMAC key: %v", err)
}
if bytes.Equal(standard, custom) {
t.Error("custom HMAC key produced identical entropy to standard")
}
}
func TestWithPostProcessor_TooShort(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
short := func(entropy []byte) ([]byte, error) {
return entropy[:32], nil
}
_, err := DeriveEntropy(key, path, WithEntropyPostProcessor(short))
if !errors.Is(err, ErrPostProcessorShort) {
t.Errorf("got: %v, want: %v", err, ErrPostProcessorShort)
}
}
func TestWithPostProcessor_Valid(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
// Post-processor that prepends a marker byte.
pp := func(entropy []byte) ([]byte, error) {
out := make([]byte, len(entropy)+1)
out[0] = 0xFF
copy(out[1:], entropy)
return out, nil
}
result, err := DeriveEntropy(key, path, WithEntropyPostProcessor(pp))
if err != nil {
t.Fatalf("valid post-processor: %v", err)
}
if result[0] != 0xFF {
t.Error("post-processor output not used")
}
if len(result) != 65 {
t.Errorf("length: got %d, want 65", len(result))
}
}
// --- Custom deriver tests ---
func TestWithCustomDeriver(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
// Custom deriver that returns a fixed 32-byte key.
fixedKey := make([]byte, 32)
fixedKey[0] = 0x42
deriver := func(_ *hdkeychain.ExtendedKey, _ Path) ([]byte, error) {
out := make([]byte, 32)
copy(out, fixedKey)
return out, nil
}
entropy, err := DeriveEntropy(key, path, WithCustomDeriver(deriver))
if err != nil {
t.Fatalf("custom deriver: %v", err)
}
if len(entropy) != 64 {
t.Errorf("entropy length: got %d, want 64", len(entropy))
}
// Must differ from standard derivation.
standard, sErr := DeriveEntropy(key, path)
if sErr != nil {
t.Fatalf("standard derivation: %v", sErr)
}
if bytes.Equal(entropy, standard) {
t.Error("custom deriver produced same entropy as standard")
}
// DeriveKeyAndEntropy with custom deriver should return the fixed key.
dk, _, err := DeriveKeyAndEntropy(key, path, WithCustomDeriver(deriver))
if err != nil {
t.Fatalf("DeriveKeyAndEntropy custom: %v", err)
}
if !bytes.Equal(dk, fixedKey) {
t.Error("DeriveKeyAndEntropy did not return the custom deriver's key")
}
}
func TestWithCustomDeriver_EmptyReturn(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
deriver := func(_ *hdkeychain.ExtendedKey, _ Path) ([]byte, error) {
return nil, nil
}
_, err := DeriveEntropy(key, path, WithCustomDeriver(deriver))
if !errors.Is(err, ErrEmptyKeyMaterial) {
t.Errorf("got: %v, want: %v", err, ErrEmptyKeyMaterial)
}
}
func TestWithCustomDeriver_Error(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
deriver := func(_ *hdkeychain.ExtendedKey, _ Path) ([]byte, error) {
return nil, errors.New("deriver failed")
}
_, err := DeriveEntropy(key, path, WithCustomDeriver(deriver))
if err == nil {
t.Fatal("expected error from failing deriver")
}
}
// --- ValidateSecp256k1Key edge cases ---
func TestValidateSecp256k1Key_MaxValid(t *testing.T) {
// order - 1 is the maximum valid private key.
orderMinus1, _ := hex.DecodeString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140")
if err := ValidateSecp256k1Key(orderMinus1); err != nil {
t.Errorf("order-1 should be valid: %v", err)
}
}
func TestValidateSecp256k1Key_One(t *testing.T) {
// 1 is the minimum valid private key.
one := make([]byte, 32)
one[31] = 0x01
if err := ValidateSecp256k1Key(one); err != nil {
t.Errorf("key=1 should be valid: %v", err)
}
}
// --- Path builder overflow protection ---
func TestBuildPath_OverflowPanics(t *testing.T) {
defer func() {
r := recover()
if r == nil {
t.Fatal("expected panic on overflow component, got none")
}
}()
// 0x80000000 exceeds hardenedMax (0x7FFFFFFF).
// This would cause silent uint32 wrap in Derive().
CorePath(0, 0x80000000)
}
// --- Combined option tests ---
func TestCustomDeriver_WithPostProcessor(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
fixedKey := make([]byte, 32)
fixedKey[0] = 0x42
deriver := func(_ *hdkeychain.ExtendedKey, _ Path) ([]byte, error) {
out := make([]byte, 32)
copy(out, fixedKey)
return out, nil
}
pp := func(entropy []byte) ([]byte, error) {
out := make([]byte, len(entropy)+1)
out[0] = 0xAA
copy(out[1:], entropy)
return out, nil
}
// Custom deriver only (no post-processor).
entropyPlain, err := DeriveEntropy(key, path, WithCustomDeriver(deriver))
if err != nil {
t.Fatalf("deriver only: %v", err)
}
// Custom deriver + post-processor.
entropyPP, err := DeriveEntropy(key, path, WithCustomDeriver(deriver), WithEntropyPostProcessor(pp))
if err != nil {
t.Fatalf("deriver + post-processor: %v", err)
}
if len(entropyPP) != 65 {
t.Errorf("post-processed length: got %d, want 65", len(entropyPP))
}
if entropyPP[0] != 0xAA {
t.Error("post-processor marker byte not present")
}
// The post-processed output should contain the plain entropy shifted by 1.
if !bytes.Equal(entropyPP[1:], entropyPlain) {
t.Error("post-processed entropy payload does not match plain entropy")
}
// DeriveKeyAndEntropy with both options.
dk, ent, err := DeriveKeyAndEntropy(key, path, WithCustomDeriver(deriver), WithEntropyPostProcessor(pp))
if err != nil {
t.Fatalf("DeriveKeyAndEntropy combined: %v", err)
}
if !bytes.Equal(dk, fixedKey) {
t.Error("DeriveKeyAndEntropy did not return the custom key")
}
if !bytes.Equal(ent, entropyPP) {
t.Error("DeriveKeyAndEntropy entropy does not match DeriveEntropy")
}
}
// TestPostProcessor_AliasingInput verifies that a post-processor returning
// the input slice unchanged does not produce zeroed output. This is a
// regression test for a slice-aliasing bug where ZeroBytes(entropy) would
// destroy the returned processed slice if they shared the same backing array.
func TestPostProcessor_AliasingInput(t *testing.T) {
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path, _ := ParsePath("m/83696968'/0'/0'")
// Post-processor that returns the input unchanged (same slice).
noop := func(entropy []byte) ([]byte, error) {
return entropy, nil
}
result, err := DeriveEntropy(key, path, WithEntropyPostProcessor(noop))
if err != nil {
t.Fatalf("noop post-processor: %v", err)
}
// The result must NOT be all zeros.
allZero := true
for _, b := range result {
if b != 0 {
allZero = false
break
}
}
if allZero {
t.Fatal("post-processor returning input unchanged produced all-zero output (aliasing bug)")
}
// Must match standard derivation.
standard, _ := DeriveEntropy(key, path)
if !bytes.Equal(result, standard) {
t.Error("noop post-processor produced different entropy than standard")
}
}
// --- Anti-tamper tests ---
// These tests verify hardcoded constants against independent sources.
// A rogue contributor changing a crypto constant would need to change
// both the constant AND these independent verifications simultaneously.
func TestHMACKey_Content(t *testing.T) {
// Verify the HMAC key is exactly the BIP85-specified ASCII string.
// This catches single-character mutations that pass the length check.
want := []byte{
0x62, 0x69, 0x70, 0x2d, 0x65, 0x6e, 0x74, 0x72, 0x6f,
0x70, 0x79, 0x2d, 0x66, 0x72, 0x6f, 0x6d, 0x2d, 0x6b,
} // "bip-entropy-from-k" as raw bytes
if !bytes.Equal(hmacKeyBIP85, want) {
t.Fatal("HMAC key content does not match BIP85 spec")
}
}
func TestSecp256k1Order_Correct(t *testing.T) {
// Verify our hardcoded curve order matches the btcec library.
// Independent source: btcec computes this from the curve parameters.
btcecOrder := btcec.S256().N
if secp256k1Order.Cmp(btcecOrder) != 0 {
t.Fatalf("secp256k1 order mismatch:\n ours: %s\n btcec: %s",
secp256k1Order.Text(16), btcecOrder.Text(16))
}
}
func TestZeroBytes_ActuallyZeros(t *testing.T) {
buf := []byte{0xFF, 0xAA, 0x55, 0x01, 0x80, 0xDE, 0xAD, 0xBE}
ZeroBytes(buf)
for i, b := range buf {
if b != 0 {
t.Fatalf("ZeroBytes did not zero byte at index %d: got 0x%02x", i, b)
}
}
}
func TestZeroBytes_NilSafe(t *testing.T) {
// Must not panic on nil slice.
ZeroBytes(nil)
// Must not panic on empty slice.
ZeroBytes([]byte{})
}
// ========================================================================
// AI threat defense tests
//
// These tests defend against a compromised AI (or rogue human contributor)
// introducing subtle changes that produce valid-looking but cryptographically
// wrong output. Each test verifies a specific attack vector that would be
// invisible to standard unit tests.
//
// Design principle: every test uses at least TWO independent verification
// paths. An attacker must modify BOTH paths simultaneously, which is
// highly visible in code review.
// ========================================================================
// TestAntiAI_HMACArgumentOrder verifies HMAC is called with the correct
// argument order: key="bip-entropy-from-k", message=derived_private_key.
//
// Attack: swap key and message in hmac.New(). Both produce valid 64-byte
// output, but the entropy is completely different. Spec vectors catch this,
// but this test makes the defense EXPLICIT and independent.
func TestAntiAI_HMACArgumentOrder(t *testing.T) {
// Compute HMAC-SHA512 manually with the correct argument order.
derivedKey, _ := hex.DecodeString("cca20ccb0e9a90feb0912870c3323b24874b0ca3d8018c4b96d0b97c0e82ded0")
// Correct: HMAC(key=hmacKey, msg=derivedKey)
correctMAC := hmac.New(sha512.New, hmacKeyBIP85)
correctMAC.Write(derivedKey)
correctEntropy := correctMAC.Sum(nil)
// Wrong: HMAC(key=derivedKey, msg=hmacKey) - swapped arguments
wrongMAC := hmac.New(sha512.New, derivedKey)
wrongMAC.Write(hmacKeyBIP85)
wrongEntropy := wrongMAC.Sum(nil)
// The two must differ (proves the order matters).
if bytes.Equal(correctEntropy, wrongEntropy) {
t.Fatal("HMAC with swapped key/message produced identical output (mathematically impossible)")
}
// The correct order must match what DeriveEntropy produces.
// This uses EntropyFromRawKey which applies the same HMAC step.
libEntropy, err := EntropyFromRawKey(derivedKey)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(libEntropy, correctEntropy) {
t.Fatal("library HMAC argument order does not match correct order (key=hmacKey, msg=derivedKey)")
}
}
// TestAntiAI_FullEntropyUsedInHMAC verifies that the full 32-byte derived
// key is used as HMAC input, not a truncated or zeroed version.
//
// Attack: silently zero or truncate bytes before HMAC. Output is still
// deterministic and 64 bytes, but entropy is reduced. This test catches
// any truncation by verifying the output matches the spec.
func TestAntiAI_FullEntropyUsedInHMAC(t *testing.T) {
// Spec vector 1: derived key -> entropy.
fullKey, _ := hex.DecodeString("cca20ccb0e9a90feb0912870c3323b24874b0ca3d8018c4b96d0b97c0e82ded0")
wantEntropy := "efecfbccffea313214232d29e71563d941229afb4338c21f9517c41aaa0d16f00b83d2a09ef747e7a64e8e2bd5a14869e693da66ce94ac2da570ab7ee48618f7"
// Library output with full key.
libEntropy, err := EntropyFromRawKey(fullKey)
if err != nil {
t.Fatal(err)
}
if hex.EncodeToString(libEntropy) != wantEntropy {
t.Fatal("library entropy does not match spec vector (full key may not be used in HMAC)")
}
// Verify truncation would produce different output.
// Zero the last byte of the key and re-derive.
truncatedKey := make([]byte, 32)
copy(truncatedKey, fullKey)
truncatedKey[31] = 0x00 // Corrupt last byte.
truncatedEntropy, err := EntropyFromRawKey(truncatedKey)
if err != nil {
t.Fatal(err)
}
if bytes.Equal(libEntropy, truncatedEntropy) {
t.Fatal("truncating last byte of key produced same entropy (HMAC may not use full key)")
}
ZeroBytes(truncatedKey)
ZeroBytes(truncatedEntropy)
ZeroBytes(libEntropy)
}
// TestAntiAI_SpecVectorIndependentHMAC recomputes spec vector 1 entropy
// using only Go stdlib crypto/hmac + crypto/sha512, without calling any
// go-bip85 function. This is the core pipeline oracle.
//
// Attack: modify the library's HMAC implementation to produce biased
// output AND update the expected test values to match. This independent
// computation catches it because the attacker would need to also modify
// this test's inline HMAC computation.
func TestAntiAI_SpecVectorIndependentHMAC(t *testing.T) {
// BIP85 spec vector 1:
// Derived key at m/83696968'/0'/0' from spec master key.
derivedKey, _ := hex.DecodeString("cca20ccb0e9a90feb0912870c3323b24874b0ca3d8018c4b96d0b97c0e82ded0")
// Independent HMAC computation using only stdlib.
key := []byte("bip-entropy-from-k") // 18 bytes, ASCII
mac := hmac.New(sha512.New, key)
mac.Write(derivedKey)
entropy := mac.Sum(nil)
// Expected entropy from spec (hardcoded, not from any go-bip85 variable).
want := "efecfbccffea313214232d29e71563d941229afb4338c21f9517c41aaa0d16f00b83d2a09ef747e7a64e8e2bd5a14869e693da66ce94ac2da570ab7ee48618f7"
got := hex.EncodeToString(entropy)
if got != want {
t.Fatalf("independent HMAC computation does not match spec:\n got: %s\n want: %s", got, want)
}
// Cross-check: library must produce the same result.
libEntropy, err := EntropyFromRawKey(derivedKey)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(entropy, libEntropy) {
t.Fatal("library output diverges from independent HMAC computation")
}
}
// TestAntiAI_NoKeyMaterialInErrors verifies that error messages from the
// derivation pipeline never contain key bytes, entropy bytes, or xprv
// strings. A rogue AI could embed key material in error messages to
// exfiltrate secrets via logging frameworks.
func TestAntiAI_NoKeyMaterialInErrors(t *testing.T) {
// Trigger various error paths and inspect the error messages.
testCases := []struct {
name string
fn func() error
}{
{"nil key", func() error {
_, err := DeriveEntropy(nil, CorePath(0, 0))
return err
}},
{"empty xprv", func() error {
_, err := ParseKey("")
return err
}},
{"invalid xprv", func() error {
_, err := ParseKey("xprv_clearly_invalid_but_long_enough_to_contain_fake_key_material_abcdef1234567890")
return err
}},
{"public key", func() error {
_, err := ParseKey("xpub661MyMwAqRbcEpFyaVwRcfeeAtFKbH3UnesyJDSbkBQw15pyoHMA6bTEcsSY1NQ8Yxfme29GEXRdj9fWwnPrAG7wX9VbT3GUh9d4GMhawAT")
return err
}},
{"invalid WIF entropy", func() error {
_, err := DeriveWIF(make([]byte, 31), nil)
return err
}},
{"zero secp256k1 key", func() error {
return ValidateSecp256k1Key(make([]byte, 32))
}},
}
// Patterns that should NEVER appear in error messages.
// These are hex fragments of the spec master key's private key data
// and common xprv prefixes that would indicate key material leakage.
forbidden := []string{
"xprv9s21ZrQH143K", // xprv prefix (first 16 chars)
"efecfbcc", // spec vector 1 entropy prefix
"cca20ccb", // spec vector 1 derived key prefix
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := tc.fn()
if err == nil {
return // No error to inspect.
}
errMsg := err.Error()
for _, pattern := range forbidden {
if strings.Contains(errMsg, pattern) {
t.Errorf("error message contains key material %q: %s", pattern, errMsg)
}
}
})
}
}
// TestAntiAI_XPRVFieldOrder verifies the BIP85-specific reversed field
// ordering independently. The BIP85 spec reverses BIP32 convention:
// first 32 bytes = chain code, second 32 bytes = private key.
//
// Attack: swap the fields back to BIP32 standard order. The output is
// still a valid xprv. Tests that only check "it parses" won't catch it.
// This test verifies the SPECIFIC bytes at each position.
func TestAntiAI_XPRVFieldOrder(t *testing.T) {
// Use spec XPRV vector entropy.
key, _ := ParseKey(specMasterXprv)
defer key.Zero()
path := XPRVPath(0)
entropy, err := DeriveEntropy(key, path)
if err != nil {
t.Fatal(err)
}
defer ZeroBytes(entropy)
xprv, err := DeriveXPRV(entropy, nil)
if err != nil {
t.Fatal(err)
}
// Parse back and verify field positions match BIP85's REVERSED ordering.
parsed, err := hdkeychain.NewKeyFromString(xprv)
if err != nil {
t.Fatal(err)
}
defer parsed.Zero()
// Chain code must be entropy[0:32] (first 32 bytes).
if !bytes.Equal(parsed.ChainCode(), entropy[:32]) {
t.Error("chain code is not entropy[0:32] (BIP85 reversed field order violated)")
}
// Private key must be entropy[32:64] (second 32 bytes).
privKey, _ := parsed.ECPrivKey()
if !bytes.Equal(privKey.Serialize(), entropy[32:64]) {
t.Error("private key is not entropy[32:64] (BIP85 reversed field order violated)")