dlc-messages 0.7.1

Structs and serialization for the Discreet Log Contract (DLC) protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! Data structure and functions related to peer communication.

// Coding conventions
#![forbid(unsafe_code)]
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![deny(dead_code)]
#![deny(unused_imports)]
#![deny(missing_docs)]

extern crate bitcoin;
extern crate dlc;
extern crate lightning;
extern crate secp256k1_zkp;
#[macro_use]
pub mod ser_macros;
pub mod ser_impls;

#[cfg(any(test, feature = "use-serde"))]
extern crate serde;

#[cfg(test)]
extern crate serde_json;

pub mod channel;
pub mod contract_msgs;
pub mod message_handler;
pub mod oracle_msgs;
pub mod segmentation;

#[cfg(any(test, feature = "use-serde"))]
pub mod serde_utils;

use std::fmt::Display;

use crate::ser_impls::{read_ecdsa_adaptor_signature, write_ecdsa_adaptor_signature};
use bitcoin::ScriptBuf;
use bitcoin::{consensus::Decodable, OutPoint, Transaction};
use channel::{
    AcceptChannel, CollaborativeCloseOffer, OfferChannel, Reject, RenewAccept, RenewConfirm,
    RenewFinalize, RenewOffer, RenewRevoke, SettleAccept, SettleConfirm, SettleFinalize,
    SettleOffer, SignChannel,
};
use contract_msgs::ContractInfo;
use dlc::{Error, TxInputInfo};
use lightning::ln::msgs::DecodeError;
use lightning::ln::wire::Type;
use lightning::util::ser::{Readable, Writeable, Writer};
use secp256k1_zkp::Verification;
use secp256k1_zkp::{ecdsa::Signature, EcdsaAdaptorSignature, PublicKey, Secp256k1};
use segmentation::{SegmentChunk, SegmentStart};

macro_rules! impl_type {
    ($const_name: ident, $type_name: ident, $type_val: expr) => {
        /// The type prefix for an [`$type_name`] message.
        pub const $const_name: u16 = $type_val;

        impl Type for $type_name {
            fn type_id(&self) -> u16 {
                $const_name
            }
        }
    };
}

impl_type!(OFFER_TYPE, OfferDlc, 42778);
impl_type!(ACCEPT_TYPE, AcceptDlc, 42780);
impl_type!(SIGN_TYPE, SignDlc, 42782);
impl_type!(OFFER_CHANNEL_TYPE, OfferChannel, 43000);
impl_type!(ACCEPT_CHANNEL_TYPE, AcceptChannel, 43002);
impl_type!(SIGN_CHANNEL_TYPE, SignChannel, 43004);
impl_type!(SETTLE_CHANNEL_OFFER_TYPE, SettleOffer, 43006);
impl_type!(SETTLE_CHANNEL_ACCEPT_TYPE, SettleAccept, 43008);
impl_type!(SETTLE_CHANNEL_CONFIRM_TYPE, SettleConfirm, 43010);
impl_type!(SETTLE_CHANNEL_FINALIZE_TYPE, SettleFinalize, 43012);
impl_type!(RENEW_CHANNEL_OFFER_TYPE, RenewOffer, 43014);
impl_type!(RENEW_CHANNEL_ACCEPT_TYPE, RenewAccept, 43016);
impl_type!(RENEW_CHANNEL_CONFIRM_TYPE, RenewConfirm, 43018);
impl_type!(RENEW_CHANNEL_FINALIZE_TYPE, RenewFinalize, 43020);
impl_type!(RENEW_CHANNEL_REVOKE_TYPE, RenewRevoke, 43026);
impl_type!(
    COLLABORATIVE_CLOSE_OFFER_TYPE,
    CollaborativeCloseOffer,
    43022
);
impl_type!(REJECT, Reject, 43024);

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Contains information about a specific input to be used in a funding transaction,
/// as well as its corresponding on-chain UTXO.
pub struct FundingInput {
    /// Serial id used for input ordering in the funding transaction.
    pub input_serial_id: u64,
    #[cfg_attr(
        feature = "use-serde",
        serde(
            serialize_with = "crate::serde_utils::serialize_hex",
            deserialize_with = "crate::serde_utils::deserialize_hex_string"
        )
    )]
    /// The previous transaction used by the associated input in serialized format.
    pub prev_tx: Vec<u8>,
    /// The vout of the output used by the associated input.
    pub prev_tx_vout: u32,
    /// The sequence number to use for the input.
    pub sequence: u32,
    /// The maximum witness length that can be used to spend the previous UTXO.
    pub max_witness_len: u16,
    /// The redeem script of the previous UTXO.
    pub redeem_script: ScriptBuf,
}

