dlc_manager/
manager.rs

1//! #Manager a component to create and update DLCs.
2
3use super::{
4    Blockchain, CachedContractSignerProvider, ContractSigner, Oracle, Storage, Time, Wallet,
5};
6use crate::chain_monitor::{ChainMonitor, ChannelInfo, RevokedTxType, TxType};
7use crate::channel::offered_channel::OfferedChannel;
8use crate::channel::signed_channel::{SignedChannel, SignedChannelState, SignedChannelStateType};
9use crate::channel::{Channel, ClosedChannel, ClosedPunishedChannel};
10use crate::channel_updater::get_signed_channel_state;
11use crate::channel_updater::verify_signed_channel;
12use crate::contract::{
13    accepted_contract::AcceptedContract, contract_info::ContractInfo,
14    contract_input::ContractInput, contract_input::OracleInput, offered_contract::OfferedContract,
15    signed_contract::SignedContract, AdaptorInfo, ClosedContract, Contract, FailedAcceptContract,
16    FailedSignContract, PreClosedContract,
17};
18use crate::contract_updater::{accept_contract, verify_accepted_and_sign_contract};
19use crate::error::Error;
20use crate::utils::get_object_in_state;
21use crate::{ChannelId, ContractId, ContractSignerProvider};
22use bitcoin::absolute::Height;
23use bitcoin::consensus::encode::serialize_hex;
24use bitcoin::consensus::Decodable;
25use bitcoin::{Address, Amount, SignedAmount};
26use bitcoin::{OutPoint, Transaction};
27use dlc_messages::channel::{
28    AcceptChannel, CollaborativeCloseOffer, OfferChannel, Reject, RenewAccept, RenewConfirm,
29    RenewFinalize, RenewOffer, RenewRevoke, SettleAccept, SettleConfirm, SettleFinalize,
30    SettleOffer, SignChannel,
31};
32use dlc_messages::oracle_msgs::{OracleAnnouncement, OracleAttestation};
33use dlc_messages::{AcceptDlc, Message as DlcMessage, OfferDlc, SignDlc};
34use hex::DisplayHex;
35use lightning::chain::chaininterface::FeeEstimator;
36use lightning::ln::chan_utils::{
37    build_commitment_secret, derive_private_key, derive_private_revocation_key,
38};
39use log::{error, warn};
40use secp256k1_zkp::XOnlyPublicKey;
41use secp256k1_zkp::{
42    ecdsa::Signature, All, EcdsaAdaptorSignature, PublicKey, Secp256k1, SecretKey,
43};
44use std::collections::HashMap;
45use std::ops::Deref;
46use std::string::ToString;
47use std::sync::{Arc, Mutex};
48
49/// The number of confirmations required before moving the the confirmed state.
50pub const NB_CONFIRMATIONS: u32 = 6;
51/// The delay to set the refund value to.
52pub const REFUND_DELAY: u32 = 86400 * 7;
53/// The nSequence value used for CETs in DLC channels
54pub const CET_NSEQUENCE: u32 = 288;
55/// Timeout in seconds when waiting for a peer's reply, after which a DLC channel
56/// is forced closed.
57pub const PEER_TIMEOUT: u64 = 3600;
58
59type ClosableContractInfo<'a> = Option<(
60    &'a ContractInfo,
61    &'a AdaptorInfo,
62    Vec<(usize, OracleAttestation)>,
63)>;
64
65/// Used to create and update DLCs.
66pub struct Manager<
67    W: Deref,
68    SP: Deref,
69    B: Deref,
70    S: Deref,
71    O: Deref,
72    T: Deref,
73    F: Deref,
74    X: ContractSigner,
75> where
76    W::Target: Wallet,
77    SP::Target: ContractSignerProvider<Signer = X>,
78    B::Target: Blockchain,
79    S::Target: Storage,
80    O::Target: Oracle,
81    T::Target: Time,
82    F::Target: FeeEstimator,
83{
84    oracles: HashMap<XOnlyPublicKey, O>,
85    wallet: W,
86    signer_provider: SP,
87    blockchain: B,
88    store: S,
89    secp: Secp256k1<All>,
90    chain_monitor: Mutex<ChainMonitor>,
91    time: T,
92    fee_estimator: F,
93}
94
95macro_rules! get_contract_in_state {
96    ($manager: ident, $contract_id: expr, $state: ident, $peer_id: expr) => {{
97        get_object_in_state!(
98            $manager,
99            $contract_id,
100            $state,
101            $peer_id,
102            Contract,
103            get_contract
104        )
105    }};
106}
107
108macro_rules! get_channel_in_state {
109    ($manager: ident, $channel_id: expr, $state: ident, $peer_id: expr) => {{
110        get_object_in_state!(
111            $manager,
112            $channel_id,
113            $state,
114            $peer_id,
115            Channel,
116            get_channel
117        )
118    }};
119}
120
121macro_rules! get_signed_channel_rollback_state {
122    ($signed_channel: ident, $state: ident, $($field: ident),*) => {{
123       match $signed_channel.roll_back_state.as_ref() {
124           Some(SignedChannelState::$state{$($field,)* ..}) => Ok(($($field,)*)),
125           _ => Err(Error::InvalidState(format!("Expected rollback state {} got {:?}", stringify!($state), $signed_channel.state))),
126        }
127    }};
128}
129
130macro_rules! check_for_timed_out_channels {
131    ($manager: ident, $state: ident) => {
132        let channels = $manager
133            .store
134            .get_signed_channels(Some(SignedChannelStateType::$state))?;
135
136        for channel in channels {
137            if let SignedChannelState::$state { timeout, .. } = channel.state {
138                let is_timed_out = timeout < $manager.time.unix_time_now();
139                if is_timed_out {
140                    match $manager.force_close_channel_internal(channel, true) {
141                        Err(e) => error!("Error force closing channel {}", e),
142                        _ => {}
143                    }
144                }
145            }
146        }
147    };
148}
149
150impl<W: Deref, SP: Deref, B: Deref, S: Deref, O: Deref, T: Deref, F: Deref, X: ContractSigner>
151    Manager<W, Arc<CachedContractSignerProvider<SP, X>>, B, S, O, T, F, X>
152where
153    W::Target: Wallet,
154    SP::Target: ContractSignerProvider<Signer = X>,
155    B::Target: Blockchain,
156    S::Target: Storage,
157    O::Target: Oracle,
158    T::Target: Time,
159    F::Target: FeeEstimator,
160{
161    /// Create a new Manager struct.
162    pub fn new(
163        wallet: W,
164        signer_provider: SP,
165        blockchain: B,
166        store: S,
167        oracles: HashMap<XOnlyPublicKey, O>,
168        time: T,
169        fee_estimator: F,
170    ) -> Result<Self, Error> {
171        let init_height = blockchain.get_blockchain_height()?;
172        let chain_monitor = Mutex::new(
173            store
174                .get_chain_monitor()?
175                .unwrap_or(ChainMonitor::new(init_height)),
176        );
177
178        let signer_provider = Arc::new(CachedContractSignerProvider::new(signer_provider));
179
180        Ok(Manager {
181            secp: secp256k1_zkp::Secp256k1::new(),
182            wallet,
183            signer_provider,
184            blockchain,
185            store,
186            oracles,
187            time,
188            fee_estimator,
189            chain_monitor,
190        })
191    }
192
193    /// Get the store from the Manager to access contracts.
194    pub fn get_store(&self) -> &S {
195        &self.store
196    }
197
198    /// Function called to pass a DlcMessage to the Manager.
199    pub fn on_dlc_message(
200        &self,
201        msg: &DlcMessage,
202        counter_party: PublicKey,
203    ) -> Result<Option<DlcMessage>, Error> {
204        match msg {
205            DlcMessage::Offer(o) => {
206                self.on_offer_message(o, counter_party)?;
207                Ok(None)
208            }
209            DlcMessage::Accept(a) => Ok(Some(self.on_accept_message(a, &counter_party)?)),
210            DlcMessage::Sign(s) => {
211                self.on_sign_message(s, &counter_party)?;
212                Ok(None)
213            }
214            DlcMessage::OfferChannel(o) => {
215                self.on_offer_channel(o, counter_party)?;
216                Ok(None)
217            }
218            DlcMessage::AcceptChannel(a) => Ok(Some(DlcMessage::SignChannel(
219                self.on_accept_channel(a, &counter_party)?,
220            ))),
221            DlcMessage::SignChannel(s) => {
222                self.on_sign_channel(s, &counter_party)?;
223                Ok(None)
224            }
225            DlcMessage::SettleOffer(s) => match self.on_settle_offer(s, &counter_party)? {
226                Some(msg) => Ok(Some(DlcMessage::Reject(msg))),
227                None => Ok(None),
228            },
229            DlcMessage::SettleAccept(s) => Ok(Some(DlcMessage::SettleConfirm(
230                self.on_settle_accept(s, &counter_party)?,
231            ))),
232            DlcMessage::SettleConfirm(s) => Ok(Some(DlcMessage::SettleFinalize(
233                self.on_settle_confirm(s, &counter_party)?,
234            ))),
235            DlcMessage::SettleFinalize(s) => {
236                self.on_settle_finalize(s, &counter_party)?;
237                Ok(None)
238            }
239            DlcMessage::RenewOffer(r) => match self.on_renew_offer(r, &counter_party)? {
240                Some(msg) => Ok(Some(DlcMessage::Reject(msg))),
241                None => Ok(None),
242            },
243            DlcMessage::RenewAccept(r) => Ok(Some(DlcMessage::RenewConfirm(
244                self.on_renew_accept(r, &counter_party)?,
245            ))),
246            DlcMessage::RenewConfirm(r) => Ok(Some(DlcMessage::RenewFinalize(
247                self.on_renew_confirm(r, &counter_party)?,
248            ))),
249            DlcMessage::RenewFinalize(r) => {
250                let revoke = self.on_renew_finalize(r, &counter_party)?;
251                Ok(Some(DlcMessage::RenewRevoke(revoke)))
252            }
253            DlcMessage::RenewRevoke(r) => {
254                self.on_renew_revoke(r, &counter_party)?;
255                Ok(None)
256            }
257            DlcMessage::CollaborativeCloseOffer(c) => {
258                self.on_collaborative_close_offer(c, &counter_party)?;
259                Ok(None)
260            }
261            DlcMessage::Reject(r) => {
262                self.on_reject(r, &counter_party)?;
263                Ok(None)
264            }
265        }
266    }
267
268    /// Function called to create a new DLC. The offered contract will be stored
269    /// and an OfferDlc message returned.
270    ///
271    /// This function will fetch the oracle announcements from the oracle.
272    pub fn send_offer(
273        &self,
274        contract_input: &ContractInput,
275        counter_party: PublicKey,
276    ) -> Result<OfferDlc, Error> {
277        let oracle_announcements = contract_input
278            .contract_infos
279            .iter()
280            .map(|x| self.get_oracle_announcements(&x.oracles))
281            .collect::<Result<Vec<_>, Error>>()?;
282
283        self.send_offer_with_announcements(contract_input, counter_party, oracle_announcements)
284    }
285
286    /// Function called to create a new DLC. The offered contract will be stored
287    /// and an OfferDlc message returned.
288    ///
289    /// This function allows to pass the oracle announcements directly instead of
290    /// fetching them from the oracle.
291    pub fn send_offer_with_announcements(
292        &self,
293        contract_input: &ContractInput,
294        counter_party: PublicKey,
295        oracle_announcements: Vec<Vec<OracleAnnouncement>>,
296    ) -> Result<OfferDlc, Error> {
297        let (offered_contract, offer_msg) = crate::contract_updater::offer_contract(
298            &self.secp,
299            contract_input,
300            oracle_announcements,
301            REFUND_DELAY,
302            &counter_party,
303            &self.wallet,
304            &self.blockchain,
305            &self.time,
306            &self.signer_provider,
307        )?;
308
309        offered_contract.validate()?;
310
311        self.store.create_contract(&offered_contract)?;
312
313        Ok(offer_msg)
314    }
315
316    /// Function to call to accept a DLC for which an offer was received.
317    pub fn accept_contract_offer(
318        &self,
319        contract_id: &ContractId,
320    ) -> Result<(ContractId, PublicKey, AcceptDlc), Error> {
321        let offered_contract =
322            get_contract_in_state!(self, contract_id, Offered, None as Option<PublicKey>)?;
323
324        let counter_party = offered_contract.counter_party;
325
326        let (accepted_contract, accept_msg) = accept_contract(
327            &self.secp,
328            &offered_contract,
329            &self.wallet,
330            &self.signer_provider,
331            &self.blockchain,
332        )?;
333
334        self.wallet.import_address(&Address::p2wsh(
335            &accepted_contract.dlc_transactions.funding_script_pubkey,
336            self.blockchain.get_network()?,
337        ))?;
338
339        let contract_id = accepted_contract.get_contract_id();
340
341        self.store
342            .update_contract(&Contract::Accepted(accepted_contract))?;
343
344        Ok((contract_id, counter_party, accept_msg))
345    }
346
347    /// Function to update the state of the [`ChainMonitor`] with new
348    /// blocks.
349    ///
350    /// Consumers **MUST** call this periodically in order to
351    /// determine when pending transactions reach confirmation.
352    pub fn periodic_chain_monitor(&self) -> Result<(), Error> {
353        let cur_height = self.blockchain.get_blockchain_height()?;
354        let last_height = self.chain_monitor.lock().unwrap().last_height;
355
356        // TODO(luckysori): We could end up reprocessing a block at
357        // the same height if there is a reorg.
358        if cur_height < last_height {
359            return Err(Error::InvalidState(
360                "Current height is lower than last height.".to_string(),
361            ));
362        }
363
364        for height in last_height + 1..=cur_height {
365            let block = self.blockchain.get_block_at_height(height)?;
366
367            self.chain_monitor
368                .lock()
369                .unwrap()
370                .process_block(&block, height);
371        }
372
373        Ok(())
374    }
375
376    /// Function to call to check the state of the currently executing DLCs and
377    /// update them if possible.
378    pub fn periodic_check(&self, check_channels: bool) -> Result<(), Error> {
379        self.check_signed_contracts()?;
380        self.check_confirmed_contracts()?;
381        self.check_preclosed_contracts()?;
382
383        if check_channels {
384            self.channel_checks()?;
385        }
386
387        Ok(())
388    }
389
390    fn on_offer_message(
391        &self,
392        offered_message: &OfferDlc,
393        counter_party: PublicKey,
394    ) -> Result<(), Error> {
395        offered_message.validate(&self.secp, REFUND_DELAY, REFUND_DELAY * 2)?;
396        let keys_id = self
397            .signer_provider
398            .derive_signer_key_id(false, offered_message.temporary_contract_id);
399        let contract: OfferedContract =
400            OfferedContract::try_from_offer_dlc(offered_message, counter_party, keys_id)?;
401        contract.validate()?;
402
403        if self.store.get_contract(&contract.id)?.is_some() {
404            return Err(Error::InvalidParameters(
405                "Contract with identical id already exists".to_string(),
406            ));
407        }
408
409        self.store.create_contract(&contract)?;
410
411        Ok(())
412    }
413
414    fn on_accept_message(
415        &self,
416        accept_msg: &AcceptDlc,
417        counter_party: &PublicKey,
418    ) -> Result<DlcMessage, Error> {
419        let offered_contract = get_contract_in_state!(
420            self,
421            &accept_msg.temporary_contract_id,
422            Offered,
423            Some(*counter_party)
424        )?;
425
426        let (signed_contract, signed_msg) = match verify_accepted_and_sign_contract(
427            &self.secp,
428            &offered_contract,
429            accept_msg,
430            &self.wallet,
431            &self.signer_provider,
432        ) {
433            Ok(contract) => contract,
434            Err(e) => return self.accept_fail_on_error(offered_contract, accept_msg.clone(), e),
435        };
436
437        self.wallet.import_address(&Address::p2wsh(
438            &signed_contract
439                .accepted_contract
440                .dlc_transactions
441                .funding_script_pubkey,
442            self.blockchain.get_network()?,
443        ))?;
444
445        self.store
446            .update_contract(&Contract::Signed(signed_contract))?;
447
448        Ok(DlcMessage::Sign(signed_msg))
449    }
450
451    fn on_sign_message(&self, sign_message: &SignDlc, peer_id: &PublicKey) -> Result<(), Error> {
452        let accepted_contract =
453            get_contract_in_state!(self, &sign_message.contract_id, Accepted, Some(*peer_id))?;
454
455        let (signed_contract, fund_tx) = match crate::contract_updater::verify_signed_contract(
456            &self.secp,
457            &accepted_contract,
458            sign_message,
459            &self.wallet,
460        ) {
461            Ok(contract) => contract,
462            Err(e) => return self.sign_fail_on_error(accepted_contract, sign_message.clone(), e),
463        };
464
465        self.store
466            .update_contract(&Contract::Signed(signed_contract))?;
467
468        self.blockchain.send_transaction(&fund_tx)?;
469
470        Ok(())
471    }
472
473    fn get_oracle_announcements(
474        &self,
475        oracle_inputs: &OracleInput,
476    ) -> Result<Vec<OracleAnnouncement>, Error> {
477        let mut announcements = Vec::new();
478        for pubkey in &oracle_inputs.public_keys {
479            let oracle = self
480                .oracles
481                .get(pubkey)
482                .ok_or_else(|| Error::InvalidParameters("Unknown oracle public key".to_string()))?;
483            announcements.push(oracle.get_announcement(&oracle_inputs.event_id)?.clone());
484        }
485
486        Ok(announcements)
487    }
488
489    fn sign_fail_on_error<R>(
490        &self,
491        accepted_contract: AcceptedContract,
492        sign_message: SignDlc,
493        e: Error,
494    ) -> Result<R, Error> {
495        error!("Error in on_sign {}", e);
496        self.store
497            .update_contract(&Contract::FailedSign(FailedSignContract {
498                accepted_contract,
499                sign_message,
500                error_message: e.to_string(),
501            }))?;
502        Err(e)
503    }
504
505    fn accept_fail_on_error<R>(
506        &self,
507        offered_contract: OfferedContract,
508        accept_message: AcceptDlc,
509        e: Error,
510    ) -> Result<R, Error> {
511        error!("Error in on_accept {}", e);
512        self.store
513            .update_contract(&Contract::FailedAccept(FailedAcceptContract {
514                offered_contract,
515                accept_message,
516                error_message: e.to_string(),
517            }))?;
518        Err(e)
519    }
520
521    fn check_signed_contract(&self, contract: &SignedContract) -> Result<(), Error> {
522        let confirmations = self.blockchain.get_transaction_confirmations(
523            &contract
524                .accepted_contract
525                .dlc_transactions
526                .fund
527                .compute_txid(),
528        )?;
529        if confirmations >= NB_CONFIRMATIONS {
530            self.store
531                .update_contract(&Contract::Confirmed(contract.clone()))?;
532        }
533        Ok(())
534    }
535
536    fn check_signed_contracts(&self) -> Result<(), Error> {
537        for c in self.store.get_signed_contracts()? {
538            if let Err(e) = self.check_signed_contract(&c) {
539                error!(
540                    "Error checking confirmed contract {}: {}",
541                    c.accepted_contract.get_contract_id_string(),
542                    e
543                )
544            }
545        }
546
547        Ok(())
548    }
549
550    fn check_confirmed_contracts(&self) -> Result<(), Error> {
551        for c in self.store.get_confirmed_contracts()? {
552            // Confirmed contracts from channel are processed in channel specific methods.
553            if c.channel_id.is_some() {
554                continue;
555            }
556            if let Err(e) = self.check_confirmed_contract(&c) {
557                error!(
558                    "Error checking confirmed contract {}: {}",
559                    c.accepted_contract.get_contract_id_string(),
560                    e
561                )
562            }
563        }
564
565        Ok(())
566    }
567
568    fn get_closable_contract_info<'a>(
569        &'a self,
570        contract: &'a SignedContract,
571    ) -> ClosableContractInfo<'a> {
572        let contract_infos = &contract.accepted_contract.offered_contract.contract_info;
573        let adaptor_infos = &contract.accepted_contract.adaptor_infos;
574        for (contract_info, adaptor_info) in contract_infos.iter().zip(adaptor_infos.iter()) {
575            let matured: Vec<_> = contract_info
576                .oracle_announcements
577                .iter()
578                .filter(|x| {
579                    (x.oracle_event.event_maturity_epoch as u64) <= self.time.unix_time_now()
580                })
581                .enumerate()
582                .collect();
583            if matured.len() >= contract_info.threshold {
584                let attestations: Vec<_> = matured
585                    .iter()
586                    .filter_map(|(i, announcement)| {
587                        let oracle = self.oracles.get(&announcement.oracle_public_key)?;
588                        let attestation = oracle
589                            .get_attestation(&announcement.oracle_event.event_id)
590                            .ok()?;
591                        attestation
592                            .validate(&self.secp, announcement)
593                            .map_err(|_| {
594                                log::error!(
595                                    "Oracle attestation is not valid. pubkey={} event_id={}",
596                                    announcement.oracle_public_key,
597                                    announcement.oracle_event.event_id
598                                )
599                            })
600                            .ok()?;
601                        Some((*i, attestation))
602                    })
603                    .collect();
604                if attestations.len() >= contract_info.threshold {
605                    return Some((contract_info, adaptor_info, attestations));
606                }
607            }
608        }
609        None
610    }
611
612    fn check_confirmed_contract(&self, contract: &SignedContract) -> Result<(), Error> {
613        let closable_contract_info = self.get_closable_contract_info(contract);
614        if let Some((contract_info, adaptor_info, attestations)) = closable_contract_info {
615            let offer = &contract.accepted_contract.offered_contract;
616            let signer = self.signer_provider.derive_contract_signer(offer.keys_id)?;
617            let cet = crate::contract_updater::get_signed_cet(
618                &self.secp,
619                contract,
620                contract_info,
621                adaptor_info,
622                &attestations,
623                &signer,
624            )?;
625            match self.close_contract(
626                contract,
627                cet,
628                attestations.iter().map(|x| x.1.clone()).collect(),
629            ) {
630                Ok(closed_contract) => {
631                    self.store.update_contract(&closed_contract)?;
632                    return Ok(());
633                }
634                Err(e) => {
635                    warn!(
636                        "Failed to close contract {}: {}",
637                        contract.accepted_contract.get_contract_id_string(),
638                        e
639                    );
640                    return Err(e);
641                }
642            }
643        }
644
645        self.check_refund(contract)?;
646
647        Ok(())
648    }
649
650    /// Manually close a contract with the oracle attestations.
651    pub fn close_confirmed_contract(
652        &self,
653        contract_id: &ContractId,
654        attestations: Vec<(usize, OracleAttestation)>,
655    ) -> Result<Contract, Error> {
656        let contract = get_contract_in_state!(self, contract_id, Confirmed, None::<PublicKey>)?;
657        let contract_infos = &contract.accepted_contract.offered_contract.contract_info;
658        let adaptor_infos = &contract.accepted_contract.adaptor_infos;
659
660        // find the contract info that matches the attestations
661        if let Some((contract_info, adaptor_info)) =
662            contract_infos.iter().zip(adaptor_infos).find(|(c, _)| {
663                let matches = attestations
664                    .iter()
665                    .filter(|(i, a)| {
666                        c.oracle_announcements[*i].oracle_event.oracle_nonces == a.nonces()
667                    })
668                    .count();
669
670                matches >= c.threshold
671            })
672        {
673            let offer = &contract.accepted_contract.offered_contract;
674            let signer = self.signer_provider.derive_contract_signer(offer.keys_id)?;
675            let cet = crate::contract_updater::get_signed_cet(
676                &self.secp,
677                &contract,
678                contract_info,
679                adaptor_info,
680                &attestations,
681                &signer,
682            )?;
683
684            // Check that the lock time has passed
685            let time = bitcoin::absolute::Time::from_consensus(self.time.unix_time_now() as u32)
686                .expect("Time is not in valid range. This should never happen.");
687            let height = Height::from_consensus(self.blockchain.get_blockchain_height()? as u32)
688                .expect("Height is not in valid range. This should never happen.");
689            let locktime = cet.lock_time;
690
691            if !locktime.is_satisfied_by(height, time) {
692                return Err(Error::InvalidState(
693                    "CET lock time has not passed yet".to_string(),
694                ));
695            }
696
697            match self.close_contract(
698                &contract,
699                cet,
700                attestations.into_iter().map(|x| x.1).collect(),
701            ) {
702                Ok(closed_contract) => {
703                    self.store.update_contract(&closed_contract)?;
704                    Ok(closed_contract)
705                }
706                Err(e) => {
707                    warn!(
708                        "Failed to close contract {}: {e}",
709                        contract.accepted_contract.get_contract_id_string()
710                    );
711                    Err(e)
712                }
713            }
714        } else {
715            Err(Error::InvalidState(
716                "Attestations did not match contract infos".to_string(),
717            ))
718        }
719    }
720
721    fn check_preclosed_contracts(&self) -> Result<(), Error> {
722        for c in self.store.get_preclosed_contracts()? {
723            if let Err(e) = self.check_preclosed_contract(&c) {
724                error!(
725                    "Error checking pre-closed contract {}: {}",
726                    c.signed_contract.accepted_contract.get_contract_id_string(),
727                    e
728                )
729            }
730        }
731
732        Ok(())
733    }
734
735    fn check_preclosed_contract(&self, contract: &PreClosedContract) -> Result<(), Error> {
736        let broadcasted_txid = contract.signed_cet.compute_txid();
737        let confirmations = self
738            .blockchain
739            .get_transaction_confirmations(&broadcasted_txid)?;
740        if confirmations >= NB_CONFIRMATIONS {
741            let closed_contract = ClosedContract {
742                attestations: contract.attestations.clone(),
743                signed_cet: Some(contract.signed_cet.clone()),
744                contract_id: contract.signed_contract.accepted_contract.get_contract_id(),
745                temporary_contract_id: contract
746                    .signed_contract
747                    .accepted_contract
748                    .offered_contract
749                    .id,
750                counter_party_id: contract
751                    .signed_contract
752                    .accepted_contract
753                    .offered_contract
754                    .counter_party,
755                pnl: contract
756                    .signed_contract
757                    .accepted_contract
758                    .compute_pnl(&contract.signed_cet)?,
759            };
760            self.store
761                .update_contract(&Contract::Closed(closed_contract))?;
762        }
763
764        Ok(())
765    }
766
767    fn close_contract(
768        &self,
769        contract: &SignedContract,
770        signed_cet: Transaction,
771        attestations: Vec<OracleAttestation>,
772    ) -> Result<Contract, Error> {
773        let confirmations = self
774            .blockchain
775            .get_transaction_confirmations(&signed_cet.compute_txid())?;
776
777        if confirmations < 1 {
778            // TODO(tibo): if this fails because another tx is already in
779            // mempool or blockchain, we might have been cheated. There is
780            // not much to be done apart from possibly extracting a fraud
781            // proof but ideally it should be handled.
782            self.blockchain.send_transaction(&signed_cet)?;
783
784            let preclosed_contract = PreClosedContract {
785                signed_contract: contract.clone(),
786                attestations: Some(attestations),
787                signed_cet,
788            };
789
790            return Ok(Contract::PreClosed(preclosed_contract));
791        } else if confirmations < NB_CONFIRMATIONS {
792            let preclosed_contract = PreClosedContract {
793                signed_contract: contract.clone(),
794                attestations: Some(attestations),
795                signed_cet,
796            };
797
798            return Ok(Contract::PreClosed(preclosed_contract));
799        }
800
801        let closed_contract = ClosedContract {
802            attestations: Some(attestations.to_vec()),
803            pnl: contract.accepted_contract.compute_pnl(&signed_cet)?,
804            signed_cet: Some(signed_cet),
805            contract_id: contract.accepted_contract.get_contract_id(),
806            temporary_contract_id: contract.accepted_contract.offered_contract.id,
807            counter_party_id: contract.accepted_contract.offered_contract.counter_party,
808        };
809
810        Ok(Contract::Closed(closed_contract))
811    }
812
813    fn check_refund(&self, contract: &SignedContract) -> Result<(), Error> {
814        // TODO(tibo): should check for confirmation of refund before updating state
815        if contract
816            .accepted_contract
817            .dlc_transactions
818            .refund
819            .lock_time
820            .to_consensus_u32() as u64
821            <= self.time.unix_time_now()
822        {
823            let accepted_contract = &contract.accepted_contract;
824            let refund = accepted_contract.dlc_transactions.refund.clone();
825            let confirmations = self
826                .blockchain
827                .get_transaction_confirmations(&refund.compute_txid())?;
828            if confirmations == 0 {
829                let offer = &contract.accepted_contract.offered_contract;
830                let signer = self.signer_provider.derive_contract_signer(offer.keys_id)?;
831                let refund =
832                    crate::contract_updater::get_signed_refund(&self.secp, contract, &signer)?;
833                self.blockchain.send_transaction(&refund)?;
834            }
835
836            self.store
837                .update_contract(&Contract::Refunded(contract.clone()))?;
838        }
839
840        Ok(())
841    }
842
843    /// Function to call when we detect that a contract was closed by our counter party.
844    /// This will update the state of the contract and return the [`Contract`] object.
845    pub fn on_counterparty_close(
846        &mut self,
847        contract: &SignedContract,
848        closing_tx: Transaction,
849        confirmations: u32,
850    ) -> Result<Contract, Error> {
851        // check if the closing tx actually spends the funding output
852        if !closing_tx.input.iter().any(|i| {
853            i.previous_output
854                == contract
855                    .accepted_contract
856                    .dlc_transactions
857                    .get_fund_outpoint()
858        }) {
859            return Err(Error::InvalidParameters(
860                "Closing tx does not spend the funding tx".to_string(),
861            ));
862        }
863
864        // check if it is the refund tx (easy case)
865        if contract
866            .accepted_contract
867            .dlc_transactions
868            .refund
869            .compute_txid()
870            == closing_tx.compute_txid()
871        {
872            let refunded = Contract::Refunded(contract.clone());
873            self.store.update_contract(&refunded)?;
874            return Ok(refunded);
875        }
876
877        let contract = if confirmations < NB_CONFIRMATIONS {
878            Contract::PreClosed(PreClosedContract {
879                signed_contract: contract.clone(),
880                attestations: None, // todo in some cases we can get the attestations from the closing tx
881                signed_cet: closing_tx,
882            })
883        } else {
884            Contract::Closed(ClosedContract {
885                attestations: None, // todo in some cases we can get the attestations from the closing tx
886                pnl: contract.accepted_contract.compute_pnl(&closing_tx)?,
887                signed_cet: Some(closing_tx),
888                contract_id: contract.accepted_contract.get_contract_id(),
889                temporary_contract_id: contract.accepted_contract.offered_contract.id,
890                counter_party_id: contract.accepted_contract.offered_contract.counter_party,
891            })
892        };
893
894        self.store.update_contract(&contract)?;
895
896        Ok(contract)
897    }
898}
899
900impl<W: Deref, SP: Deref, B: Deref, S: Deref, O: Deref, T: Deref, F: Deref, X: ContractSigner>
901    Manager<W, Arc<CachedContractSignerProvider<SP, X>>, B, S, O, T, F, X>
902where
903    W::Target: Wallet,
904    SP::Target: ContractSignerProvider<Signer = X>,
905    B::Target: Blockchain,
906    S::Target: Storage,
907    O::Target: Oracle,
908    T::Target: Time,
909    F::Target: FeeEstimator,
910{
911    /// Create a new channel offer and return the [`dlc_messages::channel::OfferChannel`]
912    /// message to be sent to the `counter_party`.
913    pub fn offer_channel(
914        &self,
915        contract_input: &ContractInput,
916        counter_party: PublicKey,
917    ) -> Result<OfferChannel, Error> {
918        let oracle_announcements = contract_input
919            .contract_infos
920            .iter()
921            .map(|x| self.get_oracle_announcements(&x.oracles))
922            .collect::<Result<Vec<_>, Error>>()?;
923
924        let (offered_channel, offered_contract) = crate::channel_updater::offer_channel(
925            &self.secp,
926            contract_input,
927            &counter_party,
928            &oracle_announcements,
929            CET_NSEQUENCE,
930            REFUND_DELAY,
931            &self.wallet,
932            &self.signer_provider,
933            &self.blockchain,
934            &self.time,
935            crate::utils::get_new_temporary_id(),
936        )?;
937
938        let msg = offered_channel.get_offer_channel_msg(&offered_contract);
939
940        self.store.upsert_channel(
941            Channel::Offered(offered_channel),
942            Some(Contract::Offered(offered_contract)),
943        )?;
944
945        Ok(msg)
946    }
947
948    /// Reject a channel that was offered. Returns the [`dlc_messages::channel::Reject`]
949    /// message to be sent as well as the public key of the offering node.
950    pub fn reject_channel(&self, channel_id: &ChannelId) -> Result<(Reject, PublicKey), Error> {
951        let offered_channel =
952            get_channel_in_state!(self, channel_id, Offered, None as Option<PublicKey>)?;
953
954        if offered_channel.is_offer_party {
955            return Err(Error::InvalidState(
956                "Cannot reject channel initiated by us.".to_string(),
957            ));
958        }
959
960        let offered_contract = get_contract_in_state!(
961            self,
962            &offered_channel.offered_contract_id,
963            Offered,
964            None as Option<PublicKey>
965        )?;
966
967        let counterparty = offered_channel.counter_party;
968        self.store.upsert_channel(
969            Channel::Cancelled(offered_channel),
970            Some(Contract::Rejected(offered_contract)),
971        )?;
972
973        let msg = Reject {
974            channel_id: *channel_id,
975        };
976        Ok((msg, counterparty))
977    }
978
979    /// Accept a channel that was offered. Returns the [`dlc_messages::channel::AcceptChannel`]
980    /// message to be sent, the updated [`crate::ChannelId`] and [`crate::ContractId`],
981    /// as well as the public key of the offering node.
982    pub fn accept_channel(
983        &self,
984        channel_id: &ChannelId,
985    ) -> Result<(AcceptChannel, ChannelId, ContractId, PublicKey), Error> {
986        let offered_channel =
987            get_channel_in_state!(self, channel_id, Offered, None as Option<PublicKey>)?;
988
989        if offered_channel.is_offer_party {
990            return Err(Error::InvalidState(
991                "Cannot accept channel initiated by us.".to_string(),
992            ));
993        }
994
995        let offered_contract = get_contract_in_state!(
996            self,
997            &offered_channel.offered_contract_id,
998            Offered,
999            None as Option<PublicKey>
1000        )?;
1001
1002        let (accepted_channel, accepted_contract, accept_channel) =
1003            crate::channel_updater::accept_channel_offer(
1004                &self.secp,
1005                &offered_channel,
1006                &offered_contract,
1007                &self.wallet,
1008                &self.signer_provider,
1009                &self.blockchain,
1010            )?;
1011
1012        self.wallet.import_address(&Address::p2wsh(
1013            &accepted_contract.dlc_transactions.funding_script_pubkey,
1014            self.blockchain.get_network()?,
1015        ))?;
1016
1017        let channel_id = accepted_channel.channel_id;
1018        let contract_id = accepted_contract.get_contract_id();
1019        let counter_party = accepted_contract.offered_contract.counter_party;
1020
1021        self.store.upsert_channel(
1022            Channel::Accepted(accepted_channel),
1023            Some(Contract::Accepted(accepted_contract)),
1024        )?;
1025
1026        Ok((accept_channel, channel_id, contract_id, counter_party))
1027    }
1028
1029    /// Force close the channel with given [`crate::ChannelId`].
1030    pub fn force_close_channel(&self, channel_id: &ChannelId) -> Result<(), Error> {
1031        let channel = get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1032
1033        self.force_close_channel_internal(channel, true)
1034    }
1035
1036    /// Offer to settle the balance of a channel so that the counter party gets
1037    /// `counter_payout`. Returns the [`dlc_messages::channel::SettleChannelOffer`]
1038    /// message to be sent and the public key of the counter party node.
1039    pub fn settle_offer(
1040        &self,
1041        channel_id: &ChannelId,
1042        counter_payout: Amount,
1043    ) -> Result<(SettleOffer, PublicKey), Error> {
1044        let mut signed_channel =
1045            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1046
1047        let msg = crate::channel_updater::settle_channel_offer(
1048            &self.secp,
1049            &mut signed_channel,
1050            counter_payout,
1051            PEER_TIMEOUT,
1052            &self.signer_provider,
1053            &self.time,
1054        )?;
1055
1056        let counter_party = signed_channel.counter_party;
1057
1058        self.store
1059            .upsert_channel(Channel::Signed(signed_channel), None)?;
1060
1061        Ok((msg, counter_party))
1062    }
1063
1064    /// Accept a settlement offer, returning the [`SettleAccept`] message to be
1065    /// sent to the node with the returned [`PublicKey`] id.
1066    pub fn accept_settle_offer(
1067        &self,
1068        channel_id: &ChannelId,
1069    ) -> Result<(SettleAccept, PublicKey), Error> {
1070        let mut signed_channel =
1071            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1072
1073        let msg = crate::channel_updater::settle_channel_accept(
1074            &self.secp,
1075            &mut signed_channel,
1076            CET_NSEQUENCE,
1077            0,
1078            PEER_TIMEOUT,
1079            &self.signer_provider,
1080            &self.time,
1081            &self.chain_monitor,
1082        )?;
1083
1084        let counter_party = signed_channel.counter_party;
1085
1086        self.store
1087            .upsert_channel(Channel::Signed(signed_channel), None)?;
1088
1089        Ok((msg, counter_party))
1090    }
1091
1092    /// Returns a [`RenewOffer`] message as well as the [`PublicKey`] of the
1093    /// counter party's node to offer the establishment of a new contract in the
1094    /// channel.
1095    pub fn renew_offer(
1096        &self,
1097        channel_id: &ChannelId,
1098        counter_payout: Amount,
1099        contract_input: &ContractInput,
1100    ) -> Result<(RenewOffer, PublicKey), Error> {
1101        let mut signed_channel =
1102            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1103
1104        let oracle_announcements = contract_input
1105            .contract_infos
1106            .iter()
1107            .map(|x| self.get_oracle_announcements(&x.oracles))
1108            .collect::<Result<Vec<_>, Error>>()?;
1109
1110        let (msg, offered_contract) = crate::channel_updater::renew_offer(
1111            &self.secp,
1112            &mut signed_channel,
1113            contract_input,
1114            oracle_announcements,
1115            counter_payout,
1116            REFUND_DELAY,
1117            PEER_TIMEOUT,
1118            CET_NSEQUENCE,
1119            &self.signer_provider,
1120            &self.time,
1121        )?;
1122
1123        let counter_party = offered_contract.counter_party;
1124
1125        self.store.upsert_channel(
1126            Channel::Signed(signed_channel),
1127            Some(Contract::Offered(offered_contract)),
1128        )?;
1129
1130        Ok((msg, counter_party))
1131    }
1132
1133    /// Accept an offer to renew the contract in the channel. Returns the
1134    /// [`RenewAccept`] message to be sent to the peer with the returned
1135    /// [`PublicKey`] as node id.
1136    pub fn accept_renew_offer(
1137        &self,
1138        channel_id: &ChannelId,
1139    ) -> Result<(RenewAccept, PublicKey), Error> {
1140        let mut signed_channel =
1141            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1142        let offered_contract_id = signed_channel.get_contract_id().ok_or_else(|| {
1143            Error::InvalidState("Expected to have a contract id but did not.".to_string())
1144        })?;
1145
1146        let offered_contract = get_contract_in_state!(
1147            self,
1148            &offered_contract_id,
1149            Offered,
1150            None as Option<PublicKey>
1151        )?;
1152
1153        let (accepted_contract, msg) = crate::channel_updater::accept_channel_renewal(
1154            &self.secp,
1155            &mut signed_channel,
1156            &offered_contract,
1157            CET_NSEQUENCE,
1158            PEER_TIMEOUT,
1159            &self.signer_provider,
1160            &self.time,
1161        )?;
1162
1163        let counter_party = signed_channel.counter_party;
1164
1165        self.store.upsert_channel(
1166            Channel::Signed(signed_channel),
1167            Some(Contract::Accepted(accepted_contract)),
1168        )?;
1169
1170        Ok((msg, counter_party))
1171    }
1172
1173    /// Reject an offer to renew the contract in the channel. Returns the
1174    /// [`Reject`] message to be sent to the peer with the returned
1175    /// [`PublicKey`] node id.
1176    pub fn reject_renew_offer(&self, channel_id: &ChannelId) -> Result<(Reject, PublicKey), Error> {
1177        let mut signed_channel =
1178            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1179        let offered_contract_id = signed_channel.get_contract_id().ok_or_else(|| {
1180            Error::InvalidState(
1181                "Expected to be in a state with an associated contract id but was not.".to_string(),
1182            )
1183        })?;
1184
1185        let offered_contract = get_contract_in_state!(
1186            self,
1187            &offered_contract_id,
1188            Offered,
1189            None as Option<PublicKey>
1190        )?;
1191
1192        let reject_msg = crate::channel_updater::reject_renew_offer(&mut signed_channel)?;
1193
1194        let counter_party = signed_channel.counter_party;
1195
1196        self.store.upsert_channel(
1197            Channel::Signed(signed_channel),
1198            Some(Contract::Rejected(offered_contract)),
1199        )?;
1200
1201        Ok((reject_msg, counter_party))
1202    }
1203
1204    /// Returns a [`Reject`] message to be sent to the counter party of the
1205    /// channel to inform them that the local party does not wish to accept the
1206    /// proposed settle offer.
1207    pub fn reject_settle_offer(
1208        &self,
1209        channel_id: &ChannelId,
1210    ) -> Result<(Reject, PublicKey), Error> {
1211        let mut signed_channel =
1212            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1213
1214        let msg = crate::channel_updater::reject_settle_offer(&mut signed_channel)?;
1215
1216        let counter_party = signed_channel.counter_party;
1217
1218        self.store
1219            .upsert_channel(Channel::Signed(signed_channel), None)?;
1220
1221        Ok((msg, counter_party))
1222    }
1223
1224    /// Returns a [`CollaborativeCloseOffer`] message to be sent to the counter
1225    /// party of the channel and update the state of the channel. Note that the
1226    /// channel will be forced closed after a timeout if the counter party does
1227    /// not broadcast the close transaction.
1228    pub fn offer_collaborative_close(
1229        &self,
1230        channel_id: &ChannelId,
1231        counter_payout: Amount,
1232    ) -> Result<CollaborativeCloseOffer, Error> {
1233        let mut signed_channel =
1234            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1235
1236        let (msg, close_tx) = crate::channel_updater::offer_collaborative_close(
1237            &self.secp,
1238            &mut signed_channel,
1239            counter_payout,
1240            &self.signer_provider,
1241            &self.time,
1242        )?;
1243
1244        self.chain_monitor.lock().unwrap().add_tx(
1245            close_tx.compute_txid(),
1246            ChannelInfo {
1247                channel_id: *channel_id,
1248                tx_type: TxType::CollaborativeClose,
1249            },
1250        );
1251
1252        self.store
1253            .upsert_channel(Channel::Signed(signed_channel), None)?;
1254        self.store
1255            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
1256
1257        Ok(msg)
1258    }
1259
1260    /// Accept an offer to collaboratively close the channel. The close transaction
1261    /// will be broadcast and the state of the channel updated.
1262    pub fn accept_collaborative_close(&self, channel_id: &ChannelId) -> Result<(), Error> {
1263        let signed_channel =
1264            get_channel_in_state!(self, channel_id, Signed, None as Option<PublicKey>)?;
1265
1266        let closed_contract = if let Some(SignedChannelState::Established {
1267            signed_contract_id,
1268            ..
1269        }) = &signed_channel.roll_back_state
1270        {
1271            let counter_payout = get_signed_channel_state!(
1272                signed_channel,
1273                CollaborativeCloseOffered,
1274                counter_payout
1275            )?;
1276            Some(self.get_collaboratively_closed_contract(
1277                signed_contract_id,
1278                *counter_payout,
1279                true,
1280            )?)
1281        } else {
1282            None
1283        };
1284
1285        let (close_tx, closed_channel) = crate::channel_updater::accept_collaborative_close_offer(
1286            &self.secp,
1287            &signed_channel,
1288            &self.signer_provider,
1289        )?;
1290
1291        self.blockchain.send_transaction(&close_tx)?;
1292
1293        self.store.upsert_channel(closed_channel, None)?;
1294
1295        if let Some(closed_contract) = closed_contract {
1296            self.store
1297                .update_contract(&Contract::Closed(closed_contract))?;
1298        }
1299
1300        Ok(())
1301    }
1302
1303    fn try_finalize_closing_established_channel(
1304        &self,
1305        signed_channel: SignedChannel,
1306    ) -> Result<(), Error> {
1307        let (buffer_tx, contract_id, &is_initiator) = get_signed_channel_state!(
1308            signed_channel,
1309            Closing,
1310            buffer_transaction,
1311            contract_id,
1312            is_initiator
1313        )?;
1314
1315        if self
1316            .blockchain
1317            .get_transaction_confirmations(&buffer_tx.compute_txid())?
1318            >= CET_NSEQUENCE
1319        {
1320            log::info!(
1321                "Buffer transaction for contract {} has enough confirmations to spend from it",
1322                serialize_hex(&contract_id)
1323            );
1324
1325            let confirmed_contract =
1326                get_contract_in_state!(self, &contract_id, Confirmed, None as Option<PublicKey>)?;
1327
1328            let (contract_info, adaptor_info, attestations) = self
1329                .get_closable_contract_info(&confirmed_contract)
1330                .ok_or_else(|| {
1331                    Error::InvalidState("Could not get information to close contract".to_string())
1332                })?;
1333
1334            let (signed_cet, closed_channel) =
1335                crate::channel_updater::finalize_unilateral_close_settled_channel(
1336                    &self.secp,
1337                    &signed_channel,
1338                    &confirmed_contract,
1339                    contract_info,
1340                    &attestations,
1341                    adaptor_info,
1342                    &self.signer_provider,
1343                    is_initiator,
1344                )?;
1345
1346            let closed_contract = self.close_contract(
1347                &confirmed_contract,
1348                signed_cet,
1349                attestations.iter().map(|x| &x.1).cloned().collect(),
1350            )?;
1351
1352            self.chain_monitor
1353                .lock()
1354                .unwrap()
1355                .cleanup_channel(signed_channel.channel_id);
1356
1357            self.store
1358                .upsert_channel(closed_channel, Some(closed_contract))?;
1359        }
1360
1361        Ok(())
1362    }
1363
1364    fn on_offer_channel(
1365        &self,
1366        offer_channel: &OfferChannel,
1367        counter_party: PublicKey,
1368    ) -> Result<(), Error> {
1369        offer_channel.validate(
1370            &self.secp,
1371            REFUND_DELAY,
1372            REFUND_DELAY * 2,
1373            CET_NSEQUENCE,
1374            CET_NSEQUENCE * 2,
1375        )?;
1376
1377        let keys_id = self
1378            .signer_provider
1379            .derive_signer_key_id(false, offer_channel.temporary_contract_id);
1380        let (channel, contract) =
1381            OfferedChannel::from_offer_channel(offer_channel, counter_party, keys_id)?;
1382
1383        contract.validate()?;
1384
1385        if self
1386            .store
1387            .get_channel(&channel.temporary_channel_id)?
1388            .is_some()
1389        {
1390            return Err(Error::InvalidParameters(
1391                "Channel with identical idea already in store".to_string(),
1392            ));
1393        }
1394
1395        self.store
1396            .upsert_channel(Channel::Offered(channel), Some(Contract::Offered(contract)))?;
1397
1398        Ok(())
1399    }
1400
1401    fn on_accept_channel(
1402        &self,
1403        accept_channel: &AcceptChannel,
1404        peer_id: &PublicKey,
1405    ) -> Result<SignChannel, Error> {
1406        let offered_channel = get_channel_in_state!(
1407            self,
1408            &accept_channel.temporary_channel_id,
1409            Offered,
1410            Some(*peer_id)
1411        )?;
1412        let offered_contract = get_contract_in_state!(
1413            self,
1414            &offered_channel.offered_contract_id,
1415            Offered,
1416            Some(*peer_id)
1417        )?;
1418
1419        let (signed_channel, signed_contract, sign_channel) = {
1420            let res = crate::channel_updater::verify_and_sign_accepted_channel(
1421                &self.secp,
1422                &offered_channel,
1423                &offered_contract,
1424                accept_channel,
1425                //TODO(tibo): this should be parameterizable.
1426                CET_NSEQUENCE,
1427                &self.wallet,
1428                &self.signer_provider,
1429                &self.chain_monitor,
1430            );
1431
1432            match res {
1433                Ok(res) => res,
1434                Err(e) => {
1435                    let channel = crate::channel::FailedAccept {
1436                        temporary_channel_id: accept_channel.temporary_channel_id,
1437                        error_message: format!("Error validating accept channel: {}", e),
1438                        accept_message: accept_channel.clone(),
1439                        counter_party: *peer_id,
1440                    };
1441                    self.store
1442                        .upsert_channel(Channel::FailedAccept(channel), None)?;
1443                    return Err(e);
1444                }
1445            }
1446        };
1447
1448        self.wallet.import_address(&Address::p2wsh(
1449            &signed_contract
1450                .accepted_contract
1451                .dlc_transactions
1452                .funding_script_pubkey,
1453            self.blockchain.get_network()?,
1454        ))?;
1455
1456        if let SignedChannelState::Established {
1457            buffer_transaction, ..
1458        } = &signed_channel.state
1459        {
1460            self.chain_monitor.lock().unwrap().add_tx(
1461                buffer_transaction.compute_txid(),
1462                ChannelInfo {
1463                    channel_id: signed_channel.channel_id,
1464                    tx_type: TxType::BufferTx,
1465                },
1466            );
1467        } else {
1468            unreachable!();
1469        }
1470
1471        self.store.upsert_channel(
1472            Channel::Signed(signed_channel),
1473            Some(Contract::Signed(signed_contract)),
1474        )?;
1475
1476        self.store
1477            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
1478
1479        Ok(sign_channel)
1480    }
1481
1482    fn on_sign_channel(
1483        &self,
1484        sign_channel: &SignChannel,
1485        peer_id: &PublicKey,
1486    ) -> Result<(), Error> {
1487        let accepted_channel =
1488            get_channel_in_state!(self, &sign_channel.channel_id, Accepted, Some(*peer_id))?;
1489        let accepted_contract = get_contract_in_state!(
1490            self,
1491            &accepted_channel.accepted_contract_id,
1492            Accepted,
1493            Some(*peer_id)
1494        )?;
1495
1496        let (signed_channel, signed_contract, signed_fund_tx) = {
1497            let res = verify_signed_channel(
1498                &self.secp,
1499                &accepted_channel,
1500                &accepted_contract,
1501                sign_channel,
1502                &self.wallet,
1503                &self.chain_monitor,
1504            );
1505
1506            match res {
1507                Ok(res) => res,
1508                Err(e) => {
1509                    let channel = crate::channel::FailedSign {
1510                        channel_id: sign_channel.channel_id,
1511                        error_message: format!("Error validating accept channel: {}", e),
1512                        sign_message: sign_channel.clone(),
1513                        counter_party: *peer_id,
1514                    };
1515                    self.store
1516                        .upsert_channel(Channel::FailedSign(channel), None)?;
1517                    return Err(e);
1518                }
1519            }
1520        };
1521
1522        if let SignedChannelState::Established {
1523            buffer_transaction, ..
1524        } = &signed_channel.state
1525        {
1526            self.chain_monitor.lock().unwrap().add_tx(
1527                buffer_transaction.compute_txid(),
1528                ChannelInfo {
1529                    channel_id: signed_channel.channel_id,
1530                    tx_type: TxType::BufferTx,
1531                },
1532            );
1533        } else {
1534            unreachable!();
1535        }
1536
1537        self.blockchain.send_transaction(&signed_fund_tx)?;
1538
1539        self.store.upsert_channel(
1540            Channel::Signed(signed_channel),
1541            Some(Contract::Signed(signed_contract)),
1542        )?;
1543        self.store
1544            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
1545
1546        Ok(())
1547    }
1548
1549    fn on_settle_offer(
1550        &self,
1551        settle_offer: &SettleOffer,
1552        peer_id: &PublicKey,
1553    ) -> Result<Option<Reject>, Error> {
1554        let mut signed_channel =
1555            get_channel_in_state!(self, &settle_offer.channel_id, Signed, Some(*peer_id))?;
1556
1557        if let SignedChannelState::SettledOffered { .. } = signed_channel.state {
1558            return Ok(Some(Reject {
1559                channel_id: settle_offer.channel_id,
1560            }));
1561        }
1562
1563        crate::channel_updater::on_settle_offer(&mut signed_channel, settle_offer)?;
1564
1565        self.store
1566            .upsert_channel(Channel::Signed(signed_channel), None)?;
1567
1568        Ok(None)
1569    }
1570
1571    fn on_settle_accept(
1572        &self,
1573        settle_accept: &SettleAccept,
1574        peer_id: &PublicKey,
1575    ) -> Result<SettleConfirm, Error> {
1576        let mut signed_channel =
1577            get_channel_in_state!(self, &settle_accept.channel_id, Signed, Some(*peer_id))?;
1578
1579        let msg = crate::channel_updater::settle_channel_confirm(
1580            &self.secp,
1581            &mut signed_channel,
1582            settle_accept,
1583            CET_NSEQUENCE,
1584            0,
1585            PEER_TIMEOUT,
1586            &self.signer_provider,
1587            &self.time,
1588            &self.chain_monitor,
1589        )?;
1590
1591        self.store
1592            .upsert_channel(Channel::Signed(signed_channel), None)?;
1593
1594        Ok(msg)
1595    }
1596
1597    fn on_settle_confirm(
1598        &self,
1599        settle_confirm: &SettleConfirm,
1600        peer_id: &PublicKey,
1601    ) -> Result<SettleFinalize, Error> {
1602        let mut signed_channel =
1603            get_channel_in_state!(self, &settle_confirm.channel_id, Signed, Some(*peer_id))?;
1604        let &own_payout = get_signed_channel_state!(signed_channel, SettledAccepted, own_payout)?;
1605        let (prev_buffer_tx, own_buffer_adaptor_signature, is_offer, signed_contract_id) = get_signed_channel_rollback_state!(
1606            signed_channel,
1607            Established,
1608            buffer_transaction,
1609            own_buffer_adaptor_signature,
1610            is_offer,
1611            signed_contract_id
1612        )?;
1613
1614        let prev_buffer_txid = prev_buffer_tx.compute_txid();
1615        let own_buffer_adaptor_signature = *own_buffer_adaptor_signature;
1616        let is_offer = *is_offer;
1617        let signed_contract_id = *signed_contract_id;
1618
1619        let msg = crate::channel_updater::settle_channel_finalize(
1620            &self.secp,
1621            &mut signed_channel,
1622            settle_confirm,
1623            &self.signer_provider,
1624        )?;
1625
1626        self.chain_monitor.lock().unwrap().add_tx(
1627            prev_buffer_txid,
1628            ChannelInfo {
1629                channel_id: signed_channel.channel_id,
1630                tx_type: TxType::Revoked {
1631                    update_idx: signed_channel.update_idx + 1,
1632                    own_adaptor_signature: own_buffer_adaptor_signature,
1633                    is_offer,
1634                    revoked_tx_type: RevokedTxType::Buffer,
1635                },
1636            },
1637        );
1638
1639        let closed_contract = Contract::Closed(self.get_collaboratively_closed_contract(
1640            &signed_contract_id,
1641            own_payout,
1642            true,
1643        )?);
1644
1645        self.store
1646            .upsert_channel(Channel::Signed(signed_channel), Some(closed_contract))?;
1647        self.store
1648            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
1649
1650        Ok(msg)
1651    }
1652
1653    fn on_settle_finalize(
1654        &self,
1655        settle_finalize: &SettleFinalize,
1656        peer_id: &PublicKey,
1657    ) -> Result<(), Error> {
1658        let mut signed_channel =
1659            get_channel_in_state!(self, &settle_finalize.channel_id, Signed, Some(*peer_id))?;
1660        let &own_payout = get_signed_channel_state!(signed_channel, SettledConfirmed, own_payout)?;
1661        let (buffer_tx, own_buffer_adaptor_signature, is_offer, signed_contract_id) = get_signed_channel_rollback_state!(
1662            signed_channel,
1663            Established,
1664            buffer_transaction,
1665            own_buffer_adaptor_signature,
1666            is_offer,
1667            signed_contract_id
1668        )?;
1669
1670        let own_buffer_adaptor_signature = *own_buffer_adaptor_signature;
1671        let is_offer = *is_offer;
1672        let buffer_txid = buffer_tx.compute_txid();
1673        let signed_contract_id = *signed_contract_id;
1674
1675        crate::channel_updater::settle_channel_on_finalize(
1676            &self.secp,
1677            &mut signed_channel,
1678            settle_finalize,
1679        )?;
1680
1681        self.chain_monitor.lock().unwrap().add_tx(
1682            buffer_txid,
1683            ChannelInfo {
1684                channel_id: signed_channel.channel_id,
1685                tx_type: TxType::Revoked {
1686                    update_idx: signed_channel.update_idx + 1,
1687                    own_adaptor_signature: own_buffer_adaptor_signature,
1688                    is_offer,
1689                    revoked_tx_type: RevokedTxType::Buffer,
1690                },
1691            },
1692        );
1693
1694        let closed_contract = Contract::Closed(self.get_collaboratively_closed_contract(
1695            &signed_contract_id,
1696            own_payout,
1697            true,
1698        )?);
1699        self.store
1700            .upsert_channel(Channel::Signed(signed_channel), Some(closed_contract))?;
1701        self.store
1702            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
1703
1704        Ok(())
1705    }
1706
1707    fn on_renew_offer(
1708        &self,
1709        renew_offer: &RenewOffer,
1710        peer_id: &PublicKey,
1711    ) -> Result<Option<Reject>, Error> {
1712        let mut signed_channel =
1713            get_channel_in_state!(self, &renew_offer.channel_id, Signed, Some(*peer_id))?;
1714
1715        // Received a renew offer when we already sent one, we reject it.
1716        if let SignedChannelState::RenewOffered { is_offer, .. } = signed_channel.state {
1717            if is_offer {
1718                return Ok(Some(Reject {
1719                    channel_id: renew_offer.channel_id,
1720                }));
1721            }
1722        }
1723
1724        let offered_contract = crate::channel_updater::on_renew_offer(
1725            &mut signed_channel,
1726            renew_offer,
1727            PEER_TIMEOUT,
1728            &self.time,
1729        )?;
1730
1731        self.store.create_contract(&offered_contract)?;
1732        self.store
1733            .upsert_channel(Channel::Signed(signed_channel), None)?;
1734
1735        Ok(None)
1736    }
1737
1738    fn on_renew_accept(
1739        &self,
1740        renew_accept: &RenewAccept,
1741        peer_id: &PublicKey,
1742    ) -> Result<RenewConfirm, Error> {
1743        let mut signed_channel =
1744            get_channel_in_state!(self, &renew_accept.channel_id, Signed, Some(*peer_id))?;
1745        let offered_contract_id = signed_channel.get_contract_id().ok_or_else(|| {
1746            Error::InvalidState(
1747                "Expected to be in a state with an associated contract id but was not.".to_string(),
1748            )
1749        })?;
1750
1751        let offered_contract =
1752            get_contract_in_state!(self, &offered_contract_id, Offered, Some(*peer_id))?;
1753
1754        let (signed_contract, msg) = crate::channel_updater::verify_renew_accept_and_confirm(
1755            &self.secp,
1756            renew_accept,
1757            &mut signed_channel,
1758            &offered_contract,
1759            CET_NSEQUENCE,
1760            PEER_TIMEOUT,
1761            &self.wallet,
1762            &self.signer_provider,
1763            &self.time,
1764        )?;
1765
1766        // Directly confirmed as we're in a channel the fund tx is already confirmed.
1767        self.store.upsert_channel(
1768            Channel::Signed(signed_channel),
1769            Some(Contract::Confirmed(signed_contract)),
1770        )?;
1771
1772        Ok(msg)
1773    }
1774
1775    fn on_renew_confirm(
1776        &self,
1777        renew_confirm: &RenewConfirm,
1778        peer_id: &PublicKey,
1779    ) -> Result<RenewFinalize, Error> {
1780        let mut signed_channel =
1781            get_channel_in_state!(self, &renew_confirm.channel_id, Signed, Some(*peer_id))?;
1782        let own_payout = get_signed_channel_state!(signed_channel, RenewAccepted, own_payout)?;
1783        let contract_id = signed_channel.get_contract_id().ok_or_else(|| {
1784            Error::InvalidState(
1785                "Expected to be in a state with an associated contract id but was not.".to_string(),
1786            )
1787        })?;
1788
1789        let (tx_type, prev_tx_id, closed_contract) = match signed_channel
1790            .roll_back_state
1791            .as_ref()
1792            .expect("to have a rollback state")
1793        {
1794            SignedChannelState::Established {
1795                own_buffer_adaptor_signature,
1796                buffer_transaction,
1797                signed_contract_id,
1798                ..
1799            } => {
1800                let closed_contract = Contract::Closed(self.get_collaboratively_closed_contract(
1801                    signed_contract_id,
1802                    *own_payout,
1803                    true,
1804                )?);
1805                (
1806                    TxType::Revoked {
1807                        update_idx: signed_channel.update_idx,
1808                        own_adaptor_signature: *own_buffer_adaptor_signature,
1809                        is_offer: false,
1810                        revoked_tx_type: RevokedTxType::Buffer,
1811                    },
1812                    buffer_transaction.compute_txid(),
1813                    Some(closed_contract),
1814                )
1815            }
1816            SignedChannelState::Settled {
1817                settle_tx,
1818                own_settle_adaptor_signature,
1819                ..
1820            } => (
1821                TxType::Revoked {
1822                    update_idx: signed_channel.update_idx,
1823                    own_adaptor_signature: *own_settle_adaptor_signature,
1824                    is_offer: false,
1825                    revoked_tx_type: RevokedTxType::Settle,
1826                },
1827                settle_tx.compute_txid(),
1828                None,
1829            ),
1830            s => {
1831                return Err(Error::InvalidState(format!(
1832                    "Expected rollback state Established or Revoked but found {s:?}"
1833                )))
1834            }
1835        };
1836        let accepted_contract =
1837            get_contract_in_state!(self, &contract_id, Accepted, Some(*peer_id))?;
1838
1839        let (signed_contract, msg) = crate::channel_updater::verify_renew_confirm_and_finalize(
1840            &self.secp,
1841            &mut signed_channel,
1842            &accepted_contract,
1843            renew_confirm,
1844            PEER_TIMEOUT,
1845            &self.time,
1846            &self.wallet,
1847            &self.signer_provider,
1848            &self.chain_monitor,
1849        )?;
1850
1851        self.chain_monitor.lock().unwrap().add_tx(
1852            prev_tx_id,
1853            ChannelInfo {
1854                channel_id: signed_channel.channel_id,
1855                tx_type,
1856            },
1857        );
1858
1859        // Directly confirmed as we're in a channel the fund tx is already confirmed.
1860        self.store.upsert_channel(
1861            Channel::Signed(signed_channel),
1862            Some(Contract::Confirmed(signed_contract)),
1863        )?;
1864
1865        self.store
1866            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
1867
1868        if let Some(closed_contract) = closed_contract {
1869            self.store.update_contract(&closed_contract)?;
1870        }
1871
1872        Ok(msg)
1873    }
1874
1875    fn on_renew_finalize(
1876        &self,
1877        renew_finalize: &RenewFinalize,
1878        peer_id: &PublicKey,
1879    ) -> Result<RenewRevoke, Error> {
1880        let mut signed_channel =
1881            get_channel_in_state!(self, &renew_finalize.channel_id, Signed, Some(*peer_id))?;
1882        let own_payout = get_signed_channel_state!(signed_channel, RenewConfirmed, own_payout)?;
1883
1884        let (tx_type, prev_tx_id, closed_contract) = match signed_channel
1885            .roll_back_state
1886            .as_ref()
1887            .expect("to have a rollback state")
1888        {
1889            SignedChannelState::Established {
1890                own_buffer_adaptor_signature,
1891                buffer_transaction,
1892                signed_contract_id,
1893                ..
1894            } => {
1895                let closed_contract = self.get_collaboratively_closed_contract(
1896                    signed_contract_id,
1897                    *own_payout,
1898                    true,
1899                )?;
1900                (
1901                    TxType::Revoked {
1902                        update_idx: signed_channel.update_idx,
1903                        own_adaptor_signature: *own_buffer_adaptor_signature,
1904                        is_offer: false,
1905                        revoked_tx_type: RevokedTxType::Buffer,
1906                    },
1907                    buffer_transaction.compute_txid(),
1908                    Some(Contract::Closed(closed_contract)),
1909                )
1910            }
1911            SignedChannelState::Settled {
1912                settle_tx,
1913                own_settle_adaptor_signature,
1914                ..
1915            } => (
1916                TxType::Revoked {
1917                    update_idx: signed_channel.update_idx,
1918                    own_adaptor_signature: *own_settle_adaptor_signature,
1919                    is_offer: false,
1920                    revoked_tx_type: RevokedTxType::Settle,
1921                },
1922                settle_tx.compute_txid(),
1923                None,
1924            ),
1925            s => {
1926                return Err(Error::InvalidState(format!(
1927                    "Expected rollback state of Established or Settled but was {s:?}"
1928                )))
1929            }
1930        };
1931
1932        let msg = crate::channel_updater::renew_channel_on_finalize(
1933            &self.secp,
1934            &mut signed_channel,
1935            renew_finalize,
1936            &self.signer_provider,
1937        )?;
1938
1939        self.chain_monitor.lock().unwrap().add_tx(
1940            prev_tx_id,
1941            ChannelInfo {
1942                channel_id: signed_channel.channel_id,
1943                tx_type,
1944            },
1945        );
1946
1947        let buffer_tx =
1948            get_signed_channel_state!(signed_channel, Established, ref buffer_transaction)?;
1949
1950        self.chain_monitor.lock().unwrap().add_tx(
1951            buffer_tx.compute_txid(),
1952            ChannelInfo {
1953                channel_id: signed_channel.channel_id,
1954                tx_type: TxType::BufferTx,
1955            },
1956        );
1957
1958        self.store
1959            .upsert_channel(Channel::Signed(signed_channel), None)?;
1960        self.store
1961            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
1962
1963        if let Some(closed_contract) = closed_contract {
1964            self.store.update_contract(&closed_contract)?;
1965        }
1966
1967        Ok(msg)
1968    }
1969
1970    fn on_renew_revoke(
1971        &self,
1972        renew_revoke: &RenewRevoke,
1973        peer_id: &PublicKey,
1974    ) -> Result<(), Error> {
1975        let mut signed_channel =
1976            get_channel_in_state!(self, &renew_revoke.channel_id, Signed, Some(*peer_id))?;
1977
1978        crate::channel_updater::renew_channel_on_revoke(
1979            &self.secp,
1980            &mut signed_channel,
1981            renew_revoke,
1982        )?;
1983
1984        self.store
1985            .upsert_channel(Channel::Signed(signed_channel), None)
1986    }
1987
1988    fn on_collaborative_close_offer(
1989        &self,
1990        close_offer: &CollaborativeCloseOffer,
1991        peer_id: &PublicKey,
1992    ) -> Result<(), Error> {
1993        let mut signed_channel =
1994            get_channel_in_state!(self, &close_offer.channel_id, Signed, Some(*peer_id))?;
1995
1996        crate::channel_updater::on_collaborative_close_offer(
1997            &mut signed_channel,
1998            close_offer,
1999            PEER_TIMEOUT,
2000            &self.time,
2001        )?;
2002
2003        self.store
2004            .upsert_channel(Channel::Signed(signed_channel), None)?;
2005
2006        Ok(())
2007    }
2008
2009    fn on_reject(&self, reject: &Reject, counter_party: &PublicKey) -> Result<(), Error> {
2010        let channel = self.store.get_channel(&reject.channel_id)?;
2011
2012        if let Some(channel) = channel {
2013            if channel.get_counter_party_id() != *counter_party {
2014                return Err(Error::InvalidParameters(format!(
2015                    "Peer {:02x?} is not involved with {} {:02x?}.",
2016                    counter_party,
2017                    stringify!(Channel),
2018                    channel.get_id()
2019                )));
2020            }
2021            match channel {
2022                Channel::Offered(offered_channel) => {
2023                    let offered_contract = get_contract_in_state!(
2024                        self,
2025                        &offered_channel.offered_contract_id,
2026                        Offered,
2027                        None as Option<PublicKey>
2028                    )?;
2029                    let utxos = offered_contract
2030                        .funding_inputs
2031                        .iter()
2032                        .map(|funding_input| {
2033                            let txid = Transaction::consensus_decode(
2034                                &mut funding_input.prev_tx.as_slice(),
2035                            )
2036                            .expect("Transaction Decode Error")
2037                            .compute_txid();
2038                            let vout = funding_input.prev_tx_vout;
2039                            OutPoint { txid, vout }
2040                        })
2041                        .collect::<Vec<_>>();
2042
2043                    self.wallet.unreserve_utxos(&utxos)?;
2044
2045                    // remove rejected channel, since nothing has been confirmed on chain yet.
2046                    self.store.upsert_channel(
2047                        Channel::Cancelled(offered_channel),
2048                        Some(Contract::Rejected(offered_contract)),
2049                    )?;
2050                }
2051                Channel::Signed(mut signed_channel) => {
2052                    let contract = match signed_channel.state {
2053                        SignedChannelState::RenewOffered {
2054                            offered_contract_id,
2055                            ..
2056                        } => {
2057                            let offered_contract = get_contract_in_state!(
2058                                self,
2059                                &offered_contract_id,
2060                                Offered,
2061                                None::<PublicKey>
2062                            )?;
2063                            Some(Contract::Rejected(offered_contract))
2064                        }
2065                        _ => None,
2066                    };
2067
2068                    crate::channel_updater::on_reject(&mut signed_channel)?;
2069
2070                    self.store
2071                        .upsert_channel(Channel::Signed(signed_channel), contract)?;
2072                }
2073                channel => {
2074                    return Err(Error::InvalidState(format!(
2075                        "Not in a state adequate to receive a reject message. {:?}",
2076                        channel
2077                    )))
2078                }
2079            }
2080        } else {
2081            warn!(
2082                "Couldn't find rejected dlc channel with id: {}",
2083                reject.channel_id.to_lower_hex_string()
2084            );
2085        }
2086
2087        Ok(())
2088    }
2089
2090    fn channel_checks(&self) -> Result<(), Error> {
2091        let established_closing_channels = self
2092            .store
2093            .get_signed_channels(Some(SignedChannelStateType::Closing))?;
2094
2095        for channel in established_closing_channels {
2096            if let Err(e) = self.try_finalize_closing_established_channel(channel) {
2097                error!("Error trying to close established channel: {}", e);
2098            }
2099        }
2100
2101        if let Err(e) = self.check_for_timed_out_channels() {
2102            error!("Error checking timed out channels {}", e);
2103        }
2104        self.check_for_watched_tx()
2105    }
2106
2107    fn check_for_timed_out_channels(&self) -> Result<(), Error> {
2108        check_for_timed_out_channels!(self, RenewOffered);
2109        check_for_timed_out_channels!(self, RenewAccepted);
2110        check_for_timed_out_channels!(self, RenewConfirmed);
2111        check_for_timed_out_channels!(self, SettledOffered);
2112        check_for_timed_out_channels!(self, SettledAccepted);
2113        check_for_timed_out_channels!(self, SettledConfirmed);
2114
2115        Ok(())
2116    }
2117
2118    pub(crate) fn process_watched_txs(
2119        &self,
2120        watched_txs: Vec<(Transaction, ChannelInfo)>,
2121    ) -> Result<(), Error> {
2122        for (tx, channel_info) in watched_txs {
2123            let mut signed_channel = match get_channel_in_state!(
2124                self,
2125                &channel_info.channel_id,
2126                Signed,
2127                None as Option<PublicKey>
2128            ) {
2129                Ok(c) => c,
2130                Err(e) => {
2131                    error!(
2132                        "Could not retrieve channel {:?}: {}",
2133                        channel_info.channel_id, e
2134                    );
2135                    continue;
2136                }
2137            };
2138
2139            let persist = match channel_info.tx_type {
2140                TxType::BufferTx => {
2141                    // TODO(tibo): should only considered closed after some confirmations.
2142                    // Ideally should save previous state, and maybe restore in
2143                    // case of reorg, though if the counter party has sent the
2144                    // tx to close the channel it is unlikely that the tx will
2145                    // not be part of a future block.
2146
2147                    let contract_id = signed_channel
2148                        .get_contract_id()
2149                        .expect("to have a contract id");
2150                    let mut state = SignedChannelState::Closing {
2151                        buffer_transaction: tx.clone(),
2152                        is_initiator: false,
2153                        contract_id,
2154                        keys_id: signed_channel.keys_id().ok_or_else(|| {
2155                            Error::InvalidState("Expected to have keys_id.".to_string())
2156                        })?,
2157                    };
2158                    std::mem::swap(&mut signed_channel.state, &mut state);
2159
2160                    signed_channel.roll_back_state = Some(state);
2161
2162                    self.store
2163                        .upsert_channel(Channel::Signed(signed_channel), None)?;
2164
2165                    false
2166                }
2167                TxType::Revoked {
2168                    update_idx,
2169                    own_adaptor_signature,
2170                    is_offer,
2171                    revoked_tx_type,
2172                } => {
2173                    let secret = signed_channel
2174                        .counter_party_commitment_secrets
2175                        .get_secret(update_idx)
2176                        .expect("to be able to retrieve the per update secret");
2177                    let counter_per_update_secret = SecretKey::from_slice(&secret)
2178                        .expect("to be able to parse the counter per update secret.");
2179
2180                    let per_update_seed_pk = signed_channel.own_per_update_seed;
2181
2182                    let per_update_seed_sk = self
2183                        .signer_provider
2184                        .get_secret_key_for_pubkey(&per_update_seed_pk)?;
2185
2186                    let per_update_secret = SecretKey::from_slice(&build_commitment_secret(
2187                        per_update_seed_sk.as_ref(),
2188                        update_idx,
2189                    ))
2190                    .expect("a valid secret key.");
2191
2192                    let per_update_point =
2193                        PublicKey::from_secret_key(&self.secp, &per_update_secret);
2194
2195                    let own_revocation_params = signed_channel.own_points.get_revokable_params(
2196                        &self.secp,
2197                        &signed_channel.counter_points.revocation_basepoint,
2198                        &per_update_point,
2199                    );
2200
2201                    let counter_per_update_point =
2202                        PublicKey::from_secret_key(&self.secp, &counter_per_update_secret);
2203
2204                    let base_own_sk = self
2205                        .signer_provider
2206                        .get_secret_key_for_pubkey(&signed_channel.own_points.own_basepoint)?;
2207
2208                    let own_sk = derive_private_key(&self.secp, &per_update_point, &base_own_sk);
2209
2210                    let counter_revocation_params =
2211                        signed_channel.counter_points.get_revokable_params(
2212                            &self.secp,
2213                            &signed_channel.own_points.revocation_basepoint,
2214                            &counter_per_update_point,
2215                        );
2216
2217                    let witness = if signed_channel.own_params.fund_pubkey
2218                        < signed_channel.counter_params.fund_pubkey
2219                    {
2220                        tx.input[0].witness.to_vec().remove(1)
2221                    } else {
2222                        tx.input[0].witness.to_vec().remove(2)
2223                    };
2224
2225                    let sig_data = witness
2226                        .iter()
2227                        .take(witness.len() - 1)
2228                        .cloned()
2229                        .collect::<Vec<_>>();
2230                    let own_sig = Signature::from_der(&sig_data)?;
2231
2232                    let counter_sk = own_adaptor_signature.recover(
2233                        &self.secp,
2234                        &own_sig,
2235                        &counter_revocation_params.publish_pk.inner,
2236                    )?;
2237
2238                    let own_revocation_base_secret =
2239                        &self.signer_provider.get_secret_key_for_pubkey(
2240                            &signed_channel.own_points.revocation_basepoint,
2241                        )?;
2242
2243                    let counter_revocation_sk = derive_private_revocation_key(
2244                        &self.secp,
2245                        &counter_per_update_secret,
2246                        own_revocation_base_secret,
2247                    );
2248
2249                    let (offer_params, accept_params) = if is_offer {
2250                        (&own_revocation_params, &counter_revocation_params)
2251                    } else {
2252                        (&counter_revocation_params, &own_revocation_params)
2253                    };
2254
2255                    let fee_rate_per_vb: u64 = (self.fee_estimator.get_est_sat_per_1000_weight(
2256                        lightning::chain::chaininterface::ConfirmationTarget::UrgentOnChainSweep,
2257                    ) / 250)
2258                        .into();
2259
2260                    let signed_tx = match revoked_tx_type {
2261                        RevokedTxType::Buffer => {
2262                            dlc::channel::create_and_sign_punish_buffer_transaction(
2263                                &self.secp,
2264                                offer_params,
2265                                accept_params,
2266                                &own_sk,
2267                                &counter_sk,
2268                                &counter_revocation_sk,
2269                                &tx,
2270                                &self.wallet.get_new_address()?,
2271                                0,
2272                                fee_rate_per_vb,
2273                            )?
2274                        }
2275                        RevokedTxType::Settle => {
2276                            dlc::channel::create_and_sign_punish_settle_transaction(
2277                                &self.secp,
2278                                offer_params,
2279                                accept_params,
2280                                &own_sk,
2281                                &counter_sk,
2282                                &counter_revocation_sk,
2283                                &tx,
2284                                &self.wallet.get_new_address()?,
2285                                CET_NSEQUENCE,
2286                                0,
2287                                fee_rate_per_vb,
2288                                is_offer,
2289                            )?
2290                        }
2291                    };
2292
2293                    self.blockchain.send_transaction(&signed_tx)?;
2294
2295                    let closed_channel = Channel::ClosedPunished(ClosedPunishedChannel {
2296                        counter_party: signed_channel.counter_party,
2297                        temporary_channel_id: signed_channel.temporary_channel_id,
2298                        channel_id: signed_channel.channel_id,
2299                        punish_txid: signed_tx.compute_txid(),
2300                    });
2301
2302                    //TODO(tibo): should probably make sure the tx is confirmed somewhere before
2303                    //stop watching the cheating tx.
2304                    self.chain_monitor
2305                        .lock()
2306                        .unwrap()
2307                        .cleanup_channel(signed_channel.channel_id);
2308                    self.store.upsert_channel(closed_channel, None)?;
2309                    true
2310                }
2311                TxType::CollaborativeClose => {
2312                    if let Some(SignedChannelState::Established {
2313                        signed_contract_id, ..
2314                    }) = signed_channel.roll_back_state
2315                    {
2316                        let counter_payout = get_signed_channel_state!(
2317                            signed_channel,
2318                            CollaborativeCloseOffered,
2319                            counter_payout
2320                        )?;
2321                        let closed_contract = self.get_collaboratively_closed_contract(
2322                            &signed_contract_id,
2323                            *counter_payout,
2324                            false,
2325                        )?;
2326                        self.store
2327                            .update_contract(&Contract::Closed(closed_contract))?;
2328                    }
2329                    let closed_channel = Channel::CollaborativelyClosed(ClosedChannel {
2330                        counter_party: signed_channel.counter_party,
2331                        temporary_channel_id: signed_channel.temporary_channel_id,
2332                        channel_id: signed_channel.channel_id,
2333                    });
2334                    self.chain_monitor
2335                        .lock()
2336                        .unwrap()
2337                        .cleanup_channel(signed_channel.channel_id);
2338                    self.store.upsert_channel(closed_channel, None)?;
2339                    true
2340                }
2341                TxType::SettleTx => {
2342                    let closed_channel = Channel::CounterClosed(ClosedChannel {
2343                        counter_party: signed_channel.counter_party,
2344                        temporary_channel_id: signed_channel.temporary_channel_id,
2345                        channel_id: signed_channel.channel_id,
2346                    });
2347                    self.chain_monitor
2348                        .lock()
2349                        .unwrap()
2350                        .cleanup_channel(signed_channel.channel_id);
2351                    self.store.upsert_channel(closed_channel, None)?;
2352                    true
2353                }
2354                TxType::Cet => {
2355                    let contract_id = signed_channel.get_contract_id();
2356                    let closed_channel = {
2357                        match &signed_channel.state {
2358                            SignedChannelState::Closing { is_initiator, .. } => {
2359                                if *is_initiator {
2360                                    Channel::Closed(ClosedChannel {
2361                                        counter_party: signed_channel.counter_party,
2362                                        temporary_channel_id: signed_channel.temporary_channel_id,
2363                                        channel_id: signed_channel.channel_id,
2364                                    })
2365                                } else {
2366                                    Channel::CounterClosed(ClosedChannel {
2367                                        counter_party: signed_channel.counter_party,
2368                                        temporary_channel_id: signed_channel.temporary_channel_id,
2369                                        channel_id: signed_channel.channel_id,
2370                                    })
2371                                }
2372                            }
2373                            _ => {
2374                                error!("Saw spending of buffer transaction without being in closing state");
2375                                Channel::Closed(ClosedChannel {
2376                                    counter_party: signed_channel.counter_party,
2377                                    temporary_channel_id: signed_channel.temporary_channel_id,
2378                                    channel_id: signed_channel.channel_id,
2379                                })
2380                            }
2381                        }
2382                    };
2383
2384                    self.chain_monitor
2385                        .lock()
2386                        .unwrap()
2387                        .cleanup_channel(signed_channel.channel_id);
2388
2389                    let pre_closed_contract = contract_id
2390                        .map(|contract_id| {
2391                            self.store.get_contract(&contract_id).map(|contract| {
2392                                contract.map(|contract| match contract {
2393                                    Contract::Confirmed(signed_contract) => {
2394                                        Some(Contract::PreClosed(PreClosedContract {
2395                                            signed_contract,
2396                                            attestations: None,
2397                                            signed_cet: tx.clone(),
2398                                        }))
2399                                    }
2400                                    _ => None,
2401                                })
2402                            })
2403                        })
2404                        .transpose()?
2405                        .flatten()
2406                        .flatten();
2407
2408                    self.store
2409                        .upsert_channel(closed_channel, pre_closed_contract)?;
2410
2411                    true
2412                }
2413            };
2414
2415            if persist {
2416                self.store
2417                    .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
2418            }
2419        }
2420        Ok(())
2421    }
2422
2423    fn check_for_watched_tx(&self) -> Result<(), Error> {
2424        let confirmed_txs = self.chain_monitor.lock().unwrap().confirmed_txs();
2425
2426        self.process_watched_txs(confirmed_txs)?;
2427
2428        self.get_store()
2429            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
2430
2431        Ok(())
2432    }
2433
2434    fn force_close_channel_internal(
2435        &self,
2436        mut channel: SignedChannel,
2437        is_initiator: bool,
2438    ) -> Result<(), Error> {
2439        match &channel.state {
2440            SignedChannelState::Established {
2441                counter_buffer_adaptor_signature,
2442                buffer_transaction,
2443                ..
2444            } => {
2445                let counter_buffer_adaptor_signature = *counter_buffer_adaptor_signature;
2446                let buffer_transaction = buffer_transaction.clone();
2447                self.initiate_unilateral_close_established_channel(
2448                    channel,
2449                    is_initiator,
2450                    counter_buffer_adaptor_signature,
2451                    buffer_transaction,
2452                )
2453            }
2454            SignedChannelState::RenewFinalized {
2455                buffer_transaction,
2456                offer_buffer_adaptor_signature,
2457                ..
2458            } => {
2459                let offer_buffer_adaptor_signature = *offer_buffer_adaptor_signature;
2460                let buffer_transaction = buffer_transaction.clone();
2461                self.initiate_unilateral_close_established_channel(
2462                    channel,
2463                    is_initiator,
2464                    offer_buffer_adaptor_signature,
2465                    buffer_transaction,
2466                )
2467            }
2468            SignedChannelState::Settled { .. } => self.close_settled_channel(channel, is_initiator),
2469            SignedChannelState::SettledOffered { .. }
2470            | SignedChannelState::SettledReceived { .. }
2471            | SignedChannelState::SettledAccepted { .. }
2472            | SignedChannelState::SettledConfirmed { .. }
2473            | SignedChannelState::RenewOffered { .. }
2474            | SignedChannelState::RenewAccepted { .. }
2475            | SignedChannelState::RenewConfirmed { .. }
2476            | SignedChannelState::CollaborativeCloseOffered { .. } => {
2477                channel.state = channel
2478                    .roll_back_state
2479                    .take()
2480                    .expect("to have a rollback state");
2481                self.force_close_channel_internal(channel, is_initiator)
2482            }
2483            SignedChannelState::Closing { .. } => Err(Error::InvalidState(
2484                "Channel is already closing.".to_string(),
2485            )),
2486        }
2487    }
2488
2489    /// Initiate the unilateral closing of a channel that has been established.
2490    fn initiate_unilateral_close_established_channel(
2491        &self,
2492        mut signed_channel: SignedChannel,
2493        is_initiator: bool,
2494        buffer_adaptor_signature: EcdsaAdaptorSignature,
2495        buffer_transaction: Transaction,
2496    ) -> Result<(), Error> {
2497        let keys_id = signed_channel.keys_id().ok_or_else(|| {
2498            Error::InvalidState("Expected to be in a state with an associated keys id.".to_string())
2499        })?;
2500
2501        crate::channel_updater::initiate_unilateral_close_established_channel(
2502            &self.secp,
2503            &mut signed_channel,
2504            buffer_adaptor_signature,
2505            keys_id,
2506            buffer_transaction,
2507            &self.signer_provider,
2508            is_initiator,
2509        )?;
2510
2511        let buffer_transaction =
2512            get_signed_channel_state!(signed_channel, Closing, ref buffer_transaction)?;
2513
2514        self.blockchain.send_transaction(buffer_transaction)?;
2515
2516        self.chain_monitor
2517            .lock()
2518            .unwrap()
2519            .remove_tx(&buffer_transaction.compute_txid());
2520
2521        self.store
2522            .upsert_channel(Channel::Signed(signed_channel), None)?;
2523
2524        self.store
2525            .persist_chain_monitor(&self.chain_monitor.lock().unwrap())?;
2526
2527        Ok(())
2528    }
2529
2530    /// Unilaterally close a channel that has been settled.
2531    fn close_settled_channel(
2532        &self,
2533        signed_channel: SignedChannel,
2534        is_initiator: bool,
2535    ) -> Result<(), Error> {
2536        let (settle_tx, closed_channel) = crate::channel_updater::close_settled_channel(
2537            &self.secp,
2538            &signed_channel,
2539            &self.signer_provider,
2540            is_initiator,
2541        )?;
2542
2543        if self
2544            .blockchain
2545            .get_transaction_confirmations(&settle_tx.compute_txid())
2546            .unwrap_or(0)
2547            == 0
2548        {
2549            self.blockchain.send_transaction(&settle_tx)?;
2550        }
2551
2552        self.chain_monitor
2553            .lock()
2554            .unwrap()
2555            .cleanup_channel(signed_channel.channel_id);
2556
2557        self.store.upsert_channel(closed_channel, None)?;
2558
2559        Ok(())
2560    }
2561
2562    fn get_collaboratively_closed_contract(
2563        &self,
2564        contract_id: &ContractId,
2565        payout: Amount,
2566        is_own_payout: bool,
2567    ) -> Result<ClosedContract, Error> {
2568        let contract = get_contract_in_state!(self, contract_id, Confirmed, None::<PublicKey>)?;
2569        let own_collateral = if contract.accepted_contract.offered_contract.is_offer_party {
2570            contract
2571                .accepted_contract
2572                .offered_contract
2573                .offer_params
2574                .collateral
2575        } else {
2576            contract.accepted_contract.accept_params.collateral
2577        };
2578        let own_payout = if is_own_payout {
2579            payout
2580        } else {
2581            contract.accepted_contract.offered_contract.total_collateral - payout
2582        };
2583        let pnl =
2584            SignedAmount::from_sat(own_payout.to_sat() as i64 - own_collateral.to_sat() as i64);
2585        Ok(ClosedContract {
2586            attestations: None,
2587            signed_cet: None,
2588            contract_id: *contract_id,
2589            temporary_contract_id: contract.accepted_contract.offered_contract.id,
2590            counter_party_id: contract.accepted_contract.offered_contract.counter_party,
2591            pnl,
2592        })
2593    }
2594}
2595
2596#[cfg(test)]
2597mod test {
2598    use bitcoin::Amount;
2599    use dlc_messages::Message;
2600    use mocks::{
2601        dlc_manager::{manager::Manager, CachedContractSignerProvider, Oracle, SimpleSigner},
2602        memory_storage_provider::MemoryStorage,
2603        mock_blockchain::MockBlockchain,
2604        mock_oracle_provider::MockOracle,
2605        mock_time::MockTime,
2606        mock_wallet::MockWallet,
2607    };
2608    use secp256k1_zkp::{PublicKey, XOnlyPublicKey};
2609    use std::{collections::HashMap, rc::Rc, sync::Arc};
2610
2611    type TestManager = Manager<
2612        Rc<MockWallet>,
2613        Arc<CachedContractSignerProvider<Rc<MockWallet>, SimpleSigner>>,
2614        Rc<MockBlockchain>,
2615        Rc<MemoryStorage>,
2616        Rc<MockOracle>,
2617        Rc<MockTime>,
2618        Rc<MockBlockchain>,
2619        SimpleSigner,
2620    >;
2621
2622    fn get_manager() -> TestManager {
2623        let blockchain = Rc::new(MockBlockchain::new());
2624        let store = Rc::new(MemoryStorage::new());
2625        let wallet = Rc::new(MockWallet::new(
2626            &blockchain,
2627            &(0..100)
2628                .map(|x| Amount::from_sat(x as u64 * 1000000))
2629                .collect::<Vec<_>>(),
2630        ));
2631
2632        let oracle_list = (0..5).map(|_| MockOracle::new()).collect::<Vec<_>>();
2633        let oracles: HashMap<XOnlyPublicKey, _> = oracle_list
2634            .into_iter()
2635            .map(|x| (x.get_public_key(), Rc::new(x)))
2636            .collect();
2637        let time = Rc::new(MockTime {});
2638
2639        mocks::mock_time::set_time(0);
2640
2641        Manager::new(
2642            wallet.clone(),
2643            wallet,
2644            blockchain.clone(),
2645            store,
2646            oracles,
2647            time,
2648            blockchain,
2649        )
2650        .unwrap()
2651    }
2652
2653    fn pubkey() -> PublicKey {
2654        "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
2655            .parse()
2656            .unwrap()
2657    }
2658
2659    #[test]
2660    fn reject_offer_with_existing_contract_id() {
2661        let offer_message = Message::Offer(
2662            serde_json::from_str(include_str!("../test_inputs/offer_contract.json")).unwrap(),
2663        );
2664
2665        let manager = get_manager();
2666
2667        manager
2668            .on_dlc_message(&offer_message, pubkey())
2669            .expect("To accept the first offer message");
2670
2671        manager
2672            .on_dlc_message(&offer_message, pubkey())
2673            .expect_err("To reject the second offer message");
2674    }
2675
2676    #[test]
2677    fn reject_channel_offer_with_existing_channel_id() {
2678        let offer_message = Message::OfferChannel(
2679            serde_json::from_str(include_str!("../test_inputs/offer_channel.json")).unwrap(),
2680        );
2681
2682        let manager = get_manager();
2683
2684        manager
2685            .on_dlc_message(&offer_message, pubkey())
2686            .expect("To accept the first offer message");
2687
2688        manager
2689            .on_dlc_message(&offer_message, pubkey())
2690            .expect_err("To reject the second offer message");
2691    }
2692}