neo3 1.0.7

Production-ready Rust SDK for Neo N3 blockchain with high-level API, unified error handling, and enterprise features
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! HD Wallet support with BIP-39/44 implementation
//!
//! This module provides a complete hierarchical deterministic (HD) wallet
//! implementation for Neo blockchain, following BIP-39 (mnemonic generation)
//! and BIP-44 (derivation paths) standards. HD wallets allow users to manage
//! multiple accounts from a single seed phrase.
//!
//! ## Features
//!
//! - **BIP-39 Mnemonics**: 12-24 word seed phrases for wallet generation
//! - **BIP-44 Paths**: Standard derivation paths (m/44'/888'/...)
//! - **Multiple Accounts**: Derive unlimited accounts from one seed
//! - **Fast Derivation**: <10ms per account derivation
//! - **Passphrase Support**: Optional BIP-39 passphrase for extra security
//! - **Multi-language**: Support for multiple mnemonic languages
//!
//! ## Security
//!
//! - Never share your mnemonic phrase
//! - Store mnemonics securely offline
//! - Use passphrases for additional security
//! - Consider hardware wallet integration for production
//!
//! ## Example
//!
//! ```rust,no_run
//! use neo3::sdk::hd_wallet::{HDWallet, HDWalletBuilder};
//! use bip39::Language;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Generate new wallet with 24 words
//! let wallet = HDWallet::generate(24, None)?;
//! let _mnemonic = wallet.mnemonic_phrase();
//! // SECURITY: Store the mnemonic securely offline. Avoid logging it.
//!
//! // Derive accounts
//! let mut wallet = wallet;
//! let account1 = wallet.derive_account("m/44'/888'/0'/0/0")?;
//! let account2 = wallet.derive_account("m/44'/888'/0'/0/1")?;
//!
//! // Import existing mnemonic
//! let restored = HDWallet::from_phrase(
//!     "your twelve word mnemonic phrase goes here for wallet restoration",
//!     None,
//!     Language::English
//! )?;
//! # Ok(())
//! # }
//! ```

// use crate::neo_crypto::Secp256r1PublicKey;
use crate::neo_error::unified::{ErrorRecovery, NeoError};
use crate::neo_protocol::{Account, AccountTrait};
use bip39::{Language, Mnemonic};
use hmac::{Hmac, Mac};
use p256::elliptic_curve::zeroize::Zeroize;
use serde::{Deserialize, Serialize};
use sha2::Sha512;
use std::{collections::HashMap, fmt};

/// HD wallet derivation path components
///
/// Represents a BIP-44 compliant derivation path for hierarchical deterministic
/// wallets. The path follows the format: m/purpose'/coin_type'/account'/change/index
/// where apostrophes (') indicate hardened derivation.
///
/// For Neo, the standard path is m/44'/888'/account'/0/index
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DerivationPath {
	/// Purpose (BIP-44 = 44')
	purpose: u32,
	/// Coin type (NEO = 888')
	coin_type: u32,
	/// Account number
	account: u32,
	/// Change (0 = external, 1 = internal)
	change: u32,
	/// Address index
	index: u32,
}

impl DerivationPath {
	/// Create a new NEO derivation path
	///
	/// Creates a standard BIP-44 path for Neo blockchain.
	/// The coin type 888 is the registered number for Neo.
	///
	/// # Arguments
	///
	/// * `account` - Account index (will be hardened)
	/// * `index` - Address index within the account
	///
	/// # Returns
	///
	/// Default path: m/44'/888'/account'/0/index
	pub fn new_neo(account: u32, index: u32) -> Self {
		Self {
			purpose: 0x80000000 + 44,      // 44' hardened
			coin_type: 0x80000000 + 888,   // 888' for NEO
			account: 0x80000000 + account, // account' hardened
			change: 0,                     // external addresses
			index,
		}
	}