impl_dlc_writeable!(FundingInput, {
    (input_serial_id, writeable),
    (prev_tx, vec),
    (prev_tx_vout, writeable),
    (sequence, writeable),
    (max_witness_len, writeable),
    (redeem_script, writeable)
});

impl From<&FundingInput> for TxInputInfo {
    fn from(funding_input: &FundingInput) -> TxInputInfo {
        TxInputInfo {
            outpoint: OutPoint {
                txid: Transaction::consensus_decode(&mut funding_input.prev_tx.as_slice())
                    .expect("Transaction Decode Error")
                    .compute_txid(),
                vout: funding_input.prev_tx_vout,
            },
            max_witness_len: (funding_input.max_witness_len as usize),
            redeem_script: funding_input.redeem_script.clone(),
            serial_id: funding_input.input_serial_id,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Contains an adaptor signature for a CET input and its associated DLEQ proof.
pub struct CetAdaptorSignature {
    /// The signature.
    pub signature: EcdsaAdaptorSignature,
}

impl_dlc_writeable!(CetAdaptorSignature, {
     (signature, { cb_writeable, write_ecdsa_adaptor_signature, read_ecdsa_adaptor_signature })
});

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Contains a list of adaptor signature for a number of CET inputs.
pub struct CetAdaptorSignatures {
    /// The set of signatures.
    pub ecdsa_adaptor_signatures: Vec<CetAdaptorSignature>,
}

impl From<&[EcdsaAdaptorSignature]> for CetAdaptorSignatures {
    fn from(signatures: &[EcdsaAdaptorSignature]) -> Self {
        CetAdaptorSignatures {
            ecdsa_adaptor_signatures: signatures
                .iter()
                .map(|x| CetAdaptorSignature { signature: *x })
                .collect(),
        }
    }
}

impl From<&CetAdaptorSignatures> for Vec<EcdsaAdaptorSignature> {
    fn from(signatures: &CetAdaptorSignatures) -> Vec<EcdsaAdaptorSignature> {
        signatures
            .ecdsa_adaptor_signatures
            .iter()
            .map(|x| x.signature)
            .collect::<Vec<_>>()
    }
}

impl_dlc_writeable!(CetAdaptorSignatures, { (ecdsa_adaptor_signatures, vec) });

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Contains the witness elements to use to make a funding transaction input valid.
pub struct FundingSignature {
    /// The set of witness elements.
    pub witness_elements: Vec<WitnessElement>,
}

impl_dlc_writeable!(FundingSignature, { (witness_elements, vec) });

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Contains a list of witness elements to satisfy the spending conditions of
/// funding inputs.
pub struct FundingSignatures {
    /// The set of funding signatures.
    pub funding_signatures: Vec<FundingSignature>,
}

impl_dlc_writeable!(FundingSignatures, { (funding_signatures, vec) });

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Contains serialized data representing a single witness stack element.
pub struct WitnessElement {
    #[cfg_attr(
        feature = "use-serde",
        serde(
            serialize_with = "crate::serde_utils::serialize_hex",
            deserialize_with = "crate::serde_utils::deserialize_hex_string"
        )
    )]
    /// The serialized witness data.
    pub witness: Vec<u8>,
}

impl_dlc_writeable!(WitnessElement, { (witness, vec) });

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Fields used to negotiate contract information.
pub enum NegotiationFields {
    /// Negotiation for single event based contract.
    Single(SingleNegotiationFields),
    /// Negotiation for multiple event based contract.
    Disjoint(DisjointNegotiationFields),
}

impl_dlc_writeable_enum!(NegotiationFields, (0, Single), (1, Disjoint);;;);

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Negotiation fields for contract based on a single event.
pub struct SingleNegotiationFields {
    /// Proposed rounding intervals.
    rounding_intervals: contract_msgs::RoundingIntervals,
}

impl_dlc_writeable!(SingleNegotiationFields, { (rounding_intervals, writeable) });

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Negotiation fields for contract based on multiple events.
pub struct DisjointNegotiationFields {
    /// The negotiation fields for each contract event.
    negotiation_fields: Vec<NegotiationFields>,
}

impl_dlc_writeable!(DisjointNegotiationFields, { (negotiation_fields, vec) });

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
/// Contains information about a party wishing to enter into a DLC with
/// another party. The contained information is sufficient for any other party
/// to create a set of transactions representing the contract and its terms.
pub struct OfferDlc {
    /// The version of the protocol used by the peer.
    pub protocol_version: u32,
    /// Feature flags to be used for the offered contract.
    pub contract_flags: u8,
    #[cfg_attr(
        feature = "use-serde",
        serde(
            serialize_with = "crate::serde_utils::serialize_hex",
            deserialize_with = "crate::serde_utils::deserialize_hex_array"
        )
    )]
    /// The identifier of the chain on which the contract will be settled.
    pub chain_hash: [u8; 32],
    #[cfg_attr(
        feature = "use-serde",
        serde(
            serialize_with = "crate::serde_utils::serialize_hex",
            deserialize_with = "crate::serde_utils::deserialize_hex_array"
        )
    )]
    /// Temporary contract id to identify the contract.
    pub temporary_contract_id: [u8; 32],
    /// Information about the contract event, payouts and oracles.
    pub contract_info: ContractInfo,
    /// The public key of the offerer to be used to lock the collateral.
    pub funding_pubkey: PublicKey,
    /// The SPK where the offerer will receive their payout.
    pub payout_spk: ScriptBuf,
    /// Serial id to order CET outputs.
    pub payout_serial_id: u64,
    /// Collateral of the offer party.
    pub offer_collateral: u64,
    /// Inputs used by the offer party to fund the contract.
    pub funding_inputs: Vec<FundingInput>,
    /// The SPK where the offer party will receive their change.
    pub change_spk: ScriptBuf,
    /// Serial id to order funding transaction outputs.
    pub change_serial_id: u64,
    /// Serial id to order funding transaction outputs.
    pub fund_output_serial_id: u64,
    /// The fee rate to use to compute transaction fees for this contract.
    pub fee_rate_per_vb: u64,
    /// The lock time for the CETs.
    pub cet_locktime: u32,
    /// The lock time for the refund transactions.
    pub refund_locktime: u32,
}

