Skip to content

Commit 1846070

Browse files
committed
some cleanup
1 parent 951ba0c commit 1846070

File tree

3 files changed

+36
-40
lines changed

3 files changed

+36
-40
lines changed

Sources/Web3Core/KeystoreManager/BIP32HDNode.swift

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ extension UInt32 {
1919
let byteArray = Array(bytePtr)
2020
return Data(byteArray)
2121
}
22+
static var maxIterationIndex = UInt32(1) << 31
2223
}
2324

2425
public class HDNode {
@@ -36,11 +37,11 @@ public class HDNode {
3637
public var parentFingerprint: Data = Data(repeating: 0, count: 4)
3738
public var childNumber: UInt32 = UInt32(0)
3839
public var isHardened: Bool {
39-
childNumber >= (UInt32(1) << 31)
40+
childNumber >= UInt32.maxIterationIndex
4041
}
4142
public var index: UInt32 {
4243
if self.isHardened {
43-
return childNumber - (UInt32(1) << 31)
44+
return childNumber - UInt32.maxIterationIndex
4445
} else {
4546
return childNumber
4647
}
@@ -91,7 +92,7 @@ public class HDNode {
9192
guard seed.count >= 16 else { return nil }
9293

9394
guard let hmacKey = "Bitcoin seed".data(using: .ascii) else { return nil }
94-
let hmac:Authenticator = HMAC(key: hmacKey.bytes, variant: HMAC.Variant.sha2(.sha512))
95+
let hmac: Authenticator = HMAC(key: hmacKey.bytes, variant: HMAC.Variant.sha2(.sha512))
9596

9697
guard let entropy = try? hmac.authenticate(seed.bytes), entropy.count == 64 else { return nil }
9798
let I_L = entropy[0..<32]
@@ -112,7 +113,7 @@ public class HDNode {
112113
public static var defaultPathPrefix: String = "m/44'/60'/0'"
113114
public static var defaultPathMetamask: String = "m/44'/60'/0'/0/0"
114115
public static var defaultPathMetamaskPrefix: String = "m/44'/60'/0'/0"
115-
public static var hardenedIndexPrefix: UInt32 = (UInt32(1) << 31)
116+
public static var hardenedIndexPrefix: UInt32 = UInt32.maxIterationIndex
116117
}
117118

118119
extension HDNode {
@@ -126,14 +127,14 @@ extension HDNode {
126127

127128
public func deriveWithoutPrivateKey(index: UInt32, hardened: Bool = false) -> HDNode? {
128129
var entropy: [UInt8] // derive public key when is itself public key
129-
if index >= (UInt32(1) << 31) || hardened {
130+
if index >= UInt32.maxIterationIndex || hardened {
130131
return nil // no derivation of hardened public key from extended public key
131132
} else {
132133
let hmac: Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha2(.sha512))
133134
var inputForHMAC = Data()
134135
inputForHMAC.append(self.publicKey)
135136
inputForHMAC.append(index.serialize32())
136-
guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil }
137+
guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else { return nil }
137138
guard ent.count == 64 else { return nil }
138139
entropy = ent
139140
}
@@ -148,7 +149,7 @@ extension HDNode {
148149
return nil
149150
}
150151
guard let tempKey = bn.serialize().setLengthLeft(32) else { return nil }
151-
guard SECP256K1.verifyPrivateKey(privateKey: tempKey) else {return nil }
152+
guard SECP256K1.verifyPrivateKey(privateKey: tempKey) else { return nil }
152153
guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: tempKey, compressed: true) else { return nil }
153154
guard pubKeyCandidate.bytes.first == 0x02 || pubKeyCandidate.bytes.first == 0x03 else { return nil }
154155
guard let newPublicKey = SECP256K1.combineSerializedPublicKeys(keys: [self.publicKey, pubKeyCandidate], outputCompressed: true) else { return nil }
@@ -180,17 +181,17 @@ extension HDNode {
180181
}
181182
var entropy: [UInt8]
182183
var trueIndex: UInt32
183-
if index >= (UInt32(1) << 31) || hardened {
184+
if index >= UInt32.maxIterationIndex || hardened {
184185
trueIndex = index
185-
if trueIndex < (UInt32(1) << 31) {
186-
trueIndex = trueIndex + (UInt32(1) << 31)
186+
if trueIndex < UInt32.maxIterationIndex {
187+
trueIndex = trueIndex + UInt32.maxIterationIndex
187188
}
188189
let hmac: Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha2(.sha512))
189190
var inputForHMAC = Data()
190191
inputForHMAC.append(Data([UInt8(0x00)]))
191192
inputForHMAC.append(privateKey)
192193
inputForHMAC.append(trueIndex.serialize32())
193-
guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil }
194+
guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else { return nil }
194195
guard ent.count == 64 else { return nil }
195196
entropy = ent
196197
} else {
@@ -199,7 +200,7 @@ extension HDNode {
199200
var inputForHMAC = Data()
200201
inputForHMAC.append(self.publicKey)
201202
inputForHMAC.append(trueIndex.serialize32())
202-
guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil }
203+
guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else { return nil }
203204
guard ent.count == 64 else { return nil }
204205
entropy = ent
205206
}
@@ -221,7 +222,7 @@ extension HDNode {
221222
return nil
222223
}
223224
guard let privKeyCandidate = newPK.serialize().setLengthLeft(32) else { return nil }
224-
guard SECP256K1.verifyPrivateKey(privateKey: privKeyCandidate) else {return nil }
225+
guard SECP256K1.verifyPrivateKey(privateKey: privKeyCandidate) else { return nil }
225226
guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: privKeyCandidate, compressed: true) else { return nil }
226227
guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else { return nil }
227228
guard self.depth < UInt8.max else { return nil }

Sources/Web3Core/KeystoreManager/BIP32Keystore.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,6 @@ public class BIP32Keystore: AbstractKeystore {
9797
try self.init(seed: seed, password: password, prefixPath: prefixPath, aesMode: aesMode)
9898
}
9999

100-
//TODO: Unit Test
101-
//TODO: merge and cleanup with above code
102100
public convenience init?(mnemonicsPhrase: [String], password: String, mnemonicsPassword: String = "", language: BIP39Language = .english, prefixPath: String = HDNode.defaultPathMetamaskPrefix, aesMode: String = "aes-128-cbc") throws {
103101
guard var seed = BIP39.seedFromMmemonics(mnemonicsPhrase, password: mnemonicsPassword, language: language) else {
104102
throw AbstractKeystoreError.noEntropyError

Sources/Web3Core/KeystoreManager/BIP39.swift

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public enum BIP39Language {
4343
return " "
4444
}
4545
}
46-
46+
4747
init?(language: String) {
4848
switch language {
4949
case "english":
@@ -69,80 +69,77 @@ public enum BIP39Language {
6969
}
7070

7171
public class BIP39 {
72-
/**
73-
Initializes a new mnemonics set with the provided bitsOfEntropy.
74-
**/
7572
/// Initializes a new mnemonics set with the provided bitsOfEntropy.
7673
/// - Parameters:
77-
/// - bitsOfEntropy: 128 - 12 words, 192 - 18 words , 256 - 24 words in output.
74+
/// - bitsOfEntropy: 128 - 12 words, 192 - 18 words, 256 - 24 words in output.
7875
/// - language: words language, default english
7976
/// - Returns: random 12-24 words, that represent new Mnemonic phrase.
8077
static public func generateMnemonics(bitsOfEntropy: Int, language: BIP39Language = .english) throws -> String? {
8178
guard let entropy = entropyOf(size: bitsOfEntropy) else { throw AbstractKeystoreError.noEntropyError }
8279
return generateMnemonicsFromEntropy(entropy: entropy, language: language)
8380
}
84-
81+
8582
static public func generateMnemonics(entropy: Int, language: BIP39Language = .english) -> [String]? {
8683
guard let entropy = entropyOf(size: entropy) else { return nil }
8784
return generateMnemonicsFrom(entropy: entropy, language: language)
8885
}
89-
86+
9087
static private func entropyOf(size: Int) -> Data? {
9188
guard size >= 128 && size <= 256 && size.isMultiple(of: 32) else {
9289
return nil
9390
}
94-
91+
9592
return Data.randomBytes(length: size/8)
9693
}
97-
94+
9895
static func bitarray(from data: Data) -> String {
9996
data.map {
10097
let binary = String($0, radix: 2)
10198
let padding = String(repeating: "0", count: 8 - binary.count)
10299
return padding + binary
103100
}.joined()
104101
}
105-
102+
106103
static func generateChecksum(entropyBytes inputData: Data, checksumLength: Int) -> String? {
107104
guard let checksumData = inputData.sha256().bitsInRange(0, checksumLength) else {
108105
return nil
109106
}
110107
let checksum = String(checksumData, radix: 2).leftPadding(toLength: checksumLength, withPad: "0")
111108
return checksum
112109
}
113-
110+
114111
static public func generateMnemonicsFromEntropy(entropy: Data, language: BIP39Language = .english) -> String? {
115112
guard entropy.count >= 16, entropy.count & 4 == 0 else {return nil}
116113
let separator = language.separator
117114
let wordList = generateMnemonicsFrom(entropy: entropy)
118115
return wordList.joined(separator: separator)
119116
}
120-
117+
121118
static public func generateMnemonicsFrom(entropy: Data, language: BIP39Language = .english) -> [String] {
122119
let entropyBitSize = entropy.count * 8
123120
let checksum_length = entropyBitSize / 32
124-
121+
125122
var entropy_bits = bitarray(from: entropy)
126-
123+
127124
guard let checksumTest = generateChecksum(entropyBytes: entropy, checksumLength: checksum_length) else {
128125
return []
129126
}
130127
entropy_bits += checksumTest
131128
return entropy_bits
132129
.split(intoChunksOf: 11)
133130
.compactMap { binary in
134-
Int(binary, radix: 2)
135-
}
136-
.map { index in
137-
language.words[index]
138-
}
131+
Int(binary, radix: 2)
132+
}
133+
.map { index in
134+
language.words[index]
135+
}
139136
}
140-
137+
141138
static public func mnemonicsToEntropy(_ mnemonics: String, language: BIP39Language = .english) -> Data? {
142139
let wordList = mnemonics.components(separatedBy: language.separator)
143140
return mnemonicsToEntropy(wordList, language: language)
144141
}
145-
142+
146143
static public func mnemonicsToEntropy(_ mnemonics: [String], language: BIP39Language = .english) -> Data? {
147144
guard mnemonics.count >= 12 && mnemonics.count.isMultiple(of: 3) && mnemonics.count <= 24 else {return nil}
148145
var bitString = ""
@@ -168,27 +165,27 @@ public class BIP39 {
168165
}
169166
return entropy
170167
}
171-
168+
172169
static public func seedFromMmemonics(_ mnemonics: [String], password: String = "", language: BIP39Language = .english) -> Data? {
173170
let wordList = mnemonics.joined(separator: language.separator)
174171
return seedFromMmemonics(wordList, password: password, language: language)
175172
}
176-
173+
177174
static public func seedFromMmemonics(_ mnemonics: String, password: String = "", language: BIP39Language = .english) -> Data? {
178175
if mnemonicsToEntropy(mnemonics, language: language) == nil {
179176
return nil
180177
}
181178
return dataFrom(mnemonics: mnemonics, password: password)
182179
}
183-
180+
184181
static private func dataFrom(mnemonics: String, password: String) -> Data? {
185182
guard let mnemData = mnemonics.decomposedStringWithCompatibilityMapping.data(using: .utf8) else {return nil}
186183
let salt = "mnemonic" + password
187184
guard let saltData = salt.decomposedStringWithCompatibilityMapping.data(using: .utf8) else {return nil}
188185
guard let seedArray = try? PKCS5.PBKDF2(password: mnemData.bytes, salt: saltData.bytes, iterations: 2048, keyLength: 64, variant: HMAC.Variant.sha2(.sha512)).calculate() else {return nil}
189186
return Data(seedArray)
190187
}
191-
188+
192189
static public func seedFromEntropy(_ entropy: Data, password: String = "", language: BIP39Language = .english) -> Data? {
193190
guard let mnemonics = generateMnemonicsFromEntropy(entropy: entropy, language: language) else {
194191
return nil

0 commit comments

Comments
 (0)