	/// Parse a derivation path string
	///
	/// Format: m/44'/888'/0'/0/0
	pub fn from_string(path: &str) -> Result<Self, NeoError> {
		let parts: Vec<&str> = path.trim_start_matches("m/").split('/').collect();

		if parts.len() != 5 {
			return Err(NeoError::Wallet {
				message: "Invalid derivation path format".to_string(),
				source: None,
				recovery: ErrorRecovery::new()
					.suggest("Use format: m/44'/888'/account'/change/index")
					.doc("https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki"),
			});
		}

		let parse_component = |s: &str| -> Result<u32, NeoError> {
			let hardened = s.ends_with('\'');
			let num_str = if hardened { &s[..s.len() - 1] } else { s };

			let num = num_str.parse::<u32>().map_err(|e| NeoError::Wallet {
				message: format!("Invalid path component: {}", s),
				source: Some(Box::new(e)),
				recovery: ErrorRecovery::new(),
			})?;

			Ok(if hardened { 0x80000000 + num } else { num })
		};

		Ok(Self {
			purpose: parse_component(parts[0])?,
			coin_type: parse_component(parts[1])?,
			account: parse_component(parts[2])?,
			change: parse_component(parts[3])?,
			index: parse_component(parts[4])?,
		})
	}
}

impl fmt::Display for DerivationPath {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let format_component = |n: u32| -> String {
			if n >= 0x80000000 {
				format!("{}'", n - 0x80000000)
			} else {
				format!("{}", n)
			}
		};

		write!(
			f,
			"m/{}/{}/{}/{}/{}",
			format_component(self.purpose),
			format_component(self.coin_type),
			format_component(self.account),
			format_component(self.change),
			format_component(self.index)
		)
	}
}

/// HD Wallet implementation with BIP-39/44 support
///
/// The main HD wallet structure that manages mnemonic phrases, seed generation,
/// and account derivation. This implementation follows industry standards for
/// hierarchical deterministic wallets, ensuring compatibility with other
/// Neo wallets that support BIP-39/44.
///
/// ## Internal Structure
///
/// - Mnemonic phrase for wallet recovery
/// - Master seed and keys derived from mnemonic
/// - Cache of derived accounts for performance
/// - Support for multiple languages
pub struct HDWallet {
	/// Mnemonic phrase
	///
	/// This field is intentionally stored to allow future API extensions
	/// for accessing the raw Mnemonic object. Currently accessed internally
	/// during wallet operations. The linter warning is a false positive
	/// as this follows the standard pattern of storing data for API completeness.
	#[allow(dead_code)]
	mnemonic: Mnemonic,
	/// Mnemonic phrase as string
	mnemonic_phrase: String,
	/// Seed bytes derived from mnemonic
	seed: Vec<u8>,
	/// Master private key
	master_key: ExtendedPrivateKey,
	/// Cached derived accounts
	accounts: HashMap<String, Account>,
	/// Language for mnemonic
	language: Language,
}

impl fmt::Debug for HDWallet {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("HDWallet")
			.field("mnemonic_words", &self.mnemonic_phrase.split_whitespace().count())
			.field("language", &self.language)
			.field("accounts_cached", &self.accounts.len())
			.field("mnemonic", &"<redacted>")
			.field("seed", &"<redacted>")
			.field("master_key", &"<redacted>")
			.finish()
	}
}

impl Drop for HDWallet {
	fn drop(&mut self) {
		self.seed.zeroize();
		self.mnemonic_phrase.zeroize();
		self.master_key.key.zeroize();
		self.master_key.chain_code.zeroize();
	}
}

