From c30aa1dc9c5feef73d9fccaf78626b5728562f1f Mon Sep 17 00:00:00 2001 From: Simon McLoughlin Date: Wed, 8 Nov 2023 15:52:10 +0000 Subject: [PATCH] - explicitly catch missing errors - sanity check secp256k1 calls don't crash with incorrect input --- Sources/KukaiCryptoSwift/PublicKey.swift | 6 ++++-- .../KukaiCryptoSwiftTests/KeyPairTests.swift | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Sources/KukaiCryptoSwift/PublicKey.swift b/Sources/KukaiCryptoSwift/PublicKey.swift index 8503fe3..ca32a7a 100644 --- a/Sources/KukaiCryptoSwift/PublicKey.swift +++ b/Sources/KukaiCryptoSwift/PublicKey.swift @@ -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 } diff --git a/Tests/KukaiCryptoSwiftTests/KeyPairTests.swift b/Tests/KukaiCryptoSwiftTests/KeyPairTests.swift index 664f4b1..17c58ae 100644 --- a/Tests/KukaiCryptoSwiftTests/KeyPairTests.swift +++ b/Tests/KukaiCryptoSwiftTests/KeyPairTests.swift @@ -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) + + } }