From ab8febfb360340432f4fc4937c51d573028c9d17 Mon Sep 17 00:00:00 2001 From: Dionysios Karatzas Date: Tue, 8 Feb 2022 15:45:23 +0200 Subject: [PATCH] Fix import wallet account instead of creating account? #111 --- web3sTests/Account/EthereumAccountTests.swift | 6 ++++++ web3swift/src/Account/EthereumAccount.swift | 16 +++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/web3sTests/Account/EthereumAccountTests.swift b/web3sTests/Account/EthereumAccountTests.swift index bc80e209..5397451b 100644 --- a/web3sTests/Account/EthereumAccountTests.swift +++ b/web3sTests/Account/EthereumAccountTests.swift @@ -28,6 +28,12 @@ class EthereumAccountTests: XCTestCase { let account = try? EthereumAccount.create(keyStorage: EthereumKeyLocalStorage(), keystorePassword: "PASSWORD") XCTAssertNotNil(account, "Failed to create account. Ensure key is valid in TestConfig.swift") } + + func testImportAccount() { + let account = try! EthereumAccount.importAccount(keyStorage: EthereumKeyLocalStorage(), privateKey: "0x2639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7173", keystorePassword: "PASSWORD") + + XCTAssertEqual(account.address.value, "0x675f5810feb3b09528e5cd175061b4eb8de69075") + } func testSignMessage() { let account = try! EthereumAccount(keyStorage: TestEthereumKeyStorage(privateKey: "0x2639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7173")) diff --git a/web3swift/src/Account/EthereumAccount.swift b/web3swift/src/Account/EthereumAccount.swift index 92c48c6a..e727a975 100644 --- a/web3swift/src/Account/EthereumAccount.swift +++ b/web3swift/src/Account/EthereumAccount.swift @@ -21,6 +21,7 @@ public protocol EthereumAccountProtocol { public enum EthereumAccountError: Error { case createAccountError + case importAccountError case loadAccountError case signError } @@ -76,7 +77,20 @@ public class EthereumAccount: EthereumAccountProtocol { throw EthereumAccountError.createAccountError } } - + + public static func importAccount(keyStorage: EthereumKeyStorageProtocol, privateKey: String, keystorePassword password: String) throws -> EthereumAccount { + guard let privateKey = privateKey.web3.hexData else { + throw EthereumAccountError.importAccountError + } + do { + let encodedData = try KeystoreUtil.encode(privateKey: privateKey, password: password) + try keyStorage.storePrivateKey(key: encodedData) + return try self.init(keyStorage: keyStorage, keystorePassword: password) + } catch { + throw EthereumAccountError.importAccountError + } + } + public func sign(data: Data) throws -> Data { return try KeyUtil.sign(message: data, with: self.privateKeyData, hashing: true) }