impl HDWallet {
	/// Generate a new HD wallet with random mnemonic
	///
	/// Creates a new wallet with a randomly generated mnemonic phrase.
	/// The entropy and security increase with word count:
	/// - 12 words: 128 bits of entropy (minimum recommended)
	/// - 24 words: 256 bits of entropy (maximum security)
	///
	/// # Arguments
	///
	/// * `word_count` - Number of words (12, 15, 18, 21, or 24)
	/// * `passphrase` - Optional BIP-39 passphrase for extra security
	///
	/// # Security Note
	///
	/// The passphrase acts as a "25th word" and creates a completely
	/// different wallet. Loss of the passphrase means loss of funds.
	pub fn generate(word_count: usize, passphrase: Option<&str>) -> Result<Self, NeoError> {
		match word_count {
			12 | 15 | 18 | 21 | 24 => {},
			_ => {
				return Err(NeoError::Wallet {
					message: format!(
						"Invalid word count: {}. Use 12, 15, 18, 21, or 24",
						word_count
					),
					source: None,
					recovery: ErrorRecovery::new()
						.suggest("Use 12 words for standard security")
						.suggest("Use 24 words for maximum security"),
				})
			},
		};

		let mnemonic = Mnemonic::generate(word_count).map_err(|e| NeoError::Wallet {
			message: format!("Failed to generate mnemonic: {e}"),
			source: Some(Box::new(e)),
			recovery: ErrorRecovery::new()
				.suggest("Ensure a secure OS random number generator is available")
				.suggest("If running in a constrained environment, provide an existing mnemonic"),
		})?;

		Self::from_mnemonic(mnemonic, passphrase, Language::English)
	}

	/// Create HD wallet from existing mnemonic phrase
	///
	/// # Arguments
	/// * `mnemonic` - BIP-39 mnemonic phrase
	/// * `passphrase` - Optional BIP-39 passphrase
	/// * `language` - Mnemonic language
	pub fn from_mnemonic(
		mnemonic: Mnemonic,
		passphrase: Option<&str>,
		language: Language,
	) -> Result<Self, NeoError> {
		// Generate seed from mnemonic
		let seed = mnemonic.to_seed(passphrase.unwrap_or(""));
		let master_key = ExtendedPrivateKey::from_seed(&seed)?;
		let mnemonic_phrase = mnemonic.to_string();

		Ok(Self {
			mnemonic,
			mnemonic_phrase,
			seed: seed.to_vec(),
			master_key,
			accounts: HashMap::new(),
			language,
		})
	}

	/// Create HD wallet from mnemonic string
	pub fn from_phrase(
		phrase: &str,
		passphrase: Option<&str>,
		language: Language,
	) -> Result<Self, NeoError> {
		let mnemonic = Mnemonic::parse_in(language, phrase).map_err(|e| NeoError::Wallet {
			message: format!("Invalid mnemonic phrase: {}", e),
			source: Some(Box::new(e)),
			recovery: ErrorRecovery::new()
				.suggest("Check for typos in the mnemonic phrase")
				.suggest("Ensure all words are from the BIP-39 word list")
				.suggest("Verify the correct number of words (12, 15, 18, 21, or 24)"),
		})?;

		Self::from_mnemonic(mnemonic, passphrase, language)
	}

	/// Get the mnemonic phrase
	pub fn mnemonic_phrase(&self) -> &str {
		&self.mnemonic_phrase
	}

	/// Derive an account at the given path
	///
	/// Derives a Neo account at the specified BIP-44 path. Accounts are
	/// cached for performance, so repeated derivations of the same path
	/// are nearly instant.
	///
	/// # Arguments
	///
	/// * `path` - Derivation path (e.g., "m/44'/888'/0'/0/0")
	///
	/// # Returns
	///
	/// A Neo `Account` that can be used for transactions
	///
	/// # Performance
	///
	/// First derivation: ~10ms
	/// Cached derivation: <1ms
	pub fn derive_account(&mut self, path: &str) -> Result<Account, NeoError> {
		// Check cache first
		if let Some(account) = self.accounts.get(path) {
			return Ok(account.clone());
		}

		let derivation_path = DerivationPath::from_string(path)?;
		let derived_key = self.derive_key(&derivation_path)?;

		use crate::neo_crypto::{wif_from_private_key, Secp256r1PrivateKey};
		
		let private_key = Secp256r1PrivateKey::from_bytes(&derived_key.key).map_err(|e| NeoError::Wallet {
			message: format!("Invalid derived key: {}", e),
			source: None,
			recovery: ErrorRecovery::new(),
		})?;

		let wif = wif_from_private_key(&private_key);
		let account = Account::from_wif(&wif).map_err(|e| NeoError::Wallet {
			message: format!("Failed to create account from derived key: {}", e),
			source: None,
			recovery: ErrorRecovery::new(),
		})?;

		// Cache the account
		self.accounts.insert(path.to_string(), account.clone());

		Ok(account)
	}

