Skip to content

Commit

Permalink
- explicitly catch missing errors
Browse files Browse the repository at this point in the history
- sanity check secp256k1 calls don't crash with incorrect input
  • Loading branch information
simonmcl committed Nov 8, 2023
1 parent 6cb9772 commit c30aa1d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
6 changes: 4 additions & 2 deletions Sources/KukaiCryptoSwift/PublicKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,10 @@ public struct PublicKey: Codable {

var cSignature = secp256k1_ecdsa_signature()
var publicKey = secp256k1_pubkey()
secp256k1_ecdsa_signature_parse_compact(context, &cSignature, signature)
_ = secp256k1_ec_pubkey_parse(context, &publicKey, self.bytes, self.bytes.count)
guard secp256k1_ecdsa_signature_parse_compact(context, &cSignature, signature) != 0,
secp256k1_ec_pubkey_parse(context, &publicKey, self.bytes, self.bytes.count) != 0 else {
return false
}

return secp256k1_ecdsa_verify(context, &cSignature, message, &publicKey) == 1
}
Expand Down
21 changes: 21 additions & 0 deletions Tests/KukaiCryptoSwiftTests/KeyPairTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -155,4 +155,25 @@ final class KeyPairTests: XCTestCase {
XCTAssert(dataString2.count == 0, dataString2.count.description)
XCTAssert(dataString2 == "", dataString2)
}

func testSafetyChecks() throws {
let messageToSign = "something very interesting that needs to be signed".bytes
let watermarkedBytes = messageToSign.addOperationWatermarkAndHash() ?? []
let mnemonic = try Mnemonic(seedPhrase: "kit trigger pledge excess payment sentence dutch mandate start sense seed venture")

let keyPair1 = KeyPair.regular(fromMnemonic: mnemonic, passphrase: "", andSigningCurve: .ed25519)
var signatureBytes = keyPair1?.privateKey.sign(bytes: watermarkedBytes) ?? []
signatureBytes.append(contentsOf: signatureBytes)
let signature1 = signatureBytes
let signatureHex1 = signature1.hexString + signature1.hexString


// Test function doesn't crash with more than 64 byte signature
XCTAssert(signatureBytes.count > 64)
XCTAssert(keyPair1?.publicKey.verify(message: watermarkedBytes, signature: signature1, hex: signatureHex1) == true)

// Test doesn't crash with empty
XCTAssert(keyPair1?.publicKey.verify(message: [], signature: [], hex: "") == false)

}
}

0 comments on commit c30aa1d

Please sign in to comment.