Skip to content

Commit 5121cad

Browse files
authored
Merge pull request #113 from tnull/2023-05-expose-mnemonic-generation
Expose BIP39 Mnemonic generation in bindings
2 parents 56fe49c + 291e9fe commit 5121cad

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

bindings/ldk_node.udl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
namespace ldk_node {
2+
Mnemonic generate_entropy_mnemonic();
23
};
34

45
dictionary Config {

src/io/utils.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParam
1212
use lightning::util::logger::Logger;
1313
use lightning::util::ser::{Readable, ReadableArgs, Writeable};
1414

15+
use bip39::Mnemonic;
1516
use bitcoin::hash_types::{BlockHash, Txid};
1617
use bitcoin::hashes::hex::FromHex;
1718
use rand::{thread_rng, RngCore};
@@ -24,6 +25,20 @@ use std::sync::Arc;
2425

2526
use super::KVStore;
2627

28+
/// Generates a random [BIP 39] mnemonic.
29+
///
30+
/// The result may be used to initialize the [`Node`] entropy, i.e., can be given to
31+
/// [`Builder::set_entropy_bip39_mnemonic`].
32+
///
33+
/// [BIP 39]: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
34+
/// [`Builder::set_entropy_bip39_mnemonic`]: crate::Builder::set_entropy_bip39_mnemonic
35+
pub fn generate_entropy_mnemonic() -> Mnemonic {
36+
// bip39::Mnemonic supports 256 bit entropy max
37+
let mut entropy = [0; 32];
38+
thread_rng().fill_bytes(&mut entropy);
39+
Mnemonic::from_entropy(&entropy).unwrap()
40+
}
41+
2742
pub(crate) fn read_or_generate_seed_file(keys_seed_path: &str) -> [u8; WALLET_KEYS_SEED_LEN] {
2843
if Path::new(&keys_seed_path).exists() {
2944
let seed = fs::read(keys_seed_path).expect("Failed to read keys seed file");
@@ -263,3 +278,16 @@ where
263278
Error::PersistenceFailed
264279
})
265280
}
281+
282+
#[cfg(test)]
283+
mod tests {
284+
use super::*;
285+
286+
#[test]
287+
fn mnemonic_to_entropy_to_mnemonic() {
288+
let mnemonic = generate_entropy_mnemonic();
289+
290+
let entropy = mnemonic.to_entropy();
291+
assert_eq!(mnemonic, Mnemonic::from_entropy(&entropy).unwrap());
292+
}
293+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ use error::Error;
105105
pub use event::Event;
106106
pub use types::NetAddress;
107107

108+
pub use io::utils::generate_entropy_mnemonic;
109+
108110
#[cfg(feature = "uniffi")]
109111
use {bitcoin::OutPoint, lightning::ln::PaymentSecret, uniffi_types::*};
110112

0 commit comments

Comments
 (0)