Merge pull request #77 from stakwork/update-deps

Update deps
This commit is contained in:
Evan Feenstra
2023-04-03 14:32:12 -07:00
committed by GitHub
19 changed files with 1602 additions and 891 deletions

View File

@@ -8,6 +8,14 @@ A Lightning Hardware Wallet based on [Validating Lightning Signer](https://gitla
`cargo build --release`
Find your port (`ls /dev/tty.*`)
`PORT=/dev/tty.usbserial-1420`
`espflash $PORT target/riscv32imc-esp-espidf/release/sphinx-key-factory`
`esptool.py --chip esp32c3 elf2image target/riscv32imc-esp-espidf/release/sphinx-key-factory`
### build
`cd ../sphinx-key`
@@ -24,10 +32,6 @@ The wifi SSID and password needs to be in env to build the firmware. SSID must b
`esptool.py --chip esp32c3 elf2image target/riscv32imc-esp-espidf/release/sphinx-key`
Find your port (`ls /dev/tty.*`)
`PORT=/dev/tty.usbserial-1420`
`esptool.py --chip esp32c3 -p $PORT -b 460800 --before=default_reset --after=hard_reset write_flash --flash_mode dio --flash_freq 40m --flash_size 4MB 0x10000 target/riscv32imc-esp-espidf/release/sphinx-key.bin`
### monitor
@@ -36,7 +40,7 @@ Find your port (`ls /dev/tty.*`)
### configure the hardware
make a seed: `./newseed.sh`
make a seed: `./newseed.sh`
make a `.env` file like:
@@ -113,4 +117,4 @@ nightly
`espmonitor /dev/tty.usbserial-1420`
for ESP-IDF#4.3.2: `export CC=$PWD/.embuild/espressif/tools/riscv32-esp-elf/esp-2021r2-8.4.0/riscv32-esp-elf/bin/riscv32-esp-elf-gcc`
for ESP-IDF#4.3.2: `export CC=$PWD/.embuild/espressif/tools/riscv32-esp-elf/esp-2021r2-8.4.0/riscv32-esp-elf/bin/riscv32-esp-elf-gcc`

875
factory/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,11 +8,11 @@ edition = "2021"
pio = ["esp-idf-sys/pio"]
[dependencies]
esp-idf-sys = { version = "0.31.8", features = ["binstart"] }
esp-idf-svc = { version = "0.42.3", features = ["experimental", "alloc"] }
esp-idf-hal = "0.38.1"
esp-idf-sys = { version = "0.32.1", features = ["binstart"] }
esp-idf-svc = { version = "0.45.0", features = ["experimental", "alloc"] }
esp-idf-hal = "0.40.1"
embedded-svc = "0.24.0"
embedded-hal = "0.2.7"
embedded-svc = "0.22.1"
anyhow = { version = "1.0.65", features = ["backtrace"] }
rand = "0.8.5"
log = "0.4.17"

View File

@@ -1,33 +1,35 @@
use embedded_hal::blocking::delay::DelayMs;
use esp_idf_hal::delay::Ets;
use esp_idf_hal::delay::FreeRtos;
use esp_idf_hal::peripherals::Peripherals;
use esp_idf_hal::rmt::config::TransmitConfig;
use esp_idf_hal::rmt::{FixedLengthSignal, PinState, Pulse, Transmit};
use esp_idf_hal::rmt::*;
use std::time::Duration;
pub fn set_ota_led() {
pub fn set_ota_led() -> anyhow::Result<()> {
let peripherals = Peripherals::take().unwrap();
let led = peripherals.pins.gpio0.into_output().unwrap();
let led = peripherals.pins.gpio0;
let channel = peripherals.rmt.channel0;
let config = TransmitConfig::new().clock_divider(1);
let mut tx = Transmit::new(led, channel, &config).unwrap();
let mut tx = TxRmtDriver::new(channel, led, &config).unwrap();
let rgb = 0xffa500; // Orange
neopixel(
RGB {
r: 255,
g: 55,
b: 00,
},
&mut tx,
)?;
FreeRtos::delay_ms(10);
let ticks_hz = tx.counter_clock().unwrap();
let t0h = Pulse::new_with_duration(ticks_hz, PinState::High, &ns(350)).unwrap();
let t0l = Pulse::new_with_duration(ticks_hz, PinState::Low, &ns(800)).unwrap();
let t1h = Pulse::new_with_duration(ticks_hz, PinState::High, &ns(700)).unwrap();
let t1l = Pulse::new_with_duration(ticks_hz, PinState::Low, &ns(600)).unwrap();
Ok(())
}
let mut signal = FixedLengthSignal::<24>::new();
for i in 0..24 {
let bit = 2_u32.pow(i) & rotate_rgb(rgb) != 0;
let (high_pulse, low_pulse) = if bit { (t1h, t1l) } else { (t0h, t0l) };
signal.set(i as usize, &(high_pulse, low_pulse)).unwrap();
}
tx.start_blocking(&signal).unwrap();
Ets.delay_ms(10u8);
struct RGB {
r: u8,
g: u8,
b: u8,
}
fn ns(nanos: u64) -> Duration {
@@ -39,3 +41,26 @@ fn rotate_rgb(rgb: u32) -> u32 {
let blue = (rgb & b_mask) << 16;
blue | (rgb >> 8)
}
fn neopixel(rgb: RGB, tx: &mut TxRmtDriver) -> anyhow::Result<()> {
// e.g. rgb: (1,2,4)
// G R B
// 7 0 7 0 7 0
// 00000010 00000001 00000100
let color: u32 = ((rgb.g as u32) << 16) | ((rgb.r as u32) << 8) | rgb.b as u32;
let ticks_hz = tx.counter_clock()?;
let t0h = Pulse::new_with_duration(ticks_hz, PinState::High, &ns(350))?;
let t0l = Pulse::new_with_duration(ticks_hz, PinState::Low, &ns(800))?;
let t1h = Pulse::new_with_duration(ticks_hz, PinState::High, &ns(700))?;
let t1l = Pulse::new_with_duration(ticks_hz, PinState::Low, &ns(600))?;
let mut signal = FixedLengthSignal::<24>::new();
for i in (0..24).rev() {
let p = 2_u32.pow(i);
let bit = p & color != 0;
let (high_pulse, low_pulse) = if bit { (t1h, t1l) } else { (t0h, t0l) };
signal.set(23 - i as usize, &(high_pulse, low_pulse))?;
}
tx.start_blocking(&signal)?;
Ok(())
}

View File

@@ -1,5 +1,5 @@
use bitflags::bitflags;
use esp_idf_sys::c_types::c_char;
use core::ffi::c_char;
use esp_idf_sys::{
esp, esp_vfs_fat_sdmmc_mount_config_t, esp_vfs_fat_sdspi_mount, gpio_num_t, sdmmc_card_t,
sdmmc_host_t, sdspi_device_config_t, spi_bus_config_t, spi_bus_initialize, spi_host_device_t,

1117
sphinx-key/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -20,14 +20,14 @@ pingpong = []
no_persist = []
[dependencies]
bitflags = "1.3.2"
esp-idf-sys = { version = "0.31.6", features = ["binstart"] }
sphinx-signer = { git = "https://github.com/stakwork/sphinx-rs.git", optional = true }
sphinx-crypter = { git = "https://github.com/stakwork/sphinx-rs.git" }
embedded-svc = "0.22.1"
esp-idf-svc = { version = "0.42.1", features = ["experimental", "alloc"] }
esp-idf-hal = "0.38.0"
embedded-hal = "=1.0.0-alpha.8"
bitflags = "1.3.2"
esp-idf-sys = { version = "0.32.1", features = ["binstart"] }
embedded-svc = "0.24.0"
esp-idf-svc = { version = "0.45.0", features = ["experimental", "alloc"] }
esp-idf-hal = "0.40.1"
embedded-hal = "=1.0.0-alpha.9"
anyhow = {version = "1", features = ["backtrace"]}
log = "0.4"
url = "2"

View File

@@ -1,15 +1,13 @@
use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported
use embedded_svc::storage::StorageBase;
// use embedded_svc::storage::StorageBase;
use esp_idf_svc::nvs::EspNvs;
use esp_idf_svc::nvs::*;
use esp_idf_svc::nvs_storage::EspNvsStorage;
use std::sync::Arc;
fn main() -> anyhow::Result<()> {
let default_nvs = Arc::new(EspDefaultNvs::new()?);
let mut store =
EspNvsStorage::new_default(default_nvs.clone(), "sphinx", true).expect("no storage");
// NvsDefault::new();
let default_nvs = EspDefaultNvsPartition::take()?;
let mut store = EspNvs::new(default_nvs.clone(), "sphinx", true).expect("no storage");
store.remove("config").expect("couldnt remove config 1");
store.remove("seed").expect("couldnt remove seed 1");
store.remove("nonce").expect("couldnt remove nonce 1");

View File

@@ -4,8 +4,12 @@ use sphinx_signer::sphinx_glyph::control::Config;
use serde::Deserialize;
use std::sync::{Arc, Condvar, Mutex};
// use embedded_svc::http::server::registry::Registry;
// use embedded_svc::http::server::*;
#[allow(deprecated)]
use embedded_svc::httpd::registry::Registry;
use embedded_svc::httpd::*;
use embedded_svc::httpd::Result;
use esp_idf_svc::httpd as idf;
#[derive(Clone, Debug, Deserialize)]
@@ -17,7 +21,7 @@ pub struct Params {
pub config: String,
}
#[allow(unused_variables)]
#[allow(unused_variables, deprecated)]
pub fn config_server(
mutex: Arc<(Mutex<Option<(Config, [u8; 32])>>, Condvar)>,
) -> Result<idf::Server> {

View File

@@ -2,10 +2,10 @@ use crate::core::events::Event as CoreEvent;
use sphinx_signer::sphinx_glyph::topics;
use anyhow::Result;
use embedded_svc::mqtt::client::utils::ConnState;
use embedded_svc::mqtt::client::utils::Connection as MqttConnection;
use embedded_svc::mqtt::client::{Connection, Event, Message as MqttMessage, MessageImpl, QoS};
use esp_idf_hal::mutex::Condvar;
use embedded_svc::utils::mqtt::client::ConnState;
// use embedded_svc::utils::mqtt::client::Connection as MqttConnection;
// use embedded_svc::utils::mutex::Condvar;
use esp_idf_svc::mqtt::client::*;
use esp_idf_sys::EspError;
use esp_idf_sys::{self};
@@ -20,10 +20,8 @@ pub fn make_client(
client_id: &str,
username: &str,
password: &str,
) -> Result<(
EspMqttClient<ConnState<MessageImpl, EspError>>,
MqttConnection<Condvar, MessageImpl, EspError>,
)> {
tx: mpsc::Sender<CoreEvent>,
) -> Result<EspMqttClient<ConnState<MessageImpl, EspError>>> {
log::info!("make_client with id {}", client_id);
let conf = MqttClientConfiguration {
client_id: Some(client_id),
@@ -37,20 +35,11 @@ pub fn make_client(
};
let b = format!("mqtt://{}", broker);
// let (mut client, mut connection) = EspMqttClient::new_with_conn(b, &conf)?;
let cc = EspMqttClient::new_with_conn(b, &conf)?;
let (client, mut connection) = EspMqttClient::new_with_conn(b, &conf)?;
// let cc = EspMqttClient::new_with_conn(b, &conf)?;
info!("MQTT client started");
Ok(cc)
}
pub fn start_listening(
client: EspMqttClient<ConnState<MessageImpl, EspError>>,
mut connection: MqttConnection<Condvar, MessageImpl, EspError>,
tx: mpsc::Sender<CoreEvent>,
) -> Result<EspMqttClient<ConnState<MessageImpl, EspError>>> {
// must start pumping before subscribe or publish will not work
thread::spawn(move || {
info!("MQTT Listening for messages");
loop {
@@ -104,3 +93,63 @@ pub fn start_listening(
Ok(client)
}
// pub fn start_listening(
// client: EspMqttClient<ConnState<MessageImpl, EspError>>,
// mut connection: MqttConnection<Condvar, MessageImpl, EspError>,
// tx: mpsc::Sender<CoreEvent>,
// ) -> Result<EspMqttClient<ConnState<MessageImpl, EspError>>> {
// // must start pumping before subscribe or publish will not work
// thread::spawn(move || {
// info!("MQTT Listening for messages");
// loop {
// match connection.next() {
// Some(msg) => match msg {
// Err(e) => match e.to_string().as_ref() {
// "ESP_FAIL" => {
// error!("ESP_FAIL msg!");
// }
// _ => error!("Unknown error: {}", e),
// },
// Ok(msg) => match msg {
// Event::BeforeConnect => info!("RECEIVED BeforeConnect MESSAGE"),
// Event::Connected(_flag) => {
// info!("RECEIVED Connected MESSAGE");
// tx.send(CoreEvent::Connected)
// .expect("couldnt send Event::Connected");
// }
// Event::Disconnected => {
// warn!("RECEIVED Disconnected MESSAGE");
// tx.send(CoreEvent::Disconnected)
// .expect("couldnt send Event::Disconnected");
// }
// Event::Subscribed(_mes_id) => info!("RECEIVED Subscribed MESSAGE"),
// Event::Unsubscribed(_mes_id) => info!("RECEIVED Unsubscribed MESSAGE"),
// Event::Published(_mes_id) => info!("RECEIVED Published MESSAGE"),
// Event::Received(msg) => {
// let topic_opt = msg.topic();
// if let Some(topic) = topic_opt {
// match topic {
// topics::VLS => tx
// .send(CoreEvent::VlsMessage(msg.data().to_vec()))
// .expect("couldnt send Event::VlsMessage"),
// topics::CONTROL => tx
// .send(CoreEvent::Control(msg.data().to_vec()))
// .expect("couldnt send Event::Control"),
// _ => log::warn!("unrecognized topic {}", topic),
// };
// } else {
// log::warn!("empty topic in msg!!!");
// }
// }
// Event::Deleted(_mes_id) => info!("RECEIVED Deleted MESSAGE"),
// },
// },
// None => break,
// }
// }
// //info!("MQTT connection loop exit");
// });
// Ok(client)
// }

View File

@@ -5,9 +5,12 @@ use std::time::Duration;
pub fn sync_time() {
let sntp = EspSntp::new_default().unwrap();
println!("SNTP initialized");
while sntp.get_sync_status() != Completed {
println!("Waiting for sntp sync...");
loop {
let status = sntp.get_sync_status();
println!("SNTP status {:?}", status);
if status == Completed {
break;
}
thread::sleep(Duration::from_secs(1));
}
}

View File

@@ -1,27 +1,35 @@
use sphinx_signer::sphinx_glyph::control::Config;
use esp_idf_svc::netif::*;
use esp_idf_svc::nvs::EspDefaultNvs;
use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::ping;
use esp_idf_svc::sysloop::*;
// use esp_idf_svc::sysloop::*;
use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::wifi::*;
use embedded_svc::httpd::Result;
use embedded_svc::ipv4;
use embedded_svc::ping::Ping;
use embedded_svc::wifi::Wifi;
// use embedded_svc::ping::Ping;
// use embedded_svc::wifi::Wifi;
use embedded_svc::wifi::*;
use esp_idf_hal::peripheral;
use log::*;
use std::sync::Arc;
use std::thread;
// use std::thread;
use std::time::Duration;
pub fn start_client(default_nvs: Arc<EspDefaultNvs>, config: &Config) -> Result<Box<EspWifi>> {
let netif_stack = Arc::new(EspNetifStack::new()?);
let sys_loop_stack = Arc::new(EspSysLoopStack::new()?);
pub fn start_client(
modem: impl peripheral::Peripheral<P = esp_idf_hal::modem::Modem> + 'static,
default_nvs: EspDefaultNvsPartition,
config: &Config,
) -> Result<Box<EspWifi<'static>>> {
// let netif_stack = Arc::new(EspNetifStack::new()?);
// let sys_loop_stack = Arc::new(EspSysLoopStack::new()?);
let mut wifi = Box::new(EspWifi::new(netif_stack, sys_loop_stack, default_nvs)?);
let sysloop = EspSystemEventLoop::take()?;
let mut wifi = Box::new(EspWifi::new(modem, sysloop.clone(), Some(default_nvs))?);
let ap_infos = wifi.scan()?;
let ssid = config.ssid.as_str();
let pass = config.pass.as_str();
@@ -48,41 +56,70 @@ pub fn start_client(default_nvs: Arc<EspDefaultNvs>, config: &Config) -> Result<
..Default::default()
}))?;
info!("...Wifi client configuration set, get status");
match wifi.wait_status_with_timeout(Duration::from_secs(20), |status| !status.is_transitional())
{
Ok(_) => (),
Err(e) => warn!("Unexpected Wifi status: {:?}", e),
};
wifi.start()?;
let status = wifi.get_status();
println!("=> wifi STATUS {:?}", status);
println!("=> is transitional? {:?}", status.is_transitional());
if let Status(
ClientStatus::Started(ClientConnectionStatus::Connected(ClientIpStatus::Done(ip_settings))),
ApStatus::Stopped,
) = status
info!("...Wifi client configuration set, get status");
// match wifi.wait_status_with_timeout(Duration::from_secs(20), |status| !status.is_transitional())
// {
// Ok(_) => (),
// Err(e) => warn!("Unexpected Wifi status: {:?}", e),
// };
if !WifiWait::new(&sysloop)?
.wait_with_timeout(Duration::from_secs(20), || wifi.is_started().unwrap())
{
info!("Wifi started!");
ping(&ip_settings)?;
} else {
thread::sleep(Duration::from_secs(13));
// bail!("Unexpected Client Wifi status: {:?}", status);
return Err(anyhow::anyhow!(
"Unexpected Client Wifi status: {:?}",
status
));
warn!("Wifi did not start");
}
info!("Connecting wifi...");
wifi.connect()?;
if !EspNetifWait::new::<EspNetif>(wifi.sta_netif(), &sysloop)?.wait_with_timeout(
Duration::from_secs(20),
|| {
wifi.is_connected().unwrap()
&& wifi.sta_netif().get_ip_info().unwrap().ip != std::net::Ipv4Addr::new(0, 0, 0, 0)
},
) {
warn!("Wifi did not connect or did not receive a DHCP lease");
}
let ip_info = wifi.sta_netif().get_ip_info()?;
info!("Wifi DHCP info: {:?}", ip_info);
// let status = wifi.get_status();
// println!("=> wifi STATUS {:?}", status);
// println!("=> is transitional? {:?}", status.is_transitional());
// if let Status(
// ClientStatus::Started(ClientConnectionStatus::Connected(ClientIpStatus::Done(ip_settings))),
// ApStatus::Stopped,
// ) = status
// {
// info!("Wifi started!");
// ping(&ip_settings)?;
// } else {
// thread::sleep(Duration::from_secs(13));
// // bail!("Unexpected Client Wifi status: {:?}", status);
// return Err(anyhow::anyhow!(
// "Unexpected Client Wifi status: {:?}",
// status
// ));
// }
info!("wifi::start_client Ok(())");
Ok(wifi)
}
pub fn start_access_point(default_nvs: Arc<EspDefaultNvs>) -> Result<Box<EspWifi>> {
let netif_stack = Arc::new(EspNetifStack::new()?);
let sys_loop_stack = Arc::new(EspSysLoopStack::new()?);
let mut wifi = Box::new(EspWifi::new(netif_stack, sys_loop_stack, default_nvs)?);
pub fn start_access_point(
modem: impl peripheral::Peripheral<P = esp_idf_hal::modem::Modem> + 'static,
default_nvs: EspDefaultNvsPartition,
) -> Result<Box<EspWifi<'static>>> {
let sysloop = EspSystemEventLoop::take()?;
// let netif_stack = Arc::new(EspNetifStack::new()?);
// let sys_loop_stack = Arc::new(EspSysLoopStack::new()?);
let mut wifi = Box::new(EspWifi::new(modem, sysloop.clone(), Some(default_nvs))?);
let ssid: &'static str = env!("SSID");
let password: &'static str = env!("PASS");
@@ -98,21 +135,34 @@ pub fn start_access_point(default_nvs: Arc<EspDefaultNvs>) -> Result<Box<EspWifi
..Default::default()
}))?;
info!("Wifi configuration set, about to get status");
wifi.wait_status_with_timeout(Duration::from_secs(20), |status| !status.is_transitional())
.map_err(|e| anyhow::anyhow!("Unexpected Wifi status: {:?}", e))?;
wifi.start()?;
let status = wifi.get_status();
if let Status(ClientStatus::Stopped, ApStatus::Started(ApIpStatus::Done)) = status {
info!("Wifi started!\n \nWIFI NAME: {}\nWIFI PASSWORD: {}\n", ssid, password);
} else {
return Err(anyhow::anyhow!("Unexpected AP Wifi status: {:?}", status));
info!("Wifi configuration set, about to get status");
if !WifiWait::new(&sysloop)?
.wait_with_timeout(Duration::from_secs(20), || wifi.is_started().unwrap())
{
return Err(anyhow::anyhow!("Wifi did not start"));
}
info!(
"Wifi started!\n \nWIFI NAME: {}\nWIFI PASSWORD: {}\n",
ssid, password
);
// let status = wifi.get_status();
// if let Status(ClientStatus::Stopped, ApStatus::Started(ApIpStatus::Done)) = status {
// info!(
// "Wifi started!\n \nWIFI NAME: {}\nWIFI PASSWORD: {}\n",
// ssid, password
// );
// } else {
// return Err(anyhow::anyhow!("Unexpected AP Wifi status: {:?}", status));
// }
Ok(wifi)
}
fn ping(ip_settings: &ipv4::ClientSettings) -> Result<()> {
fn _ping(ip_settings: &ipv4::ClientSettings) -> Result<()> {
info!("About to do some pings for {:?}", ip_settings);
let ping_summary =

View File

@@ -10,6 +10,8 @@ use embedded_svc::wifi::*;
use esp_idf_svc::nvs::*;
use esp_idf_svc::wifi::*;
use esp_idf_hal::peripheral;
use sphinx_crypter::chacha::{decrypt, PAYLOAD_LEN};
use sphinx_crypter::ecdh::{derive_shared_secret_from_slice, PUBLIC_KEY_LEN};
use sphinx_crypter::secp256k1::rand::thread_rng;
@@ -39,9 +41,13 @@ pub struct ConfigDTO {
arp -a
*/
pub fn start_wifi_client(default_nvs: Arc<EspDefaultNvs>, config: &Config) -> Result<Box<EspWifi>> {
let wifi = conn::wifi::start_client(default_nvs, config)?;
println!("CLIENT CONNECTED!!!!!! {:?}", wifi.get_status());
pub fn start_wifi_client(
modem: impl peripheral::Peripheral<P = esp_idf_hal::modem::Modem> + 'static,
default_nvs: EspDefaultNvsPartition,
config: &Config,
) -> Result<Box<EspWifi>> {
let wifi = conn::wifi::start_client(modem, default_nvs, config)?;
println!("CLIENT CONNECTED!!!!!! {:?}", wifi.is_connected());
Ok(wifi)
}
@@ -71,13 +77,14 @@ pub fn decrypt_seed(dto: ConfigDTO, sk1: SecretKey) -> Result<(Config, [u8; 32])
}
pub fn start_config_server_and_wait(
default_nvs: Arc<EspDefaultNvs>,
) -> Result<(Box<EspWifi>, Config, [u8; 32])> {
modem: impl peripheral::Peripheral<P = esp_idf_hal::modem::Modem> + 'static,
default_nvs: EspDefaultNvsPartition,
) -> Result<(Box<EspWifi<'static>>, Config, [u8; 32])> {
let mutex = Arc::new((Mutex::new(None), Condvar::new()));
#[allow(clippy::redundant_clone)]
#[allow(unused_mut)]
let mut wifi = conn::wifi::start_access_point(default_nvs.clone())?;
let mut wifi = conn::wifi::start_access_point(modem, default_nvs.clone())?;
let httpd = conn::http::config_server(mutex.clone());
let mut wait = mutex.0.lock().unwrap();

View File

@@ -1,10 +1,8 @@
use anyhow::{anyhow, Result};
use embedded_svc::storage::RawStorage;
use embedded_svc::storage::StorageBase;
use esp_idf_svc::nvs::EspDefaultNvs;
use esp_idf_svc::nvs_storage::EspNvsStorage;
use sphinx_signer::sphinx_glyph::control::{Config, ControlPersist, Controller, FlashKey, Policy};
use esp_idf_svc::nvs::{EspDefaultNvs, EspDefaultNvsPartition};
use sphinx_signer::lightning_signer::bitcoin::Network;
use sphinx_signer::sphinx_glyph::control::{Config, ControlPersist, Controller, FlashKey, Policy};
use std::convert::TryInto;
use std::sync::{Arc, Mutex};
@@ -18,11 +16,12 @@ pub fn controller_from_seed(
Controller::new_with_persister(sk, pk, flash)
}
pub struct FlashPersister(pub EspNvsStorage);
// EspDefaultNvsPartition
pub struct FlashPersister(pub EspDefaultNvs);
impl FlashPersister {
pub fn new(nvs: Arc<EspDefaultNvs>) -> Self {
let store = EspNvsStorage::new_default(nvs, "sphinx", true).expect("no storage");
pub fn new(nvs: EspDefaultNvsPartition) -> Self {
let store = EspDefaultNvs::new(nvs, "sphinx", true).expect("no storage");
Self(store)
}
}
@@ -34,12 +33,12 @@ impl ControlPersist for FlashPersister {
if let None = existing {
return Err(anyhow!("no existing nonce"));
}
let r: [u8; 8] = existing.unwrap().0.try_into()?;
let r: [u8; 8] = existing.unwrap().try_into()?;
Ok(u64::from_be_bytes(r))
}
fn set_nonce(&mut self, nonce: u64) -> Result<()> {
let n = nonce.to_be_bytes();
self.0.put_raw(FlashKey::Nonce.as_str(), &n[..])?;
self.0.set_raw(FlashKey::Nonce.as_str(), &n[..])?;
Ok(())
}
fn read_config(&self) -> Result<Config> {
@@ -48,11 +47,11 @@ impl ControlPersist for FlashPersister {
if let None = existing {
return Err(anyhow!("no existing config"));
}
Ok(rmp_serde::from_slice(existing.unwrap().0)?)
Ok(rmp_serde::from_slice(existing.unwrap())?)
}
fn write_config(&mut self, conf: Config) -> Result<()> {
let conf1 = rmp_serde::to_vec(&conf)?;
self.0.put_raw(FlashKey::Config.as_str(), &conf1[..])?;
self.0.set_raw(FlashKey::Config.as_str(), &conf1[..])?;
Ok(())
}
fn remove_config(&mut self) -> Result<()> {
@@ -65,11 +64,11 @@ impl ControlPersist for FlashPersister {
if let None = s {
return Err(anyhow!("no existing seed"));
}
let r: [u8; 32] = s.unwrap().0.try_into()?;
let r: [u8; 32] = s.unwrap().try_into()?;
Ok(r)
}
fn write_seed(&mut self, s: [u8; 32]) -> Result<()> {
self.0.put_raw(FlashKey::Seed.as_str(), &s[..])?;
self.0.set_raw(FlashKey::Seed.as_str(), &s[..])?;
Ok(())
}
fn remove_seed(&mut self) -> Result<()> {
@@ -82,11 +81,11 @@ impl ControlPersist for FlashPersister {
if let None = existing {
return Err(anyhow!("no existing config"));
}
Ok(rmp_serde::from_slice(existing.unwrap().0)?)
Ok(rmp_serde::from_slice(existing.unwrap())?)
}
fn write_policy(&mut self, pol: Policy) -> Result<()> {
let pol1 = rmp_serde::to_vec(&pol)?;
self.0.put_raw(FlashKey::Policy.as_str(), &pol1[..])?;
self.0.set_raw(FlashKey::Policy.as_str(), &pol1[..])?;
Ok(())
}
fn remove_policy(&mut self) -> Result<()> {

View File

@@ -15,9 +15,9 @@ use std::sync::Arc;
use std::thread;
use embedded_svc::httpd::Result;
use embedded_svc::mqtt::client::utils::ConnState;
use embedded_svc::mqtt::client::Client;
use embedded_svc::mqtt::client::{MessageImpl, Publish};
// use embedded_svc::mqtt::client::Client;
use embedded_svc::mqtt::client::MessageImpl;
use embedded_svc::utils::mqtt::client::ConnState;
use esp_idf_svc::mqtt::client::*;
use esp_idf_sys;
use esp_idf_sys::EspError;

View File

@@ -6,7 +6,7 @@ mod periph;
use crate::core::control::{controller_from_seed, FlashPersister};
use crate::core::{config::*, events::*};
use crate::periph::led::led_control_loop;
// use crate::periph::led::led_control_loop;
#[allow(unused_imports)]
use crate::periph::sd::{mount_sd_card, simple_fs_test};
@@ -20,8 +20,8 @@ use std::time::SystemTime;
use esp_idf_hal::peripherals::Peripherals;
use esp_idf_svc::nvs::*;
use sphinx_signer::sphinx_glyph::control::{Config, ControlPersist, Policy};
use sphinx_signer::lightning_signer::bitcoin::Network;
use sphinx_signer::sphinx_glyph::control::{Config, ControlPersist, Policy};
#[cfg(not(feature = "pingpong"))]
const CLIENT_ID: &str = "sphinx-1";
@@ -39,11 +39,11 @@ fn main() -> Result<()> {
thread::sleep(Duration::from_secs(1));
let peripherals = Peripherals::take().unwrap();
let pins = peripherals.pins;
let _pins = peripherals.pins;
let (led_tx, led_rx) = mpsc::channel();
let (led_tx, _led_rx) = mpsc::channel();
// LED control thread
led_control_loop(pins.gpio0, peripherals.rmt.channel0, led_rx);
// led_control_loop(pins.gpio0, peripherals.rmt.channel0, led_rx);
led_tx.send(Status::MountingSDCard).unwrap();
println!("About to mount the sdcard...");
@@ -53,7 +53,9 @@ fn main() -> Result<()> {
}
println!("SD card mounted!");
let default_nvs = Arc::new(EspDefaultNvs::new()?);
// let default_nav_partition = EspDefaultNvs.take().unwrap();
let default_nvs = EspDefaultNvsPartition::take()?;
// let default_nvs = Arc::new();
let mut flash = FlashPersister::new(default_nvs.clone());
if let Ok(exist) = flash.read_config() {
let seed = flash.read_seed().expect("no seed...");
@@ -63,15 +65,16 @@ fn main() -> Result<()> {
exist
);
led_tx.send(Status::ConnectingToWifi).unwrap();
let _wifi = loop {
if let Ok(wifi) = start_wifi_client(default_nvs.clone(), &exist) {
println!("Wifi connected!");
break wifi;
} else {
println!("Failed to connect to wifi. Make sure the details are correct, trying again in 5 seconds...");
thread::sleep(Duration::from_secs(5));
}
};
let wifi_ = start_wifi_client(peripherals.modem, default_nvs.clone(), &exist)?;
// let _wifi = loop {
// if let Ok(wifi) = start_wifi_client(peripherals.modem, default_nvs.clone(), &exist) {
// println!("Wifi connected!");
// break wifi;
// } else {
// println!("Failed to connect to wifi. Make sure the details are correct, trying again in 5 seconds...");
// thread::sleep(Duration::from_secs(5));
// }
// };
led_tx.send(Status::SyncingTime).unwrap();
conn::sntp::sync_time();
@@ -104,13 +107,13 @@ fn main() -> Result<()> {
} else {
led_tx.send(Status::WifiAccessPoint).unwrap();
println!("=============> START SERVER NOW AND WAIT <==============");
match start_config_server_and_wait(default_nvs.clone()) {
match start_config_server_and_wait(peripherals.modem, default_nvs.clone()) {
Ok((_wifi, config, seed)) => {
flash.write_config(config).expect("could not store config");
flash.write_seed(seed).expect("could not store seed");
println!("CONFIG SAVED");
unsafe { esp_idf_sys::esp_restart() };
},
}
Err(msg) => log::error!("{}", msg),
}
}
@@ -142,8 +145,8 @@ fn make_and_launch_client(
let token = ctrlr.make_auth_token().expect("couldnt make auth token");
log::info!("PUBKEY {} TOKEN {}", &pubkey, &token);
let (mqtt, connection) = conn::mqtt::make_client(&config.broker, CLIENT_ID, &pubkey, &token)?;
let mqtt_client = conn::mqtt::start_listening(mqtt, connection, tx)?;
let mqtt_client = conn::mqtt::make_client(&config.broker, CLIENT_ID, &pubkey, &token, tx)?;
// let mqtt_client = conn::mqtt::start_listening(mqtt, connection, tx)?;
// this blocks forever... the "main thread"
let do_log = true;

View File

@@ -1,13 +1,12 @@
use crate::core::events::Status;
use anyhow::{anyhow, Result};
use embedded_svc::http::client::Client;
use embedded_svc::http::client::Request;
use embedded_svc::http::client::Response;
use embedded_svc::http::Status as HttpStatus;
use embedded_svc::io::Read;
use embedded_svc::ota::Ota;
use esp_idf_svc::http::client::EspHttpClient;
use esp_idf_svc::http::client::EspHttpClientConfiguration;
// use embedded_svc::ota::Ota;
use esp_idf_svc::http::client::Configuration;
use esp_idf_svc::http::client::EspHttpConnection;
use esp_idf_svc::http::client::FollowRedirectsPolicy::FollowNone;
use esp_idf_svc::ota::EspOta;
use log::{error, info};
@@ -34,17 +33,17 @@ fn factory_reset() -> Result<()> {
}
fn get_update(params: OtaParams, led_tx: mpsc::Sender<Status>) -> Result<()> {
let configuration = EspHttpClientConfiguration {
let configuration = Configuration {
buffer_size: Some(BUFFER_LEN),
buffer_size_tx: Some(BUFFER_LEN / 3),
follow_redirects_policy: FollowNone,
use_global_ca_store: true,
crt_bundle_attach: None,
..Default::default()
};
let mut client = EspHttpClient::new(&configuration)?;
let mut client = Client::wrap(EspHttpConnection::new(&configuration)?);
let full_url = params_to_url(params);
let mut response = client.get(&full_url)?.submit()?;
let mut reader = response.reader();
let mut reader = client.get(&full_url)?.submit()?;
// let mut reader = response.reader();
let _ = remove_file(UPDATE_BIN_PATH);
let file = File::create(UPDATE_BIN_PATH)?;
@@ -84,14 +83,14 @@ pub fn update_sphinx_key(params: OtaParams, led_tx: mpsc::Sender<Status>) -> Res
}
pub fn validate_ota_message(params: OtaParams) -> Result<()> {
let configuration = EspHttpClientConfiguration {
let configuration = Configuration {
buffer_size: Some(BUFFER_LEN / 3),
buffer_size_tx: Some(BUFFER_LEN / 3),
follow_redirects_policy: FollowNone,
use_global_ca_store: true,
crt_bundle_attach: None,
..Default::default()
};
let mut client = EspHttpClient::new(&configuration)?;
let mut client = Client::wrap(EspHttpConnection::new(&configuration)?);
let full_url = params_to_url(params);
info!("Pinging this url for an update: {}", full_url);
let response = client.get(&full_url)?.submit()?;

View File

@@ -1,8 +1,8 @@
use crate::core::events::Status;
use embedded_hal::delay::blocking::DelayUs;
use esp_idf_hal::delay::Ets;
// use embedded_hal::delay::blocking::DelayUs;
use esp_idf_hal::delay::FreeRtos;
use esp_idf_hal::rmt::config::TransmitConfig;
use esp_idf_hal::rmt::{FixedLengthSignal, PinState, Pulse, Transmit};
use esp_idf_hal::rmt::{FixedLengthSignal, PinState, Pulse, TxRmtDriver};
use esp_idf_hal::{gpio, rmt};
use std::collections::BTreeMap;
use std::sync::{mpsc, Arc, Mutex};
@@ -32,14 +32,12 @@ fn states() -> BTreeMap<Status, (Color, Time)> {
s
}
pub fn led_control_loop(
gpio0: gpio::Gpio0<gpio::Unknown>,
channel0: rmt::CHANNEL0,
rx: mpsc::Receiver<Status>,
) {
let led = gpio0.into_output().unwrap();
pub fn led_control_loop(gpio0: gpio::Gpio0, channel0: rmt::CHANNEL0, rx: mpsc::Receiver<Status>) {
let led = gpio0;
let config = TransmitConfig::new().clock_divider(1);
let transmit = Arc::new(Mutex::new(Transmit::new(led, channel0, &config).unwrap()));
let transmit = Arc::new(Mutex::new(
TxRmtDriver::new(channel0, led, &config).unwrap(),
));
thread::spawn(move || {
let mut led = Led::new(0x000001, 100);
let states = states();
@@ -69,10 +67,7 @@ impl Led {
self.blink_length = blink_length;
}
pub fn blink(
&mut self,
transmit: Arc<Mutex<Transmit<gpio::Gpio0<gpio::Output>, rmt::CHANNEL0>>>,
) {
pub fn blink(&mut self, transmit: Arc<Mutex<TxRmtDriver>>) {
// Prepare signal
let mut tx = transmit.lock().unwrap();
let ticks_hz = tx.counter_clock().unwrap();
@@ -89,7 +84,7 @@ impl Led {
}
// Set high and wait
tx.start_blocking(&signal).unwrap();
Ets.delay_ms(self.blink_length).unwrap();
FreeRtos::delay_ms(self.blink_length);
// Set low
let mut signal = FixedLengthSignal::<24>::new();
for i in 0..24 {

View File

@@ -1,5 +1,6 @@
use bitflags::bitflags;
use esp_idf_sys::c_types::c_char;
// use esp_idf_sys::c_types::c_char;
use core::ffi::c_char;
use esp_idf_sys::{
esp, esp_vfs_fat_sdmmc_mount_config_t, esp_vfs_fat_sdspi_mount, gpio_num_t, sdmmc_card_t,
sdmmc_host_t, sdspi_device_config_t, spi_bus_config_t, spi_bus_initialize, spi_host_device_t,