impl OfferDlc {
    /// Returns the total collateral locked in the contract.
    pub fn get_total_collateral(&self) -> u64 {
        match &self.contract_info {
            ContractInfo::SingleContractInfo(single) => single.total_collateral,
            ContractInfo::DisjointContractInfo(disjoint) => disjoint.total_collateral,
        }
    }

    /// Returns whether the message satisfies validity requirements.
    pub fn validate<C: Verification>(
        &self,
        secp: &Secp256k1<C>,
        min_timeout_interval: u32,
        max_timeout_interval: u32,
    ) -> Result<(), Error> {
        match &self.contract_info {
            ContractInfo::SingleContractInfo(s) => s.contract_info.oracle_info.validate(secp)?,
            ContractInfo::DisjointContractInfo(d) => {
                if d.contract_infos.len() < 2 {
                    return Err(Error::InvalidArgument);
                }

                for c in &d.contract_infos {
                    c.oracle_info.validate(secp)?;
                }
            }
        }

        let closest_maturity_date = self.contract_info.get_closest_maturity_date();
        let valid_dates = self.cet_locktime <= closest_maturity_date
            && closest_maturity_date + min_timeout_interval <= self.refund_locktime
            && self.refund_locktime <= closest_maturity_date + max_timeout_interval;
        if !valid_dates {
            return Err(Error::InvalidArgument);
        }

        Ok(())
    }
}

impl_dlc_writeable!(OfferDlc, {
        (protocol_version, writeable),
        (contract_flags, writeable),
        (chain_hash, writeable),
        (temporary_contract_id, writeable),
        (contract_info, writeable),
        (funding_pubkey, writeable),
        (payout_spk, writeable),
        (payout_serial_id, writeable),
        (offer_collateral, writeable),
        (funding_inputs, vec),
        (change_spk, writeable),
        (change_serial_id, writeable),
        (fund_output_serial_id, writeable),
        (fee_rate_per_vb, writeable),
        (cet_locktime, writeable),
        (refund_locktime, writeable)
});

