Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraCore/HD/BIP39.swift8// Module : Qyvora Core9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import QyvoraSymmetric4445/// BIP-39 mnemonic sentences (English word list).46public enum BIP39 {47 public enum Error: Swift.Error, Equatable {48 case invalidEntropyLength49 case invalidWordCount50 case unknownWord(position: Int)51 case invalidChecksum52 }5354 public static var wordList: [String] { BIP39English.words }5556 private static let index: [String: Int] = {57 var d = [String: Int](minimumCapacity: 2048)58 for (i, w) in BIP39English.words.enumerated() { d[w] = i }59 return d60 }()6162 /// A new sentence from system randomness: 24 words (256 bits) by default.63 public static func generate(wordCount: Int = 24) throws -> [String] {64 guard [12, 15, 18, 21, 24].contains(wordCount) else { throw Error.invalidWordCount }65 var entropy = SystemRandom.bytes(wordCount / 3 * 4)66 defer { SecureMemory.zero(&entropy) }67 return try mnemonic(entropy: entropy)68 }6970 /// Entropy (16, 20, 24, 28 or 32 bytes) → words.71 public static func mnemonic(entropy: Bytes) throws -> [String] {72 guard [16, 20, 24, 28, 32].contains(entropy.count) else { throw Error.invalidEntropyLength }73 let checksumBits = entropy.count / 474 let hash = SHA256.hash(entropy)75 var bits = [UInt8]()76 bits.reserveCapacity(entropy.count * 8 + checksumBits)77 for b in entropy { for i in (0..<8).reversed() { bits.append((b >> UInt8(i)) & 1) } }78 for i in 0..<checksumBits { bits.append((hash[i / 8] >> UInt8(7 - i % 8)) & 1) }79 var words = [String]()80 for w in 0..<(bits.count / 11) {81 var v = 082 for i in 0..<11 { v = v << 1 | Int(bits[w * 11 + i]) }83 words.append(BIP39English.words[v])84 }85 SecureMemory.zero(&bits)86 return words87 }8889 /// Words → entropy, with word and checksum validation.90 public static func entropy(mnemonic words: [String]) throws -> Bytes {91 guard [12, 15, 18, 21, 24].contains(words.count) else { throw Error.invalidWordCount }92 var bits = [UInt8]()93 bits.reserveCapacity(words.count * 11)94 for (position, w) in words.enumerated() {95 guard let v = index[w] else { throw Error.unknownWord(position: position) }96 for i in (0..<11).reversed() { bits.append(UInt8((v >> i) & 1)) }97 }98 let entropyBits = words.count * 11 * 32 / 3399 var entropy = Bytes(repeating: 0, count: entropyBits / 8)100 for i in 0..<entropyBits { entropy[i / 8] |= bits[i] << UInt8(7 - i % 8) }101 let hash = SHA256.hash(entropy)102 for i in 0..<(bits.count - entropyBits) {103 guard bits[entropyBits + i] == (hash[i / 8] >> UInt8(7 - i % 8)) & 1 else {104 SecureMemory.zero(&entropy)105 throw Error.invalidChecksum106 }107 }108 SecureMemory.zero(&bits)109 return entropy110 }111112 /// Splits user input into normalized words (NFKD, lower case, any white space).113 public static func words(from text: String) -> [String] {114 text.decomposedStringWithCompatibilityMapping.lowercased()115 .split(whereSeparator: { $0.isWhitespace }).map(String.init)116 }117118 public static func isValid(_ words: [String]) -> Bool {119 (try? entropy(mnemonic: words)) != nil120 }121122 /// The same seed from bytes, without building a `String` of the phrase (QYV-CRY-003: a `String` cannot be erased).123 ///124 /// - `normalizedMnemonic`: the words in lower case separated by single spaces, NFKD, UTF-8 — the form in which the125 /// wallet stores the phrase in its vault. It is NOT validated here (word list, checksum): the caller vouches for126 /// it, as the wallet does for a phrase it validated when it was created or imported.127 /// - `normalizedPassphrase`: the BIP-39 passphrase, NFKD, UTF-8 (empty for none).128 public static func seed(normalizedMnemonic: Bytes, normalizedPassphrase: Bytes = []) -> Bytes {129 let dit = DataIndependentTiming.enable()130 defer { DataIndependentTiming.restore(dit) }131 var salt = Bytes("mnemonic".utf8) + normalizedPassphrase132 defer { SecureMemory.zero(&salt) }133 return PBKDF2<SHA512>.deriveKey(password: normalizedMnemonic, salt: salt, iterations: 2048, length: 64)134 }135136 /// 64-byte seed: PBKDF2-HMAC-SHA512(sentence, "mnemonic" ‖ passphrase, 2048 iterations). The sentence must be valid.137 public static func seed(mnemonic words: [String], passphrase: String = "") throws -> Bytes {138 let dit = DataIndependentTiming.enable()139 defer { DataIndependentTiming.restore(dit) }140 var e = try entropy(mnemonic: words)141 SecureMemory.zero(&e)142 var password = Bytes(words.joined(separator: " ").decomposedStringWithCompatibilityMapping.utf8)143 defer { SecureMemory.zero(&password) }144 let salt = Bytes(("mnemonic" + passphrase).decomposedStringWithCompatibilityMapping.utf8)145 return PBKDF2<SHA512>.deriveKey(password: password, salt: salt, iterations: 2048, length: 64)146 }147}148