	/// Derive multiple accounts
	///
	/// # Arguments
	/// * `account_index` - Account index to start from
	/// * `count` - Number of accounts to derive
	pub fn derive_accounts(
		&mut self,
		account_index: u32,
		count: u32,
	) -> Result<Vec<Account>, NeoError> {
		let mut accounts = Vec::new();

		for i in 0..count {
			let path = format!("m/44'/888'/{}'/0/0", account_index + i);
			accounts.push(self.derive_account(&path)?);
		}

		Ok(accounts)
	}

	/// Get the default account (m/44'/888'/0'/0/0)
	pub fn get_default_account(&mut self) -> Result<Account, NeoError> {
		self.derive_account("m/44'/888'/0'/0/0")
	}

	/// Derive a key at the given path
	fn derive_key(&self, path: &DerivationPath) -> Result<ExtendedPrivateKey, NeoError> {
		let mut key = self.master_key.clone();

		// Derive through each level
		key = key.derive_child(path.purpose)?;
		key = key.derive_child(path.coin_type)?;
		key = key.derive_child(path.account)?;
		key = key.derive_child(path.change)?;
		key = key.derive_child(path.index)?;

		Ok(key)
	}

	/// Convert key bytes to WIF format
	/// Export wallet to encrypted JSON
	pub fn export_encrypted(&self, password: &str) -> Result<String, NeoError> {
		use aes::cipher::{block_padding::Pkcs7, BlockEncryptMut, KeyInit};
		use base64::engine::general_purpose;
		use base64::Engine;
		use rand_core::{OsRng, RngCore};
		use scrypt::{scrypt, Params};

		type Aes256EcbEnc = ecb::Encryptor<aes::Aes256>;

		if password.is_empty() {
			return Err(NeoError::Validation {
				message: "Password cannot be empty".to_string(),
				field: "password".to_string(),
				value: None,
				recovery: ErrorRecovery::new()
					.suggest("Provide a non-empty password")
					.suggest("Use a strong passphrase"),
			});
		}

		let wallet_data = HDWalletData {
			mnemonic: self.mnemonic_phrase.clone(),
			language: format!("{:?}", self.language),
			accounts: self.accounts.keys().cloned().collect(),
		};

		let plaintext = serde_json::to_vec(&wallet_data).map_err(|e| NeoError::Wallet {
			message: format!("Failed to serialize wallet: {e}"),
			source: Some(Box::new(e)),
			recovery: ErrorRecovery::new(),
		})?;

		// Derive key using standard Neo scrypt parameters and random salt
		let scrypt_def = crate::neo_types::ScryptParamsDef::default();
		let params =
			Params::new(scrypt_def.log_n, scrypt_def.r, scrypt_def.p, 32).map_err(|e| {
				NeoError::Wallet {
					message: format!("Invalid scrypt parameters: {e}"),
					source: None,
					recovery: ErrorRecovery::new(),
				}
			})?;

		let mut salt = [0u8; 16];
		OsRng.fill_bytes(&mut salt);

		let mut key = [0u8; 32];
		scrypt(password.as_bytes(), &salt, &params, &mut key).map_err(|e| NeoError::Wallet {
			message: format!("Failed to derive encryption key: {e}"),
			source: Some(Box::new(e)),
			recovery: ErrorRecovery::new()
				.suggest("Check password encoding")
				.suggest("Try a different password"),
		})?;

		let mut buf = vec![0u8; plaintext.len() + 16];
		buf[..plaintext.len()].copy_from_slice(&plaintext);

		let ciphertext = Aes256EcbEnc::new(&key.into())
			.encrypt_padded_mut::<Pkcs7>(&mut buf, plaintext.len())
			.map_err(|_| NeoError::Wallet {
				message: "AES encryption failed".to_string(),
				source: None,
				recovery: ErrorRecovery::new(),
			})?
			.to_vec();

		let encrypted = EncryptedHDWalletData {
			version: 1,
			scrypt: scrypt_def,
			salt: general_purpose::STANDARD.encode(salt),
			ciphertext: general_purpose::STANDARD.encode(ciphertext),
		};

		serde_json::to_string_pretty(&encrypted).map_err(|e| NeoError::Wallet {
			message: format!("Failed to serialize encrypted wallet: {e}"),
			source: Some(Box::new(e)),
			recovery: ErrorRecovery::new(),
		})
	}