/// Contains information about a party wishing to accept a DLC offer. The contained
/// information is sufficient for the offering party to re-build the set of
/// transactions representing the contract and its terms, and guarantees the offering
/// party that they can safely provide signatures for their funding input.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct AcceptDlc {
    /// The version of the protocol used by the peer.
    pub protocol_version: u32,
    #[cfg_attr(
        feature = "use-serde",
        serde(
            serialize_with = "crate::serde_utils::serialize_hex",
            deserialize_with = "crate::serde_utils::deserialize_hex_array"
        )
    )]
    /// The temporary contract id for the contract.
    pub temporary_contract_id: [u8; 32],
    /// The collateral input by the accept party.
    pub accept_collateral: u64,
    /// The public key of the accept party to be used to lock the collateral.
    pub funding_pubkey: PublicKey,
    /// The SPK where the accept party will receive their payout.
    pub payout_spk: ScriptBuf,
    /// Serial id to order CET outputs.
    pub payout_serial_id: u64,
    /// Inputs used by the accept party to fund the contract.
    pub funding_inputs: Vec<FundingInput>,
    /// The SPK where the accept party will receive their change.
    pub change_spk: ScriptBuf,
    /// Serial id to order funding transaction outputs.
    pub change_serial_id: u64,
    /// The set of adaptor signatures from the accept party.
    pub cet_adaptor_signatures: CetAdaptorSignatures,
    /// The refund signature of the accept party.
    pub refund_signature: Signature,
    /// The negotiation fields from the accept party.
    pub negotiation_fields: Option<NegotiationFields>,
}

impl_dlc_writeable!(AcceptDlc, {
    (protocol_version, writeable),
    (temporary_contract_id, writeable),
    (accept_collateral, writeable),
    (funding_pubkey, writeable),
    (payout_spk, writeable),
    (payout_serial_id, writeable),
    (funding_inputs, vec),
    (change_spk, writeable),
    (change_serial_id, writeable),
    (cet_adaptor_signatures, writeable),
    (refund_signature, writeable),
    (negotiation_fields, option)
});

/// Contains all the required signatures for the DLC transactions from the offering
/// party.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "use-serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SignDlc {
    /// The version of the protocol used by the peer.
    pub protocol_version: u32,
    #[cfg_attr(
        feature = "use-serde",
        serde(
            serialize_with = "crate::serde_utils::serialize_hex",
            deserialize_with = "crate::serde_utils::deserialize_hex_array"
        )
    )]
    /// The id of the contract referred to by this message.
    pub contract_id: [u8; 32],
    /// The set of adaptor signatures from the offer party.
    pub cet_adaptor_signatures: CetAdaptorSignatures,
    /// The refund signature from the offer party.
    pub refund_signature: Signature,
    /// The set of funding signatures from the offer party.
    pub funding_signatures: FundingSignatures,
}

impl_dlc_writeable!(SignDlc, {
    (protocol_version, writeable),
    (contract_id, writeable),
    (cet_adaptor_signatures, writeable),
    (refund_signature, writeable),
    (funding_signatures, writeable)
});

#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub enum Message {
    Offer(OfferDlc),
    Accept(AcceptDlc),
    Sign(SignDlc),
    OfferChannel(OfferChannel),
    AcceptChannel(AcceptChannel),
    SignChannel(SignChannel),
    SettleOffer(SettleOffer),
    SettleAccept(SettleAccept),
    SettleConfirm(SettleConfirm),
    SettleFinalize(SettleFinalize),
    RenewOffer(RenewOffer),
    RenewAccept(RenewAccept),
    RenewConfirm(RenewConfirm),
    RenewFinalize(RenewFinalize),
    RenewRevoke(RenewRevoke),
    CollaborativeCloseOffer(CollaborativeCloseOffer),
    Reject(Reject),
}

macro_rules! impl_type_writeable_for_enum {
    ($type_name: ident, {$($variant_name: ident),*}) => {
       impl Type for $type_name {
           fn type_id(&self) -> u16 {
               match self {
                   $($type_name::$variant_name(v) => v.type_id(),)*
               }
           }
       }

       impl Writeable for $type_name {
            fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::lightning::io::Error> {
                match self {
                   $($type_name::$variant_name(v) => v.write(writer),)*
                }
            }
       }
    };
}

