ddk 1.0.11

application tooling for DLCs 🌊
Documentation
mod relay_handler;

use crate::logger::{log_error, log_info, WriteLog};
pub use relay_handler::NostrDlc;
use tokio::sync::watch;

use crate::error::TransportError;
use crate::nostr;
use crate::{DlcDevKitDlcManager, Oracle, Storage, Transport};
use async_trait::async_trait;
use ddk_dlc::secp256k1_zkp::PublicKey as BitcoinPublicKey;
use ddk_messages::Message;
use std::sync::Arc;

#[async_trait]
impl Transport for NostrDlc {
    fn name(&self) -> String {
        "nostr".to_string()
    }

    fn public_key(&self) -> BitcoinPublicKey {
        nostr::nostr_to_bitcoin_pubkey(&self.keys.public_key())
    }

    /// Get messages that have not been processed yet.
    async fn start<S: Storage, O: Oracle>(
        &self,
        mut stop_signal: watch::Receiver<bool>,
        manager: Arc<DlcDevKitDlcManager<S, O>>,
    ) -> Result<(), TransportError> {
        let listen_handle = self.start(stop_signal.clone(), manager);

        // Wait for either task to complete or stop signal
        tokio::select! {
            _ = stop_signal.changed() => Ok(()),
            res = listen_handle => res.map_err(|e| TransportError::Listen(e.to_string()))?,
        }
    }
    /// Send a message to a specific counterparty.
    async fn send_message(&self, counterparty: BitcoinPublicKey, message: Message) {
        let nostr_counterparty = nostr::bitcoin_to_nostr_pubkey(&counterparty);
        log_info!(
            self.logger,
            "Sending nostr message. bitcoin_pk={} nostr_pk={}",
            counterparty.to_string(),
            nostr_counterparty.to_string()
        );
        let event =
            nostr::messages::create_dlc_msg_event(nostr_counterparty, None, message, &self.keys)
                .unwrap();
        match self.client.send_event(&event).await {
            Ok(e) => log_info!(
                self.logger,
                "Sent DLC message event. event_id={}",
                e.val.to_string()
            ),
            Err(e) => log_error!(
                self.logger,
                "Failed to send nostr event. error={}",
                e.to_string()
            ),
        }
    }
    /// Connect to a relay.
    async fn connect_outbound(&self, _pubkey: BitcoinPublicKey, host: &str) {
        match self.client.add_relay(host).await {
            Ok(_) => log_info!(self.logger, "Added relay. host={}", host),
            Err(e) => log_error!(
                self.logger,
                "Could not add relay. host={} error={}",
                host,
                e.to_string()
            ),
        }
    }
}