1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! # fci4096
//!
//! A BIP39-inspired mnemonic wordlist and seed-derivation library built on 4096
//! standard Chinese four-character idioms (*chengyu*). Each idiom encodes 12
//! bits of entropy (2¹² = 4096), delivering higher information density than
//! BIP39's 2048-word list (11 bits/word). The checksum length is 1/8 of the
//! raw entropy.
//!
//! Designed for **offline, local-only** key derivation — no network requests,
//! zero configuration, no third-party cloud services. Runs on native desktop,
//! embedded devices, hardware wallets (`no_std`), and WebAssembly targets. The
//! idiom-based wordlist improves memorability, readability, and backup
//! usability for Chinese-language users while maintaining a self-contained,
//! locally-controlled mnemonic system.
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use fci4096::{generate, IdiomMnemonicSize};
//!
//! // Generate a 12-idiom mnemonic (128 bits of entropy)
//! let mnemonic = generate(IdiomMnemonicSize::Idioms12).unwrap();
//! println!("{}", mnemonic.phrase());
//!
//! // Derive a 64-byte seed via PBKDF2-SHA512
//! let seed = mnemonic.to_seed("my_passphrase");
//! ```
//!
//! ## Core Parameters
//!
//! | Parameter | Value |
//! |-----------|-------|
//! | Wordlist size | 4096 (2¹²) |
//! | Bits per idiom | 12 |
//! | Idiom length | 4 Chinese characters (uniform) |
//! | Checksum ratio | 1/8 of entropy length |
//! | Seed derivation | PBKDF2-HMAC-SHA512 |
//! | Default iterations | 4096 (BIP39 uses 2048) |
//! | Lookup complexity | O(log N) binary search |
//! | Index storage | `Vec<u16>` (2 bytes/idiom) |
//! | Supported entropy | 128 / 160 / 192 / 224 / 256 bits |
//! | Supported word counts | 12 / 15 / 18 / 21 / 24 idioms |
//!
//! ### Entropy & Word Count Mapping
//!
//! | Idioms | Entropy | Checksum | Total Bits |
//! |--------|---------|----------|------------|
//! | 12 | 128 | 16 | 144 |
//! | 15 | 160 | 20 | 180 |
//! | 18 | 192 | 24 | 216 |
//! | 21 | 224 | 28 | 252 |
//! | 24 | 256 | 32 | 288 |
//!
//! ## Feature Flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `std` | Yes | Standard library support |
//! | `rand` | Yes | OS random source for entropy generation (via `getrandom`) |
//! | `serde` | No | `Serialize` / `Deserialize` for [`IdiomMnemonic`] |
//! | `wasm` | No | WebAssembly bindings (auto-enables `rand`) |
//!
//! ## Modules
//!
//! - [`entropy`] — Bit-level encoding/decoding: entropy ↔ idiom indices, SHA-256 checksum.
//! - [`mnemonic`] — Core [`IdiomMnemonic`] type and [`IdiomMnemonicSize`] enum.
//! - [`seed`] — PBKDF2-HMAC-SHA512 seed derivation with NFKD normalization.
//! - [`idiom_list`] — Compile-time validated 4096-idiom wordlist with O(log N) binary search.
//! - [`error`] — Error enum ([`Error`]) and [`Result`] alias.
//!
//! ## Top-level API
//!
//! | Function | Description |
//! |----------|-------------|
//! | [`generate`] | Generate a random mnemonic from OS entropy source |
//! | [`from_entropy`] | Build a mnemonic from raw entropy bytes |
//! | [`from_phrase`] | Parse & validate a space-separated idiom phrase |
//! | [`validate`] | Check phrase validity (wordlist + checksum) |
//! | [`idiom_to_index`] | Binary-search an idiom's index (O(log N)) |
//! | [`index_to_idiom`] | Look up an idiom by index (O(1)) |
//! | [`get_pinyin`] | Get the pinyin of an idiom by index |
//! | [`IDIOM_COUNT`] | Constant: total idiom count (4096) |
//!
//! ## Runtime Characteristics
//!
//! - **Offline**: All operations are local; zero network I/O.
//! - **Lightweight**: No heavy dependencies; core stack is `sha2` + `pbkdf2` + `hmac`.
//! - **`no_std` compatible**: Usable on bare-metal embedded devices and hardware wallets.
//! - **WASM ready**: Enable the `wasm` feature for browser-based key derivation.
//! - **Low latency**: O(log N) idiom lookup via Unicode-codepoint-sorted binary search array.
extern crate std;
extern crate alloc;
/// Bit-level entropy encoding/decoding: entropy ↔ idiom index conversion,
/// SHA-256 checksum calculation, and OS random entropy generation.
/// Error enum ([`Error`]) and [`Result`] type alias for all fallible operations.
/// Compile-time validated 4096-idiom wordlist with O(log N) Unicode-codepoint
/// binary search and pinyin lookup.
/// Core mnemonic types: [`IdiomMnemonic`] and [`IdiomMnemonicSize`].
/// Seed derivation via PBKDF2-HMAC-SHA512 with NFKD Unicode normalization.
/// WebAssembly bindings exposing `generate`, `from_phrase`, `validate`,
/// `phrase`, and `to_seed` to JavaScript (requires the `wasm` feature).
pub use crate;
pub use crateChineseIdiomList;
pub use crate;
pub use cratePBKDF2_ITERATIONS;
/// Generate a cryptographically secure random mnemonic from the OS entropy source.
///
/// Uses the operating system's CSPRNG (via `getrandom`) to produce raw entropy,
/// then appends a SHA-256 checksum and maps the bitstream to idiom indices.
/// Suitable for key creation on desktop, server, embedded (`no_std`), and WASM
/// targets (requires the `rand` feature; on `wasm32` the `getrandom/js` backend
/// is used automatically).
///
/// # Arguments
///
/// * `size` — The mnemonic length variant (12/15/18/21/24 idioms).
///
/// # Errors
///
/// Returns [`Error::InvalidEntropyLength`] if the size maps to an unsupported
/// entropy length, or [`Error::RandError`] if the OS random source fails.
///
/// # Example
///
/// ```rust,no_run
/// use fci4096::{generate, IdiomMnemonicSize};
///
/// let mnemonic = generate(IdiomMnemonicSize::Idioms12).unwrap();
/// assert_eq!(mnemonic.idioms().len(), 12);
/// ```
/// Build a mnemonic from raw entropy bytes.
///
/// Appends a SHA-256 checksum (1/8 of the entropy length) and slices the
/// combined bitstream into 12-bit idiom indices. Suitable for deterministic
/// key derivation from a known entropy source (e.g. hardware RNG, BIP85 child
/// entropy, or pre-seeded test vectors).
///
/// # Arguments
///
/// * `entropy` — Raw entropy bytes. Must be 16/20/24/28/32 bytes
/// (128/160/192/224/256 bits).
///
/// # Errors
///
/// Returns [`Error::InvalidEntropyLength`] if the byte length does not match
/// one of the five supported sizes.
///
/// # Example
///
/// ```rust
/// use fci4096::from_entropy;
///
/// let entropy = [0x00u8; 16]; // 128 bits of entropy
/// let mnemonic = from_entropy(&entropy).unwrap();
/// assert_eq!(mnemonic.idioms().len(), 12);
/// ```
/// Parse and validate a mnemonic from a space-separated idiom phrase.
///
/// Splits the input by half-width spaces, full-width spaces (`\u{3000}`), and
/// tabs, then looks up each idiom via O(log N) binary search. Automatically
/// validates the SHA-256 checksum after parsing. Suitable for restoring a
/// mnemonic from user input, clipboard text, or QR-decoded phrases.
///
/// # Arguments
///
/// * `phrase` — Space-separated idiom string. Full-width spaces and tabs are
/// accepted as delimiters.
///
/// # Errors
///
/// Returns [`Error::InvalidLength`] if the idiom count is not 12/15/18/21/24,
/// [`Error::InvalidIdiom`] if any token is not a four-character idiom in the
/// wordlist, or [`Error::ChecksumMismatch`] if the checksum does not validate.
///
/// # Example
///
/// ```rust
/// use fci4096::{from_entropy, from_phrase};
///
/// let entropy = [0x00u8; 16];
/// let mnemonic = from_entropy(&entropy).unwrap();
/// let phrase = mnemonic.phrase();
/// let recovered = from_phrase(&phrase).unwrap();
/// assert_eq!(mnemonic, recovered);
/// ```
/// Validate a mnemonic phrase without constructing an [`IdiomMnemonic`].
///
/// Checks whether all tokens exist in the 4096-idiom wordlist and the SHA-256
/// checksum matches. Suitable for pre-flight input validation before seed
/// derivation or before prompting the user to confirm a phrase.
///
/// # Arguments
///
/// * `phrase` — Space-separated idiom string (full-width spaces and tabs
/// accepted as delimiters).
///
/// # Returns
///
/// `true` if the phrase is valid (wordlist + checksum), `false` otherwise.
/// This function never panics.
///
/// # Example
///
/// ```rust
/// use fci4096::{generate, validate, IdiomMnemonicSize};
///
/// let mnemonic = generate(IdiomMnemonicSize::Idioms12).unwrap();
/// assert!(validate(&mnemonic.phrase()));
/// assert!(!validate("invalid phrase"));
/// ```
/// Look up an idiom's 0-based index in the wordlist via binary search.
///
/// Uses binary search over a Unicode-codepoint-sorted lookup array compiled at
/// build time. Time complexity O(log N) where N = 4096 (≈ 12 comparisons).
/// Returns `None` immediately for non-four-character input (fast rejection path).
/// Suitable for high-frequency lookup on resource-constrained devices.
///
/// # Arguments
///
/// * `idiom` — A four-character Chinese idiom string.
///
/// # Returns
///
/// `Some(index)` if the idiom exists in the wordlist, `None` otherwise.
/// Index range is `0..4096`.
///
/// # Example
///
/// ```rust
/// use fci4096::{idiom_to_index, index_to_idiom};
///
/// let idiom = index_to_idiom(0).unwrap();
/// if let Some(idx) = idiom_to_index(idiom) {
/// println!("Idiom index: {}", idx);
/// }
/// ```
/// Look up an idiom by its 0-based index (direct array access, O(1)).
///
/// Returns a `&'static str` reference into the compile-time embedded wordlist,
/// with zero heap allocation. Suitable for rendering mnemonic phrases on
/// embedded displays or serializing to external formats.
///
/// # Arguments
///
/// * `idx` — Idiom index, expected range `0..4096`.
///
/// # Returns
///
/// `Some(&'static str)` if the index is valid, `None` if `idx >= 4096`.
///
/// # Example
///
/// ```rust
/// use fci4096::index_to_idiom;
///
/// if let Some(idiom) = index_to_idiom(0) {
/// println!("First idiom in wordlist: {}", idiom);
/// }
/// ```
/// Get the pinyin (romanization) of an idiom by its index.
///
/// Returns a `&'static str` pinyin string compiled from the bundled CSV data
/// at build time. Suitable for input-method integration, text-to-speech, or
/// pronunciation aids in mnemonic backup/recovery UIs.
///
/// # Arguments
///
/// * `idx` — Idiom index, expected range `0..4096`.
///
/// # Returns
///
/// `Some(&'static str)` if the index is valid and pinyin data is available,
/// `None` if `idx >= 4096` or the CSV data file was not present at build time.
///
/// # Example
///
/// ```rust
/// use fci4096::get_pinyin;
///
/// if let Some(pinyin) = get_pinyin(0) {
/// println!("Pinyin: {}", pinyin);
/// }
/// ```
/// Total number of idioms in the wordlist, fixed at 4096 (2¹²).
/// Each idiom encodes 12 bits of entropy.
pub const IDIOM_COUNT: usize = 4096;