From f66649d87212d5c67def7dad309714d99ecfae2a Mon Sep 17 00:00:00 2001 From: irriden Date: Tue, 12 Sep 2023 18:40:37 +0000 Subject: [PATCH] derive: complain loudly on unexpected input --- signer/src/derive.rs | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/signer/src/derive.rs b/signer/src/derive.rs index 7ed3340..f865d83 100644 --- a/signer/src/derive.rs +++ b/signer/src/derive.rs @@ -24,22 +24,54 @@ pub fn mnemonic_from_entropy(entropy: &[u8]) -> anyhow::Result { pub fn entropy_from_mnemonic(mn: &str) -> anyhow::Result> { let mn = bip39::Mnemonic::parse_normalized(mn) .map_err(|e| anyhow::anyhow!("Mnemonic::parse_normalized failed {:?}", e))?; - let mut e = mn.to_entropy_array().0.to_vec(); - e.resize(ENTROPY_LEN, 0); + match mn.word_count() { + 12 => (), + len => { + return Err(anyhow::anyhow!( + "Mnemonic is length {}, should be 12 words long.", + len + )) + } + } + let e = mn.to_entropy_array().0.to_vec(); + if e.len() != 16 { + return Err(anyhow::anyhow!("Should never happen, 12 words didn't convert to 16 bytes of entropy. Please try again.")); + } Ok(e) } pub fn mnemonic_to_seed(mn: &str) -> anyhow::Result> { let mn = bip39::Mnemonic::parse_normalized(mn) .map_err(|e| anyhow::anyhow!("Mnemonic::parse_normalized failed {:?}", e))?; - // Do like CLN does, chop off the last 32 bytes + match mn.word_count() { + 12 => (), + len => { + return Err(anyhow::anyhow!( + "Mnemonic is length {}, should be 12 words long.", + len + )) + } + } + // BIP39 seed is 64 bytes. Do like CLN does, chop off the last 32 bytes. let e = mn.to_seed_normalized("")[..32].to_vec(); Ok(e) } pub fn entropy_to_seed(entropy: &[u8]) -> anyhow::Result> { + match entropy.len() { + 16 => (), + len => { + return Err(anyhow::anyhow!( + "Entropy is length {}, should be 16 bytes.", + len + )) + } + } let mn = bip39::Mnemonic::from_entropy(entropy) .map_err(|e| anyhow::anyhow!("Mnemonic::from_entropy failed {:?}", e))?; + if mn.word_count() != 12 { + return Err(anyhow::anyhow!("Should never happen, 16 bytes of entropy didn't convert to 12 words. Please try again.")); + } // Do like CLN does, chop off the last 32 bytes let e = mn.to_seed_normalized("")[..32].to_vec(); Ok(e)