From 29908fe86d360ab8396e702e61e53d29ebec78d2 Mon Sep 17 00:00:00 2001 From: Alexander Osokin Date: Thu, 23 Mar 2023 18:29:28 +0500 Subject: [PATCH] IOS-3271 Validate the key --- .../HDWallet/BIP32/ExtendedPublicKey.swift | 22 ++++++++++++------- TangemSdk/TangemSdkTests/JSONRPCTests.swift | 13 +++++++++++ 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/TangemSdk/TangemSdk/Crypto/HDWallet/BIP32/ExtendedPublicKey.swift b/TangemSdk/TangemSdk/Crypto/HDWallet/BIP32/ExtendedPublicKey.swift index 9f534ab60..d7313c517 100644 --- a/TangemSdk/TangemSdk/Crypto/HDWallet/BIP32/ExtendedPublicKey.swift +++ b/TangemSdk/TangemSdk/Crypto/HDWallet/BIP32/ExtendedPublicKey.swift @@ -163,18 +163,24 @@ extension ExtendedPublicKey: Decodable { let publicKey = try container.decode(Data.self, forKey: .publicKey) let chainCode = try container.decode(Data.self, forKey: .chainCode) + let depth = try container.decodeIfPresent(Int.self, forKey: .depth) + let parentFingerprint = try container.decodeIfPresent(Data.self, forKey: .parentFingerprint) + let childNumber = try container.decodeIfPresent(UInt32.self, forKey: .childNumber) + + if let depth, let parentFingerprint, let childNumber { + try self.init(publicKey: publicKey, + chainCode: chainCode, + depth: depth, + parentFingerprint: parentFingerprint, + childNumber: childNumber) + return + } - guard let depth = try container.decodeIfPresent(Int.self, forKey: .depth), - let parentFingerprint = try container.decodeIfPresent(Data.self, forKey: .parentFingerprint), - let childNumber = try container.decodeIfPresent(UInt32.self, forKey: .childNumber) else { + if depth == nil, parentFingerprint == nil, childNumber == nil { self.init(publicKey: publicKey, chainCode: chainCode) return } - try self.init(publicKey: publicKey, - chainCode: chainCode, - depth: depth, - parentFingerprint: parentFingerprint, - childNumber: childNumber) + throw TangemSdkError.decodingFailed("Missing data in the ExtendedPublicKey") } } diff --git a/TangemSdk/TangemSdkTests/JSONRPCTests.swift b/TangemSdk/TangemSdkTests/JSONRPCTests.swift index 00d0d717a..b0b41c03b 100644 --- a/TangemSdk/TangemSdkTests/JSONRPCTests.swift +++ b/TangemSdk/TangemSdkTests/JSONRPCTests.swift @@ -36,6 +36,19 @@ class JSONRPCTests: XCTestCase { XCTAssertEqual(decoded.parentFingerprint.hexString, "00000000") } + func testDecodeInvalidExtendedPublicKey() throws { + let json = + """ + { + "publicKey": "0200300397571D99D41BB2A577E2CBE495C04AC5B9A97B7A4ECF999F23CE45E962", + "chainCode": "537F7361175B150732E17508066982B42D9FB1F8239C4D7BFC490088C83A8BBB", + "depth" : 1, + } + """ + + XCTAssertThrowsError(try JSONDecoder.tangemSdkDecoder.decode(ExtendedPublicKey.self, from: json.data(using: .utf8)!)) + } + func testDecodeExtendedPublicKey() throws { let json = """