add network to config bin and NVS storage

This commit is contained in:
Evan Feenstra
2022-07-01 17:11:23 -07:00
parent 5bb4a990d2
commit c0d2a813af
5 changed files with 36 additions and 31 deletions

View File

@@ -43,6 +43,7 @@ SSID=my_ssid
PASS=my_wifi_password PASS=my_wifi_password
BROKER=my_ip:1883 BROKER=my_ip:1883
SEED=my_seed SEED=my_seed
NETWORK=regtest
``` ```
connect to the `sphinxkey` network on your computer connect to the `sphinxkey` network on your computer

View File

@@ -57,6 +57,7 @@ pub fn config_server(mutex: Arc<(Mutex<Option<Config>>, Condvar)>) -> Result<idf
broker: dto.broker, broker: dto.broker,
ssid: dto.ssid, ssid: dto.ssid,
pass: dto.pass, pass: dto.pass,
network: dto.network,
seed: seed, seed: seed,
}; };
let mut wait = mutex.0.lock().unwrap(); let mut wait = mutex.0.lock().unwrap();

View File

@@ -15,6 +15,7 @@ pub struct Config {
pub ssid: String, pub ssid: String,
pub pass: String, pub pass: String,
pub seed: [u8; 32], pub seed: [u8; 32],
pub network: String,
} }
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConfigDTO { pub struct ConfigDTO {
@@ -23,6 +24,7 @@ pub struct ConfigDTO {
pub pass: String, pub pass: String,
pub pubkey: String, pub pubkey: String,
pub seed: String, // encrypted (56 bytes) pub seed: String, // encrypted (56 bytes)
pub network: String,
} }
/* /*

View File

@@ -3,20 +3,20 @@ mod conn;
mod core; mod core;
mod periph; mod periph;
use crate::core::{events::*, config::*}; use crate::core::{config::*, events::*};
use crate::periph::led::led_control_loop; use crate::periph::led::led_control_loop;
use crate::periph::sd::sd_card; use crate::periph::sd::sd_card;
use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported
use std::thread;
use std::sync::{Arc, mpsc};
use std::time::Duration;
use anyhow::Result; use anyhow::Result;
use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use esp_idf_svc::nvs::*;
use esp_idf_svc::nvs_storage::EspNvsStorage;
use embedded_svc::storage::Storage; use embedded_svc::storage::Storage;
use esp_idf_hal::peripherals::Peripherals; use esp_idf_hal::peripherals::Peripherals;
use esp_idf_svc::nvs::*;
use esp_idf_svc::nvs_storage::EspNvsStorage;
use sphinx_key_signer::lightning_signer::bitcoin::Network; use sphinx_key_signer::lightning_signer::bitcoin::Network;
@@ -26,31 +26,14 @@ const CLIENT_ID: &str = "sphinx-1";
#[cfg(feature = "pingpong")] #[cfg(feature = "pingpong")]
const CLIENT_ID: &str = "test-1"; const CLIENT_ID: &str = "test-1";
const NETWORK: Option<&'static str> = option_env!("NETWORK");
fn main() -> Result<()> { fn main() -> Result<()> {
// Temporary. Will disappear once ESP-IDF 4.4 is released, but for now it is necessary to call this function once, // Temporary. Will disappear once ESP-IDF 4.4 is released, but for now it is necessary to call this function once,
// or else some patches to the runtime implemented by esp-idf-sys might not link properly. // or else some patches to the runtime implemented by esp-idf-sys might not link properly.
esp_idf_sys::link_patches(); esp_idf_sys::link_patches();
let network: Network = if let Some(n) = NETWORK {
match n {
"bitcoin" => Network::Bitcoin,
"mainnet" => Network::Bitcoin,
"testnet" => Network::Testnet,
"signet" => Network::Signet,
"regtest" => Network::Regtest,
_ => Network::Regtest,
}
} else {
Network::Regtest
};
esp_idf_svc::log::EspLogger::initialize_default(); esp_idf_svc::log::EspLogger::initialize_default();
thread::sleep(Duration::from_secs(1)); thread::sleep(Duration::from_secs(1));
log::info!("Network set to {:?}", network);
let peripherals = Peripherals::take().unwrap(); let peripherals = Peripherals::take().unwrap();
let pins = peripherals.pins; let pins = peripherals.pins;
@@ -63,10 +46,14 @@ fn main() -> Result<()> {
sd_card(peripherals.spi2); sd_card(peripherals.spi2);
let default_nvs = Arc::new(EspDefaultNvs::new()?); let default_nvs = Arc::new(EspDefaultNvs::new()?);
let mut store = EspNvsStorage::new_default(default_nvs.clone(), "sphinx", true).expect("no storage"); let mut store =
EspNvsStorage::new_default(default_nvs.clone(), "sphinx", true).expect("no storage");
let existing: Option<Config> = store.get("config").expect("failed"); let existing: Option<Config> = store.get("config").expect("failed");
if let Some(exist) = existing { if let Some(exist) = existing {
println!("=============> START CLIENT NOW <============== {:?}", exist); println!(
"=============> START CLIENT NOW <============== {:?}",
exist
);
// store.remove("config").expect("couldnt remove config"); // store.remove("config").expect("couldnt remove config");
led_tx.send(Status::ConnectingToWifi).unwrap(); led_tx.send(Status::ConnectingToWifi).unwrap();
let _wifi = start_wifi_client(default_nvs.clone(), &exist)?; let _wifi = start_wifi_client(default_nvs.clone(), &exist)?;
@@ -77,17 +64,26 @@ fn main() -> Result<()> {
// _conn needs to stay in scope or its dropped // _conn needs to stay in scope or its dropped
let (mqtt, connection) = conn::mqtt::make_client(&exist.broker, CLIENT_ID)?; let (mqtt, connection) = conn::mqtt::make_client(&exist.broker, CLIENT_ID)?;
let mqtt_client = conn::mqtt::start_listening(mqtt, connection, tx)?; let mqtt_client = conn::mqtt::start_listening(mqtt, connection, tx)?;
// this blocks forever... the "main thread" // this blocks forever... the "main thread"
log::info!(">>>>>>>>>>> blocking forever..."); log::info!(">>>>>>>>>>> blocking forever...");
let do_log = true; let do_log = true;
let network = match exist.network.as_str() {
"bitcoin" => Network::Bitcoin,
"mainnet" => Network::Bitcoin,
"testnet" => Network::Testnet,
"signet" => Network::Signet,
"regtest" => Network::Regtest,
_ => Network::Regtest,
};
log::info!("Network set to {:?}", network);
make_event_loop(mqtt_client, rx, network, do_log, led_tx)?; make_event_loop(mqtt_client, rx, network, do_log, led_tx)?;
} else { } else {
led_tx.send(Status::WifiAccessPoint).unwrap(); led_tx.send(Status::WifiAccessPoint).unwrap();
println!("=============> START SERVER NOW AND WAIT <=============="); println!("=============> START SERVER NOW AND WAIT <==============");
if let Ok((wifi, config)) = start_config_server_and_wait(default_nvs.clone()) { if let Ok((wifi, config)) = start_config_server_and_wait(default_nvs.clone()) {
store.put("config", &config).expect("could not store config"); store
.put("config", &config)
.expect("could not store config");
println!("CONFIG SAVED"); println!("CONFIG SAVED");
drop(wifi); drop(wifi);
thread::sleep(Duration::from_secs(1)); thread::sleep(Duration::from_secs(1));

View File

@@ -22,6 +22,7 @@ pub struct ConfigBody {
pub pass: String, pub pass: String,
pub broker: String, pub broker: String,
pub pubkey: String, // for ecdh pub pubkey: String, // for ecdh
pub network: String,
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConfigResponse { pub struct ConfigResponse {
@@ -37,7 +38,11 @@ async fn main() -> anyhow::Result<()> {
let broker: String = env::var("BROKER").expect("no broker"); let broker: String = env::var("BROKER").expect("no broker");
let seed_string: String = env::var("SEED").expect("no seed"); let seed_string: String = env::var("SEED").expect("no seed");
let seed: [u8; MSG_LEN] = hex::decode(seed_string)?[..MSG_LEN].try_into()?; let seed: [u8; MSG_LEN] = hex::decode(seed_string)?[..MSG_LEN].try_into()?;
println!("seed {:?}", seed); let network: String = env::var("NETWORK").unwrap_or("regtest".to_string());
if !(network == "bitcoin" || network == "mainnet" || network == "testnet" || network == "signet" || network == "regtest") {
panic!("invalid network string");
}
println!("network {:?}", network);
let s = Secp256k1::new(); let s = Secp256k1::new();
let (sk1, pk1) = s.generate_keypair(&mut thread_rng()); let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
@@ -65,7 +70,7 @@ async fn main() -> anyhow::Result<()> {
let cipher_seed = hex::encode(cipher); let cipher_seed = hex::encode(cipher);
let config = ConfigBody { let config = ConfigBody {
seed: cipher_seed, seed: cipher_seed,
ssid, pass, broker, ssid, pass, broker, network,
pubkey: hex::encode(pk1.serialize()), pubkey: hex::encode(pk1.serialize()),
}; };