-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6d40715
commit 0437a3a
Showing
1 changed file
with
73 additions
and
0 deletions.
There are no files selected for viewing
73 changes: 73 additions & 0 deletions
73
...CommunityCoreiOS/SOLARdVPNCommunityCoreiOS/Services/SecurityService/SecurityService.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// | ||
// SecurityService.swift | ||
// SOLARdVPNCommunityCoreiOS | ||
// | ||
// Created by Lika Vorobeva on 05.10.2022. | ||
// | ||
|
||
import Foundation | ||
import SentinelWallet | ||
import HDWallet | ||
import SwiftKeychainWrapper | ||
|
||
enum SecurityServiceError: Error { | ||
case emptyInput | ||
case invalidInput | ||
} | ||
|
||
private struct Constants { | ||
let key = "password" | ||
let mnemonicsCount = 24 | ||
} | ||
private let constants = Constants() | ||
|
||
final public class SecurityService: SecurityServiceType { | ||
private let keychain: KeychainWrapper | ||
|
||
public init( | ||
keychain: KeychainWrapper = .init( | ||
serviceName: "SecurityService", | ||
accessGroup: "group.ee.solarlabs.community-core.ios" | ||
) | ||
) { | ||
self.keychain = keychain | ||
} | ||
|
||
public func save(mnemonics: [String], for account: String) -> Bool { | ||
let mnemonicString = mnemonics.joined(separator: " ") | ||
return keychain.set( | ||
mnemonicString, | ||
forKey: account.sha1(), | ||
withAccessibility: .afterFirstUnlockThisDeviceOnly | ||
) | ||
} | ||
|
||
public func loadMnemonics(for account: String) -> [String]? { | ||
keychain | ||
.string(forKey: account.sha1())? | ||
.trimmingCharacters(in: .whitespacesAndNewlines) | ||
.components(separatedBy: " ") | ||
} | ||
|
||
public func mnemonicsExists(for account: String) -> Bool { | ||
keychain.hasValue(forKey: account.sha1()) | ||
} | ||
|
||
public func restore(from mnemonics: [String]) -> Result<String, Error> { | ||
guard !mnemonics.isEmpty else { | ||
return .failure(SecurityServiceError.emptyInput) | ||
} | ||
|
||
guard | ||
mnemonics.count == constants.mnemonicsCount, mnemonics.allSatisfy({ WordList.english.words.contains($0) }) | ||
else { | ||
return .failure(SecurityServiceError.invalidInput) | ||
} | ||
|
||
guard let restoredAddress = restoreAddress(for: mnemonics) else { | ||
return .failure(SecurityServiceError.invalidInput) | ||
} | ||
|
||
return .success(restoredAddress) | ||
} | ||
} |