@@ -306,3 +306,61 @@ func TestParsePrivateKey_Error(t *testing.T) {
306
306
}
307
307
}
308
308
}
309
+
310
+ func TestPrivateKey_Zero (t * testing.T ) {
311
+ var testCases []bip32.Goldie
312
+ ReadGoldenJSON (t , bip32 .GoldenName , & testCases )
313
+
314
+ isZero := func (data []byte ) bool {
315
+ for _ , v := range data {
316
+ if 0 != v {
317
+ return false
318
+ }
319
+ }
320
+
321
+ return true
322
+ }
323
+
324
+ isZeroKey := func (xpriv * bip32.PrivateKey ) bool {
325
+ if nil == xpriv {
326
+ return true
327
+ }
328
+
329
+ xpub := xpriv .PublicKey
330
+ return isZero (xpriv .Data ) && isZero (xpriv .Version ) &&
331
+ isZero (xpub .ChainCode ) && 0 == xpub .ChildIndex && isZero (xpub .Data ) &&
332
+ 0 == xpub .Level && isZero (xpub .ParentFP ) && isZero (xpub .Version )
333
+ }
334
+
335
+ for _ , c := range testCases {
336
+ chains := c .Chains
337
+
338
+ t .Run ("" , func (st * testing.T ) {
339
+ for _ , chain := range chains {
340
+ xpriv , err := bip32 .ParsePrivateKey (chain .ExtendedPrivateKey )
341
+ if nil != err {
342
+ st .Fatalf ("unexpected error: %v" , err )
343
+ }
344
+
345
+ if isZeroKey (xpriv ) {
346
+ st .Fatalf ("private key %s shouldn't be zeroed" ,
347
+ chain .ExtendedPrivateKey )
348
+ }
349
+
350
+ xpriv .Zero ()
351
+
352
+ if ! isZeroKey (xpriv ) {
353
+ st .Fatalf ("private key %s should have been zeroed" ,
354
+ chain .ExtendedPrivateKey )
355
+ }
356
+ }
357
+ })
358
+ }
359
+
360
+ // edge case as nil private key
361
+ var xpriv * bip32.PrivateKey
362
+ xpriv .Zero ()
363
+ if ! isZeroKey (xpriv ) {
364
+ t .Fatal ("nil private key should be treated as zeroed already" )
365
+ }
366
+ }
0 commit comments