Skip to content

Commit

Permalink
Modify the function of SignCanonical in btcec, do makeCompact after i…
Browse files Browse the repository at this point in the history
…sCanonicalSig.

Since function recoverKeyFromSignature is called inside function makeCompact, the performance loss calculated by function recoverKeyFromSignature is relatively large.
So do makeCompact after isCanonicalSig can reduce the number of times it is executed, when isCanonicalSig is false then continue the next loop.
The average performance improvement after modification is nearly 40%-50%.
  • Loading branch information
yjwxfq authored Aug 15, 2024
1 parent 59afdfa commit 65e9d96
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions btcsuite/btcd/btcec/privkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,16 @@ func (p *PrivateKey) SignCanonical(curve *KoblitzCurve, hash []byte) ([]byte, er
return nil, err
}

if !isCanonicalSig(sig.R.Bytes(), sig.S.Bytes()) {
continue
}

compactSig, err := makeCompact(curve, sig, p, hash, true)
if err != nil {
continue
}

if isCanonical(compactSig) {
return compactSig, nil
}
return compactSig, nil
}
return nil, errors.New("couldn't find a canonical signature")
}
Expand Down Expand Up @@ -110,3 +112,11 @@ func isCanonical(compactSig []byte) bool {
t4 := !(d[33] == 0 && ((d[34] & 0x80) == 0))
return t1 && t2 && t3 && t4
}

func isCanonicalSig(r []byte, s []byte) bool {
t1 := (r[0] & 0x80) == 0
t2 := !(r[0] == 0 && ((r[1] & 0x80) == 0))
t3 := (s[0] & 0x80) == 0
t4 := !(s[0] == 0 && ((s[1] & 0x80) == 0))
return t1 && t2 && t3 && t4
}

0 comments on commit 65e9d96

Please sign in to comment.