impl_type_writeable_for_enum!(Message,
{
    Offer,
    Accept,
    Sign,
    OfferChannel,
    AcceptChannel,
    SignChannel,
    SettleOffer,
    SettleAccept,
    SettleConfirm,
    SettleFinalize,
    RenewOffer,
    RenewAccept,
    RenewConfirm,
    RenewFinalize,
    RenewRevoke,
    CollaborativeCloseOffer,
    Reject
});

#[derive(Debug, Clone)]
/// Wrapper for DLC related message and segmentation related messages.
pub enum WireMessage {
    /// Message related to establishment of a DLC contract.
    Message(Message),
    /// Message indicating an incoming segmented message.
    SegmentStart(SegmentStart),
    /// Message providing a chunk of a segmented message.
    SegmentChunk(SegmentChunk),
}

impl Display for WireMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Self::Message(_) => "Message",
            Self::SegmentStart(_) => "SegmentStart",
            Self::SegmentChunk(_) => "SegmentChunk",
        };
        f.write_str(name)
    }
}

impl_type_writeable_for_enum!(WireMessage, { Message, SegmentStart, SegmentChunk });

#[cfg(test)]
mod tests {
    use secp256k1_zkp::SECP256K1;

    use super::*;

    macro_rules! roundtrip_test {
        ($type: ty, $input: ident) => {
            let msg: $type = serde_json::from_str(&$input).unwrap();
            test_roundtrip(msg);
        };
    }

    fn test_roundtrip<T: Writeable + Readable + PartialEq + std::fmt::Debug>(msg: T) {
        let mut buf = Vec::new();
        msg.write(&mut buf).expect("Error writing message");
        let mut cursor = lightning::io::Cursor::new(buf);
        let deser = Readable::read(&mut cursor).expect("Error reading message");
        assert_eq!(msg, deser);
    }

    #[test]
    fn offer_msg_roundtrip() {
        let input = include_str!("./test_inputs/offer_msg.json");
        roundtrip_test!(OfferDlc, input);
    }

    #[test]
    fn accept_msg_roundtrip() {
        let input = include_str!("./test_inputs/accept_msg.json");
        roundtrip_test!(AcceptDlc, input);
    }

    #[test]
    fn sign_msg_roundtrip() {
        let input = include_str!("./test_inputs/sign_msg.json");
        roundtrip_test!(SignDlc, input);
    }

    #[test]
    fn valid_offer_message_passes_validation() {
        let input = include_str!("./test_inputs/offer_msg.json");
        let valid_offer: OfferDlc = serde_json::from_str(input).unwrap();
        valid_offer
            .validate(SECP256K1, 86400 * 7, 86400 * 14)
            .expect("to validate valid offer messages.");
    }

    #[test]
    fn invalid_offer_messages_fail_validation() {
        let input = include_str!("./test_inputs/offer_msg.json");
        let offer: OfferDlc = serde_json::from_str(input).unwrap();

        let mut invalid_maturity = offer.clone();
        invalid_maturity.cet_locktime += 3;

        let mut too_short_timeout = offer.clone();
        too_short_timeout.refund_locktime -= 100;

        let mut too_long_timeout = offer;
        too_long_timeout.refund_locktime -= 100;

        for invalid in &[invalid_maturity, too_short_timeout, too_long_timeout] {
            invalid
                .validate(SECP256K1, 86400 * 7, 86400 * 14)
                .expect_err("Should not pass validation of invalid offer message.");
        }
    }

    #[test]
    fn disjoint_contract_offer_messages_fail_validation() {
        let input = include_str!("./test_inputs/offer_msg_disjoint.json");
        let offer: OfferDlc = serde_json::from_str(input).unwrap();

        let mut no_contract_input = offer.clone();
        no_contract_input.contract_info =
            ContractInfo::DisjointContractInfo(contract_msgs::DisjointContractInfo {
                total_collateral: 100000000,
                contract_infos: vec![],
            });

        let mut single_contract_input = offer.clone();
        single_contract_input.contract_info =
            if let ContractInfo::DisjointContractInfo(d) = offer.contract_info {
                let mut single = d;
                single.contract_infos.remove(1);
                ContractInfo::DisjointContractInfo(single)
            } else {
                panic!("Expected disjoint contract info.");
            };

        for invalid in &[no_contract_input, single_contract_input] {
            invalid
                .validate(SECP256K1, 86400 * 7, 86400 * 14)
                .expect_err("Should not pass validation of invalid offer message.");
        }
    }
}