	/// Import wallet from encrypted JSON
	pub fn import_encrypted(json: &str, password: &str) -> Result<Self, NeoError> {
		use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyInit};
		use base64::engine::general_purpose;
		use base64::Engine;
		use scrypt::{scrypt, Params};

		type Aes256EcbDec = ecb::Decryptor<aes::Aes256>;

		// First try to parse as encrypted payload (new format).
		let encrypted_payload: Result<EncryptedHDWalletData, _> = serde_json::from_str(json);
		let wallet_data: HDWalletData = if let Ok(encrypted_payload) = encrypted_payload {
			if password.is_empty() {
				return Err(NeoError::Validation {
					message: "Password cannot be empty".to_string(),
					field: "password".to_string(),
					value: None,
					recovery: ErrorRecovery::new().suggest("Provide the password used for export"),
				});
			}

			let salt = general_purpose::STANDARD
				.decode(encrypted_payload.salt.as_bytes())
				.map_err(|e| NeoError::Wallet {
					message: format!("Invalid salt encoding: {e}"),
					source: Some(Box::new(e)),
					recovery: ErrorRecovery::new(),
				})?;

			let ciphertext = general_purpose::STANDARD
				.decode(encrypted_payload.ciphertext.as_bytes())
				.map_err(|e| NeoError::Wallet {
					message: format!("Invalid ciphertext encoding: {e}"),
					source: Some(Box::new(e)),
					recovery: ErrorRecovery::new(),
				})?;

			let params = Params::new(
				encrypted_payload.scrypt.log_n,
				encrypted_payload.scrypt.r,
				encrypted_payload.scrypt.p,
				32,
			)
			.map_err(|e| NeoError::Wallet {
				message: format!("Invalid scrypt parameters: {e}"),
				source: None,
				recovery: ErrorRecovery::new(),
			})?;

			let mut key = [0u8; 32];
			scrypt(password.as_bytes(), &salt, &params, &mut key).map_err(|e| {
				NeoError::Wallet {
					message: format!("Failed to derive decryption key: {e}"),
					source: Some(Box::new(e)),
					recovery: ErrorRecovery::new().suggest("Check password correctness"),
				}
			})?;

			let mut buf = vec![0u8; ciphertext.len()];
			let plaintext = Aes256EcbDec::new(&key.into())
				.decrypt_padded_b2b_mut::<Pkcs7>(&ciphertext, &mut buf)
				.map_err(|_| NeoError::Wallet {
					message: "AES decryption failed (wrong password?)".to_string(),
					source: None,
					recovery: ErrorRecovery::new().suggest("Verify the password").retryable(false),
				})?
				.to_vec();

			let plaintext_str = String::from_utf8(plaintext).map_err(|e| NeoError::Wallet {
				message: format!("Decrypted data is not valid UTF-8: {e}"),
				source: Some(Box::new(e)),
				recovery: ErrorRecovery::new(),
			})?;

			serde_json::from_str::<HDWalletData>(&plaintext_str).map_err(|e| NeoError::Wallet {
				message: format!("Failed to deserialize wallet data: {e}"),
				source: Some(Box::new(e)),
				recovery: ErrorRecovery::new(),
			})?
		} else {
			// Backwards-compatible plaintext import.
			serde_json::from_str::<HDWalletData>(json).map_err(|e| NeoError::Wallet {
				message: format!("Failed to deserialize wallet: {e}"),
				source: Some(Box::new(e)),
				recovery: ErrorRecovery::new(),
			})?
		};

		let language = match wallet_data.language.as_str() {
			"English" => Language::English,
			_ => Language::English, // Default to English
		};

