1#![crate_name = "ddk_manager"]
5#![forbid(unsafe_code)]
7#![deny(non_upper_case_globals)]
8#![deny(non_camel_case_types)]
9#![deny(non_snake_case)]
10#![deny(unused_mut)]
11#![deny(dead_code)]
12#![deny(unused_imports)]
13#![deny(missing_docs)]
14
15#[macro_use]
16extern crate dlc_messages;
17
18pub mod chain_monitor;
19pub mod channel;
20pub mod channel_updater;
21pub mod contract;
22pub mod contract_updater;
23mod conversion_utils;
24pub mod error;
25pub mod manager;
26pub mod payout_curve;
27mod utils;
28
29use bitcoin::psbt::Psbt;
30use bitcoin::{Address, Block, OutPoint, ScriptBuf, Transaction, TxOut, Txid};
31use chain_monitor::ChainMonitor;
32use channel::offered_channel::OfferedChannel;
33use channel::signed_channel::{SignedChannel, SignedChannelStateType};
34use channel::Channel;
35use contract::PreClosedContract;
36use contract::{offered_contract::OfferedContract, signed_contract::SignedContract, Contract};
37use dlc_messages::impl_dlc_writeable;
38use dlc_messages::oracle_msgs::{OracleAnnouncement, OracleAttestation};
39use dlc_messages::ser_impls::{read_address, write_address};
40use error::Error;
41use lightning::ln::msgs::DecodeError;
42use lightning::util::ser::{Readable, Writeable, Writer};
43use secp256k1_zkp::{PublicKey, SecretKey, Signing};
44use secp256k1_zkp::{Secp256k1, XOnlyPublicKey};
45use std::collections::HashMap;
46use std::ops::Deref;
47use std::sync::RwLock;
48
49pub type ContractId = [u8; 32];
51
52pub type KeysId = [u8; 32];
54
55pub type ChannelId = [u8; 32];
57
58pub trait Time {
60 fn unix_time_now(&self) -> u64;
62}
63
64pub struct SystemTimeProvider {}
66
67impl Time for SystemTimeProvider {
68 fn unix_time_now(&self) -> u64 {
69 let now = std::time::SystemTime::now();
70 now.duration_since(std::time::UNIX_EPOCH)
71 .expect("Unexpected time error")
72 .as_secs()
73 }
74}
75
76pub trait ContractSigner: Clone {
78 fn get_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> Result<PublicKey, Error>;
80 fn get_secret_key(&self) -> Result<SecretKey, Error>;
83}
84
85#[derive(Debug, Copy, Clone)]
87pub struct SimpleSigner {
88 secret_key: SecretKey,
89}
90
91impl SimpleSigner {
92 pub fn new(secret_key: SecretKey) -> Self {
94 Self { secret_key }
95 }
96}
97
98impl ContractSigner for SimpleSigner {
99 fn get_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> Result<PublicKey, Error> {
100 Ok(self.secret_key.public_key(secp))
101 }
102
103 fn get_secret_key(&self) -> Result<SecretKey, Error> {
104 Ok(self.secret_key)
105 }
106}
107
108impl ContractSigner for SecretKey {
109 fn get_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> Result<PublicKey, Error> {
110 Ok(self.public_key(secp))
111 }
112
113 fn get_secret_key(&self) -> Result<SecretKey, Error> {
114 Ok(*self)
115 }
116}
117
118pub trait ContractSignerProvider {
120 type Signer: ContractSigner;
122
123 fn derive_signer_key_id(&self, is_offer_party: bool, temp_id: [u8; 32]) -> [u8; 32];
125
126 fn derive_contract_signer(&self, key_id: [u8; 32]) -> Result<Self::Signer, Error>;
128
129 fn get_secret_key_for_pubkey(&self, pubkey: &PublicKey) -> Result<SecretKey, Error>;
133 fn get_new_secret_key(&self) -> Result<SecretKey, Error>;
137}
138
139#[async_trait::async_trait]
140pub trait Wallet {
143 async fn get_new_address(&self) -> Result<Address, Error>;
145 async fn get_new_change_address(&self) -> Result<Address, Error>;
147 fn get_utxos_for_amount(
149 &self,
150 amount: u64,
151 fee_rate: u64,
152 lock_utxos: bool,
153 ) -> Result<Vec<Utxo>, Error>;
154 fn import_address(&self, address: &Address) -> Result<(), Error>;
156 fn sign_psbt_input(&self, psbt: &mut Psbt, input_index: usize) -> Result<(), Error>;
158 fn unreserve_utxos(&self, outpoints: &[OutPoint]) -> Result<(), Error>;
160}
161
162#[async_trait::async_trait]
163pub trait Blockchain {
165 async fn send_transaction(&self, transaction: &Transaction) -> Result<(), Error>;
167 fn get_network(&self) -> Result<bitcoin::Network, Error>;
169 async fn get_blockchain_height(&self) -> Result<u64, Error>;
171 async fn get_block_at_height(&self, height: u64) -> Result<Block, Error>;
173 async fn get_transaction(&self, tx_id: &Txid) -> Result<Transaction, Error>;
175 async fn get_transaction_confirmations(&self, tx_id: &Txid) -> Result<u32, Error>;
177}
178
179#[async_trait::async_trait]
180pub trait Storage {
182 async fn get_contract(&self, id: &ContractId) -> Result<Option<Contract>, Error>;
184 async fn get_contracts(&self) -> Result<Vec<Contract>, Error>;
186 async fn create_contract(&self, contract: &OfferedContract) -> Result<(), Error>;
188 async fn delete_contract(&self, id: &ContractId) -> Result<(), Error>;
190 async fn update_contract(&self, contract: &Contract) -> Result<(), Error>;
192 async fn get_contract_offers(&self) -> Result<Vec<OfferedContract>, Error>;
194 async fn get_signed_contracts(&self) -> Result<Vec<SignedContract>, Error>;
196 async fn get_confirmed_contracts(&self) -> Result<Vec<SignedContract>, Error>;
198 async fn get_preclosed_contracts(&self) -> Result<Vec<PreClosedContract>, Error>;
201 async fn upsert_channel(
204 &self,
205 channel: Channel,
206 contract: Option<Contract>,
207 ) -> Result<(), Error>;
208 async fn delete_channel(&self, channel_id: &ChannelId) -> Result<(), Error>;
210 async fn get_channel(&self, channel_id: &ChannelId) -> Result<Option<Channel>, Error>;
212 async fn get_signed_channels(
215 &self,
216 channel_state: Option<SignedChannelStateType>,
217 ) -> Result<Vec<SignedChannel>, Error>;
218 async fn get_offered_channels(&self) -> Result<Vec<OfferedChannel>, Error>;
220 async fn persist_chain_monitor(&self, monitor: &ChainMonitor) -> Result<(), Error>;
222 async fn get_chain_monitor(&self) -> Result<Option<ChainMonitor>, Error>;
224}
225
226#[async_trait::async_trait]
227pub trait Oracle {
229 fn get_public_key(&self) -> XOnlyPublicKey;
231 async fn get_announcement(&self, event_id: &str) -> Result<OracleAnnouncement, Error>;
233 async fn get_attestation(&self, event_id: &str) -> Result<OracleAttestation, Error>;
235}
236
237#[derive(Clone, Debug)]
239pub struct Utxo {
240 pub tx_out: TxOut,
242 pub outpoint: OutPoint,
244 pub address: Address,
246 pub redeem_script: ScriptBuf,
248 pub reserved: bool,
251}
252
253impl_dlc_writeable!(Utxo, {
254 (tx_out, writeable),
255 (outpoint, writeable),
256 (address, {cb_writeable, write_address, read_address}),
257 (redeem_script, writeable),
258 (reserved, writeable)
259});
260
261pub struct CachedContractSignerProvider<SP: Deref, X>
263where
264 SP::Target: ContractSignerProvider<Signer = X>,
265{
266 pub(crate) signer_provider: SP,
267 pub(crate) cache: RwLock<HashMap<KeysId, X>>,
268}
269
270impl<SP: Deref, X> CachedContractSignerProvider<SP, X>
271where
272 SP::Target: ContractSignerProvider<Signer = X>,
273{
274 pub fn new(signer_provider: SP) -> Self {
276 Self {
277 signer_provider,
278 cache: RwLock::new(HashMap::new()),
279 }
280 }
281}
282
283impl<SP: Deref, X: ContractSigner> ContractSignerProvider for CachedContractSignerProvider<SP, X>
284where
285 SP::Target: ContractSignerProvider<Signer = X>,
286{
287 type Signer = X;
288
289 fn derive_signer_key_id(&self, is_offer_party: bool, temp_id: [u8; 32]) -> KeysId {
290 self.signer_provider
291 .derive_signer_key_id(is_offer_party, temp_id)
292 }
293
294 fn derive_contract_signer(&self, key_id: KeysId) -> Result<Self::Signer, Error> {
295 match self.cache.try_read().unwrap().get(&key_id) {
296 Some(signer) => Ok(signer.clone()),
297 None => self.signer_provider.derive_contract_signer(key_id),
298 }
299 }
300
301 fn get_secret_key_for_pubkey(&self, pubkey: &PublicKey) -> Result<SecretKey, Error> {
302 self.signer_provider.get_secret_key_for_pubkey(pubkey)
303 }
304
305 fn get_new_secret_key(&self) -> Result<SecretKey, Error> {
306 self.signer_provider.get_new_secret_key()
307 }
308}