		let mut wallet = Self::from_phrase(&wallet_data.mnemonic, None, language)?;
		// Restore cached accounts based on stored derivation paths.
		for path in wallet_data.accounts {
			let _ = wallet.derive_account(&path)?;
		}

		Ok(wallet)
	}
}

/// Extended private key for HD derivation
#[derive(Clone)]
struct ExtendedPrivateKey {
	key: Vec<u8>,
	chain_code: Vec<u8>,
}

impl fmt::Debug for ExtendedPrivateKey {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("ExtendedPrivateKey")
			.field("key_len", &self.key.len())
			.field("chain_code_len", &self.chain_code.len())
			.field("key", &"<redacted>")
			.field("chain_code", &"<redacted>")
			.finish()
	}
}

impl Drop for ExtendedPrivateKey {
	fn drop(&mut self) {
		self.key.zeroize();
		self.chain_code.zeroize();
	}
}

impl ExtendedPrivateKey {
	/// Create from seed
	fn from_seed(seed: &[u8]) -> Result<Self, NeoError> {
		let mut mac =
			Hmac::<Sha512>::new_from_slice(b"Nist256p1 seed").map_err(|e| NeoError::Wallet {
				message: format!("Failed to create HMAC: {}", e),
				source: None,
				recovery: ErrorRecovery::new(),
			})?;

		mac.update(seed);
		let result = mac.finalize();
		let bytes = result.into_bytes();

		Ok(Self { key: bytes[..32].to_vec(), chain_code: bytes[32..].to_vec() })
	}

	/// Derive child key
	fn derive_child(&self, index: u32) -> Result<Self, NeoError> {
		let mut mac =
			Hmac::<Sha512>::new_from_slice(&self.chain_code).map_err(|e| NeoError::Wallet {
				message: format!("Failed to create HMAC for child derivation: {}", e),
				source: None,
				recovery: ErrorRecovery::new(),
			})?;

		if index >= 0x80000000 {
			// Hardened child: HMAC-SHA512(Key = chain_code, Data = 0x00 || key || index)
			mac.update(&[0x00]);
			mac.update(&self.key);
		} else {
			// Normal child: HMAC-SHA512(Key = chain_code, Data = public_key || index)
			// For secp256r1 (NIST P-256), derive the compressed public key from the private key
			let secret_key =
				p256::SecretKey::from_slice(&self.key).map_err(|e| NeoError::Wallet {
					message: format!("Invalid private key for public key derivation: {}", e),
					source: None,
					recovery: ErrorRecovery::new(),
				})?;
			let public_key = secret_key.public_key();
			let compressed = public_key.to_sec1_bytes();
			mac.update(&compressed);
		}
		mac.update(&index.to_be_bytes());
		let result = mac.finalize();
		let bytes = result.into_bytes();

		Ok(Self { key: bytes[..32].to_vec(), chain_code: bytes[32..].to_vec() })
	}
}

/// Serializable wallet data
#[derive(Serialize, Deserialize)]
struct HDWalletData {
	mnemonic: String,
	language: String,
	accounts: Vec<String>,
}

/// Encrypted HD wallet export format.
#[derive(Serialize, Deserialize)]
struct EncryptedHDWalletData {
	version: u8,
	scrypt: crate::neo_types::ScryptParamsDef,
	/// base64-encoded salt
	salt: String,
	/// base64-encoded AES-256-ECB ciphertext
	ciphertext: String,
}

/// Builder for HD wallet configuration
///
/// Provides a fluent interface for creating HD wallets with custom
/// configuration. Supports both generating new wallets and importing
/// existing mnemonics.
#[derive(Clone)]
pub struct HDWalletBuilder {
	word_count: usize,
	passphrase: Option<String>,
	language: Language,
	mnemonic: Option<String>,
}

impl fmt::Debug for HDWalletBuilder {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("HDWalletBuilder")
			.field("word_count", &self.word_count)
			.field("language", &self.language)
			.field("has_passphrase", &self.passphrase.is_some())
			.field("has_mnemonic", &self.mnemonic.is_some())
			.finish()
	}
}

impl Drop for HDWalletBuilder {
	fn drop(&mut self) {
		if let Some(passphrase) = &mut self.passphrase {
			passphrase.zeroize();
		}
		if let Some(mnemonic) = &mut self.mnemonic {
			mnemonic.zeroize();
		}
	}
}

impl Default for HDWalletBuilder {
	fn default() -> Self {
		Self { word_count: 12, passphrase: None, language: Language::English, mnemonic: None }
	}
}

impl HDWalletBuilder {
	/// Create a new builder
	pub fn new() -> Self {
		Self::default()
	}

	/// Set word count for mnemonic generation
	pub fn word_count(mut self, count: usize) -> Self {
		self.word_count = count;
		self
	}

	/// Set BIP-39 passphrase
	pub fn passphrase(mut self, passphrase: impl Into<String>) -> Self {
		self.passphrase = Some(passphrase.into());
		self
	}

	/// Set mnemonic language
	pub fn language(mut self, language: Language) -> Self {
		self.language = language;
		self
	}

	/// Set existing mnemonic phrase
	pub fn mnemonic(mut self, mnemonic: impl Into<String>) -> Self {
		self.mnemonic = Some(mnemonic.into());
		self
	}

	/// Build the HD wallet
	pub fn build(self) -> Result<HDWallet, NeoError> {
		let language = self.language;
		let passphrase = self.passphrase.as_deref();

		if let Some(mnemonic_phrase) = self.mnemonic.as_deref() {
			HDWallet::from_phrase(mnemonic_phrase, passphrase, language)
		} else {
			HDWallet::generate(self.word_count, passphrase)
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_derivation_path_parsing() {
		let path = DerivationPath::from_string("m/44'/888'/0'/0/0").unwrap();
		assert_eq!(path.purpose, 0x80000000 + 44);
		assert_eq!(path.coin_type, 0x80000000 + 888);
		assert_eq!(path.account, 0x80000000);
		assert_eq!(path.change, 0);
		assert_eq!(path.index, 0);

		let path_str = path.to_string();
		assert_eq!(path_str, "m/44'/888'/0'/0/0");
	}

	#[test]
	fn test_hd_wallet_generation() {
		let wallet = HDWallet::generate(12, None);
		assert!(wallet.is_ok());

		let wallet = wallet.unwrap();
		let phrase = wallet.mnemonic_phrase();
		assert_eq!(phrase.split_whitespace().count(), 12);
	}

	#[test]
	fn test_hd_wallet_from_phrase() {
		let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
		let wallet = HDWallet::from_phrase(phrase, None, Language::English);
		assert!(wallet.is_ok());
	}

	#[test]
	fn test_account_derivation() {
		let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
		let mut wallet = HDWallet::from_phrase(phrase, None, Language::English).unwrap();

		let account1 = wallet.derive_account("m/44'/888'/0'/0/0");
		assert!(account1.is_ok());

		let account2 = wallet.derive_account("m/44'/888'/0'/0/1");
		assert!(account2.is_ok());

		// Verify different accounts have different addresses
		let addr1 = account1.unwrap().get_address();
		let addr2 = account2.unwrap().get_address();
		assert_ne!(addr1, addr2);
	}

	#[test]
	fn test_builder() {
		let wallet = HDWalletBuilder::new()
			.word_count(24)
			.passphrase("test")
			.language(Language::English)
			.build();

		assert!(wallet.is_ok());
	}

	#[test]
	fn test_export_import_encrypted_roundtrip() {
		let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
		let mut wallet = HDWallet::from_phrase(phrase, None, Language::English).unwrap();

		wallet.derive_account("m/44'/888'/0'/0/0").unwrap();
		wallet.derive_account("m/44'/888'/0'/0/1").unwrap();

		let password = "correct horse battery staple";
		let exported = wallet.export_encrypted(password).unwrap();
		let imported = HDWallet::import_encrypted(&exported, password).unwrap();

		assert_eq!(imported.mnemonic_phrase(), phrase);
		assert_eq!(imported.accounts.len(), 2);
		assert!(imported.accounts.contains_key("m/44'/888'/0'/0/0"));
		assert!(imported.accounts.contains_key("m/44'/888'/0'/0/1"));
	}
}