vls_protocol/
msgs.rs

1#![allow(missing_docs)]
2#![allow(deprecated)]
3
4use alloc::boxed::Box;
5use alloc::vec::Vec;
6use as_any::AsAny;
7use bitcoin::blockdata::block::Header as BlockHeader;
8use bitcoin::consensus::{Decodable, Encodable};
9use bitcoin::{BlockHash, OutPoint, Transaction, Txid};
10use core::fmt::{Debug, Formatter};
11use core::ops::Deref;
12use serde_bolt::{bitcoin, ReadBigEndian};
13use txoo::bitcoin::hash_types::FilterHeader;
14
15use crate::error::{Error, Result};
16use crate::model::*;
17use crate::psbt::{PsbtWrapper, StreamedPSBT};
18use bitcoin_consensus_derive::{Decodable, Encodable};
19#[cfg(feature = "developer")]
20use bolt_derive::SerBoltTlvOptions;
21use bolt_derive::{ReadMessage, SerBolt};
22#[cfg(feature = "developer")]
23use lightning_signer::lightning;
24use lightning_signer::prelude::*;
25use serde_bolt::{
26    io, io::Read, io::Write, take::Take, to_vec, Array, ArrayBE, LargeOctets, Octets, WireString,
27    WithSize,
28};
29use txoo::proof::{ProofType, TxoProof};
30
31use log::error;
32
33const MAX_MESSAGE_SIZE: u32 = 128 * 1024;
34
35// Error codes used to demarcate Message::SignerError instances
36pub const CODE_ORPHAN_BLOCK: u16 = 401;
37
38// Notable hsmd protocol versions
39pub const PROTOCOL_VERSION_REVOKE: u32 = 5; // RevokeCommitmentTx was split from ValidateCommitmentTx
40pub const PROTOCOL_VERSION_NO_SECRET: u32 = 6; // GetPerCommitmentPoint no longer returns secret
41
42/// Our default protcol version
43/// (see also [`HsmdInit::hsm_wire_min_version`], etc.)
44pub const DEFAULT_MAX_PROTOCOL_VERSION: u32 = PROTOCOL_VERSION_NO_SECRET;
45
46/// Our minimum protcol version
47pub const MIN_PROTOCOL_VERSION: u32 = 2;
48
49/// Serialize a message with a type prefix, in BOLT style
50pub trait SerBolt: Debug + AsAny + Send {
51    fn as_vec(&self) -> Vec<u8>;
52    fn name(&self) -> &'static str;
53}
54
55pub trait DeBolt: Debug + Sized + Encodable + Decodable {
56    const TYPE: u16;
57    fn from_vec(ser: Vec<u8>) -> Result<Self>;
58}
59
60/// Developer setup for testing
61/// Must preceed `HsmdInit{,2}` message
62#[cfg(feature = "developer")]
63#[derive(SerBolt, Debug, Encodable, Decodable)]
64#[message_id(90)]
65pub struct HsmdDevPreinit {
66    pub derivation_style: u8,
67    pub network_name: WireString,
68    pub seed: Option<DevSecret>,
69    pub allowlist: Array<WireString>,
70}
71
72#[cfg(feature = "developer")]
73#[derive(SerBolt, Debug, Encodable, Decodable)]
74#[message_id(190)]
75pub struct HsmdDevPreinitReply {
76    /// The derived nodeid (or generated if none was supplied)
77    pub node_id: PubKey,
78}
79
80/// Developer setup for testing
81/// Must preceed `HsmdInit{,2}` message
82#[cfg(feature = "developer")]
83#[derive(SerBolt, Debug, Encodable, Decodable)]
84#[message_id(99)]
85pub struct HsmdDevPreinit2 {
86    pub options: HsmdDevPreinit2Options,
87}
88
89/// TLV encoded options for HsmdDevPreinit2
90#[cfg(feature = "developer")]
91#[derive(SerBoltTlvOptions, Default, Debug, Clone)]
92pub struct HsmdDevPreinit2Options {
93    // CLN: allocates from 1 ascending
94    #[tlv_tag = 1]
95    pub fail_preapprove: Option<bool>,
96    #[tlv_tag = 3]
97    pub no_preapprove_check: Option<bool>,
98
99    // VLS: allocates from 252 descending (largest single byte tag value is 252)
100    #[tlv_tag = 252]
101    pub derivation_style: Option<u8>,
102    #[tlv_tag = 251]
103    pub network_name: Option<WireString>,
104    #[tlv_tag = 250]
105    pub seed: Option<DevSecret>,
106    #[tlv_tag = 249]
107    pub allowlist: Option<Array<WireString>>,
108}
109
110/// HsmdDevPreinit2 does not return a reply
111
112/// hsmd Init
113/// CLN only
114#[derive(SerBolt, Debug, Encodable, Decodable)]
115#[message_id(11)]
116pub struct HsmdInit {
117    pub key_version: Bip32KeyVersion,
118    pub chain_params: BlockHash,
119    pub encryption_key: Option<DevSecret>,
120    pub dev_privkey: Option<DevPrivKey>,
121    pub dev_bip32_seed: Option<DevSecret>,
122    pub dev_channel_secrets: Option<Array<DevSecret>>,
123    pub dev_channel_secrets_shaseed: Option<Sha256>,
124    pub hsm_wire_min_version: u32,
125    pub hsm_wire_max_version: u32,
126}
127
128// // Removed in CLN v23.05
129// #[derive(SerBolt, Debug, Encodable, Decodable)]
130// #[message_id(111)]
131// pub struct HsmdInitReplyV1 {
132//     pub node_id: PubKey,
133//     pub bip32: ExtKey,
134//     pub bolt12: PubKey32,
135//     pub onion_reply_secret: Secret,
136// }
137
138/// deprecated after CLN v23.05
139#[derive(SerBolt, Debug, Encodable, Decodable)]
140#[message_id(113)]
141pub struct HsmdInitReplyV2 {
142    pub node_id: PubKey,
143    pub bip32: ExtKey,
144    pub bolt12: PubKey,
145}
146
147// There doesn't seem to be a HsmdInitReplyV3
148
149///
150#[derive(SerBolt, Debug, Encodable, Decodable)]
151#[message_id(114)]
152pub struct HsmdInitReplyV4 {
153    /// This gets upgraded when the wire protocol changes in incompatible ways:
154    pub hsm_version: u32,
155    /// Capabilities, by convention are message numbers, indicating that the HSM
156    /// supports you sending this message.
157    pub hsm_capabilities: ArrayBE<u32>,
158    pub node_id: PubKey,
159    pub bip32: ExtKey,
160    pub bolt12: PubKey,
161}
162
163/// Signer Init for LDK
164/// LDK only
165#[derive(SerBolt, Debug, Encodable, Decodable)]
166#[message_id(1011)]
167pub struct HsmdInit2 {
168    pub derivation_style: u8,
169    pub network_name: WireString,
170    pub dev_seed: Option<DevSecret>,
171    pub dev_allowlist: Array<WireString>,
172}
173
174///
175#[derive(SerBolt, Debug, Encodable, Decodable)]
176#[message_id(1111)]
177pub struct HsmdInit2Reply {
178    pub node_id: PubKey,
179    pub bip32: ExtKey,
180    pub bolt12: PubKey,
181}
182
183/// Get node public keys.
184/// Used by the frontend
185#[derive(SerBolt, Debug, Encodable, Decodable)]
186#[message_id(1012)]
187pub struct NodeInfo {}
188
189///
190#[derive(SerBolt, Debug, Encodable, Decodable)]
191#[message_id(1112)]
192pub struct NodeInfoReply {
193    pub network_name: WireString,
194    pub node_id: PubKey,
195    pub bip32: ExtKey,
196}
197
198/// Connect a new client
199/// CLN only
200#[derive(SerBolt, Debug, Encodable, Decodable)]
201#[message_id(9)]
202pub struct ClientHsmFd {
203    pub peer_id: PubKey,
204    pub dbid: u64,
205    pub capabilities: u64,
206}
207
208///
209#[derive(SerBolt, Debug, Encodable, Decodable)]
210#[message_id(109)]
211pub struct ClientHsmFdReply {
212    // TODO fd handling
213}
214
215/// Sign invoice
216#[derive(SerBolt, Debug, Encodable, Decodable)]
217#[message_id(8)]
218pub struct SignInvoice {
219    pub u5bytes: Octets,
220    pub hrp: Octets,
221}
222
223///
224#[derive(SerBolt, Debug, Encodable, Decodable)]
225#[message_id(108)]
226pub struct SignInvoiceReply {
227    pub signature: RecoverableSignature,
228}
229
230///
231#[derive(SerBolt, Debug, Encodable, Decodable)]
232#[message_id(7)]
233pub struct SignWithdrawal {
234    pub utxos: Array<Utxo>,
235    pub psbt: WithSize<StreamedPSBT>,
236}
237
238///
239#[derive(SerBolt, Debug, Encodable, Decodable)]
240#[message_id(107)]
241pub struct SignWithdrawalReply {
242    pub psbt: WithSize<PsbtWrapper>,
243}
244
245///
246#[derive(SerBolt, Debug, Encodable, Decodable)]
247#[message_id(1)]
248pub struct Ecdh {
249    pub point: PubKey,
250}
251
252///
253#[derive(SerBolt, Debug, Encodable, Decodable)]
254#[message_id(100)]
255pub struct EcdhReply {
256    pub secret: Secret,
257}
258
259/// Memleak
260/// CLN only
261#[derive(SerBolt, Debug, Encodable, Decodable)]
262#[message_id(33)]
263pub struct Memleak {}
264
265///
266#[derive(SerBolt, Debug, Encodable, Decodable)]
267#[message_id(133)]
268pub struct MemleakReply {
269    pub result: bool,
270}
271
272/// CheckFutureSecret
273#[derive(SerBolt, Debug, Encodable, Decodable)]
274#[message_id(22)]
275pub struct CheckFutureSecret {
276    pub commitment_number: u64,
277    pub secret: DisclosedSecret,
278}
279
280///
281#[derive(SerBolt, Debug, Encodable, Decodable)]
282#[message_id(122)]
283pub struct CheckFutureSecretReply {
284    pub result: bool,
285}
286
287/// SignMessage
288#[derive(SerBolt, Debug, Encodable, Decodable)]
289#[message_id(23)]
290pub struct SignMessage {
291    pub message: Octets,
292}
293
294///
295#[derive(SerBolt, Debug, Encodable, Decodable)]
296#[message_id(123)]
297pub struct SignMessageReply {
298    pub signature: RecoverableSignature,
299}
300
301/// SignBolt12
302#[derive(SerBolt, Debug, Encodable, Decodable)]
303#[message_id(25)]
304pub struct SignBolt12 {
305    pub message_name: WireString,
306    pub field_name: WireString,
307    pub merkle_root: Sha256,
308    pub public_tweak: Octets,
309}
310
311///
312#[derive(SerBolt, Debug, Encodable, Decodable)]
313#[message_id(125)]
314pub struct SignBolt12Reply {
315    pub signature: Signature,
316}
317
318/// PreapproveInvoice {
319#[derive(SerBolt, Debug, Encodable, Decodable)]
320#[message_id(38)]
321pub struct PreapproveInvoice {
322    pub invstring: WireString,
323}
324
325///
326#[derive(SerBolt, Debug, Encodable, Decodable)]
327#[message_id(138)]
328pub struct PreapproveInvoiceReply {
329    pub result: bool,
330}
331
332/// PreapproveKeysend {
333#[derive(SerBolt, Debug, Encodable, Decodable)]
334#[message_id(39)]
335pub struct PreapproveKeysend {
336    pub destination: PubKey,
337    pub payment_hash: Sha256,
338    pub amount_msat: u64,
339}
340
341///
342#[derive(SerBolt, Debug, Encodable, Decodable)]
343#[message_id(139)]
344pub struct PreapproveKeysendReply {
345    pub result: bool,
346}
347
348/// DeriveSecret
349#[derive(SerBolt, Debug, Encodable, Decodable)]
350#[message_id(27)]
351pub struct DeriveSecret {
352    pub info: Octets,
353}
354
355///
356#[derive(SerBolt, Debug, Encodable, Decodable)]
357#[message_id(127)]
358pub struct DeriveSecretReply {
359    pub secret: Secret,
360}
361
362/// CheckPubKey
363#[derive(SerBolt, Debug, Encodable, Decodable)]
364#[message_id(28)]
365pub struct CheckPubKey {
366    pub index: u32,
367    pub pubkey: PubKey,
368}
369
370///
371#[derive(SerBolt, Debug, Encodable, Decodable)]
372#[message_id(128)]
373pub struct CheckPubKeyReply {
374    pub ok: bool,
375}
376
377///
378#[derive(SerBolt, Debug, Encodable, Decodable)]
379#[message_id(147)]
380pub struct SignAnchorspend {
381    pub peer_id: PubKey,
382    pub dbid: u64,
383    pub utxos: Array<Utxo>,
384    pub psbt: WithSize<StreamedPSBT>,
385}
386
387///
388#[derive(SerBolt, Debug, Encodable, Decodable)]
389#[message_id(148)]
390pub struct SignAnchorspendReply {
391    pub psbt: WithSize<PsbtWrapper>,
392}
393
394/// Sign channel update
395#[derive(SerBolt, Debug, Encodable, Decodable)]
396#[message_id(3)]
397pub struct SignChannelUpdate {
398    pub update: Octets,
399}
400
401///
402#[derive(SerBolt, Debug, Encodable, Decodable)]
403#[message_id(103)]
404pub struct SignChannelUpdateReply {
405    pub update: Octets,
406}
407
408///
409#[derive(SerBolt, Debug, Encodable, Decodable)]
410#[message_id(2)]
411pub struct SignChannelAnnouncement {
412    pub announcement: Octets,
413}
414
415///
416#[derive(SerBolt, Debug, Encodable, Decodable)]
417#[message_id(102)]
418pub struct SignChannelAnnouncementReply {
419    pub node_signature: Signature,
420    pub bitcoin_signature: Signature,
421}
422
423/// CLN only
424/// Same as [SignChannelAnnouncement] but called from lightningd
425#[derive(SerBolt, Debug, Encodable, Decodable)]
426#[message_id(4)]
427pub struct SignAnyChannelAnnouncement {
428    pub announcement: Octets,
429    pub peer_id: PubKey,
430    pub dbid: u64,
431}
432
433///
434#[derive(SerBolt, Debug, Encodable, Decodable)]
435#[message_id(104)]
436pub struct SignAnyChannelAnnouncementReply {
437    pub node_signature: Signature,
438    pub bitcoin_signature: Signature,
439}
440
441///
442#[derive(SerBolt, Debug, Encodable, Decodable)]
443#[message_id(6)]
444pub struct SignNodeAnnouncement {
445    pub announcement: Octets,
446}
447
448///
449#[derive(SerBolt, Debug, Encodable, Decodable)]
450#[message_id(106)]
451pub struct SignNodeAnnouncementReply {
452    pub signature: Signature,
453}
454
455/// Get per-commitment point n and optionally revoke a point n-2 by releasing the secret
456#[derive(SerBolt, Debug, Encodable, Decodable)]
457#[message_id(18)]
458pub struct GetPerCommitmentPoint {
459    pub commitment_number: u64,
460}
461
462/// Get per-commitment point
463/// LDK only
464#[derive(SerBolt, Debug, Encodable, Decodable)]
465#[message_id(1018)]
466pub struct GetPerCommitmentPoint2 {
467    pub commitment_number: u64,
468}
469
470///
471#[derive(SerBolt, Debug, Encodable, Decodable)]
472#[message_id(118)]
473pub struct GetPerCommitmentPointReply {
474    pub point: PubKey,
475    pub secret: Option<DisclosedSecret>,
476}
477
478///
479#[derive(SerBolt, Debug, Encodable, Decodable)]
480#[message_id(1118)]
481pub struct GetPerCommitmentPoint2Reply {
482    pub point: PubKey,
483}
484
485///
486#[derive(SerBolt, Debug, Encodable, Decodable)]
487#[message_id(31)]
488pub struct SetupChannel {
489    pub is_outbound: bool,
490    pub channel_value: u64,
491    pub push_value: u64,
492    pub funding_txid: Txid,
493    pub funding_txout: u16,
494    pub to_self_delay: u16,
495    pub local_shutdown_script: Octets,
496    pub local_shutdown_wallet_index: Option<u32>,
497    pub remote_basepoints: Basepoints,
498    pub remote_funding_pubkey: PubKey,
499    pub remote_to_self_delay: u16,
500    pub remote_shutdown_script: Octets,
501    pub channel_type: Octets,
502}
503
504///
505#[derive(SerBolt, Debug, Encodable, Decodable)]
506#[message_id(131)]
507pub struct SetupChannelReply {}
508
509///
510#[derive(SerBolt, Debug, Encodable, Decodable)]
511#[message_id(34)]
512pub struct ForgetChannel {
513    pub node_id: PubKey,
514    pub dbid: u64,
515}
516
517///
518#[derive(SerBolt, Debug, Encodable, Decodable)]
519#[message_id(134)]
520pub struct ForgetChannelReply {}
521
522///
523#[derive(SerBolt, Debug, Encodable, Decodable)]
524#[message_id(32)]
525pub struct CheckOutpoint {
526    pub funding_txid: Txid,
527    pub funding_txout: u16,
528}
529
530///
531#[derive(SerBolt, Debug, Encodable, Decodable)]
532#[message_id(132)]
533pub struct CheckOutpointReply {
534    pub is_buried: bool,
535}
536
537///
538#[derive(SerBolt, Debug, Encodable, Decodable)]
539#[message_id(37)]
540pub struct LockOutpoint {
541    pub funding_txid: Txid,
542    pub funding_txout: u16,
543}
544
545///
546#[derive(SerBolt, Debug, Encodable, Decodable)]
547#[message_id(137)]
548pub struct LockOutpointReply {}
549
550///
551/// CLN only
552#[derive(SerBolt, Debug, Encodable, Decodable)]
553#[message_id(35)]
554pub struct ValidateCommitmentTx {
555    pub tx: WithSize<Transaction>,
556    pub psbt: WithSize<PsbtWrapper>,
557    pub htlcs: Array<Htlc>,
558    pub commitment_number: u64,
559    pub feerate: u32,
560    pub signature: BitcoinSignature,
561    pub htlc_signatures: Array<BitcoinSignature>,
562}
563
564///
565/// LDK only
566#[derive(SerBolt, Debug, Encodable, Decodable)]
567#[message_id(1035)]
568pub struct ValidateCommitmentTx2 {
569    pub commitment_number: u64,
570    pub feerate: u32,
571    pub to_local_value_sat: u64,
572    pub to_remote_value_sat: u64,
573    pub htlcs: Array<Htlc>,
574    pub signature: BitcoinSignature,
575    pub htlc_signatures: Array<BitcoinSignature>,
576}
577
578///
579#[derive(SerBolt, Debug, Encodable, Decodable)]
580#[message_id(135)]
581pub struct ValidateCommitmentTxReply {
582    pub old_commitment_secret: Option<DisclosedSecret>,
583    pub next_per_commitment_point: PubKey,
584}
585
586///
587/// CLN only
588#[derive(SerBolt, Debug, Encodable, Decodable)]
589#[message_id(40)]
590pub struct RevokeCommitmentTx {
591    pub commitment_number: u64,
592}
593
594///
595#[derive(SerBolt, Debug, Encodable, Decodable)]
596#[message_id(140)]
597pub struct RevokeCommitmentTxReply {
598    pub old_commitment_secret: DisclosedSecret,
599    pub next_per_commitment_point: PubKey,
600}
601
602///
603#[derive(SerBolt, Debug, Encodable, Decodable)]
604#[message_id(36)]
605pub struct ValidateRevocation {
606    pub commitment_number: u64,
607    pub commitment_secret: DisclosedSecret,
608}
609
610///
611#[derive(SerBolt, Debug, Encodable, Decodable)]
612#[message_id(136)]
613pub struct ValidateRevocationReply {}
614
615///
616/// CLN only
617#[derive(SerBolt, Encodable, Decodable)]
618#[message_id(5)]
619pub struct SignCommitmentTx {
620    pub peer_id: PubKey,
621    pub dbid: u64,
622    pub tx: WithSize<Transaction>,
623    pub psbt: WithSize<PsbtWrapper>,
624    pub remote_funding_key: PubKey,
625    pub commitment_number: u64,
626}
627
628impl Debug for SignCommitmentTx {
629    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
630        // Sometimes c-lightning calls handle_sign_commitment_tx with mutual
631        // close transactions.  We can tell the difference because the locktime
632        // field will be set to 0 for a mutual close.
633        let name = if self.tx.0.lock_time.to_consensus_u32() == 0 {
634            "SignMutualCloseTx as a SignCommitmentTx"
635        } else {
636            "SignCommitmentTx"
637        };
638        f.debug_struct(name)
639            .field("peer_id", &self.peer_id)
640            .field("dbid", &self.dbid)
641            .field("tx", &self.tx)
642            .field("psbt", &self.psbt)
643            .field("remote_funding_key", &self.remote_funding_key)
644            .field("commitment_number", &self.commitment_number)
645            .finish()
646    }
647}
648
649///
650/// LDK only
651#[derive(SerBolt, Debug, Encodable, Decodable)]
652#[message_id(1005)]
653pub struct SignLocalCommitmentTx2 {
654    pub commitment_number: u64,
655}
656
657///
658#[derive(SerBolt, Debug, Encodable, Decodable)]
659#[message_id(1006)]
660pub struct SignGossipMessage {
661    pub message: Octets,
662}
663
664///
665#[derive(SerBolt, Debug, Encodable, Decodable)]
666#[message_id(1106)]
667pub struct SignGossipMessageReply {
668    pub signature: Signature,
669}
670
671///
672/// CLN only
673#[derive(SerBolt, Debug, Encodable, Decodable)]
674#[message_id(19)]
675pub struct SignRemoteCommitmentTx {
676    pub tx: WithSize<Transaction>,
677    pub psbt: WithSize<PsbtWrapper>,
678    pub remote_funding_key: PubKey,
679    pub remote_per_commitment_point: PubKey,
680    pub option_static_remotekey: bool,
681    pub commitment_number: u64,
682    pub htlcs: Array<Htlc>,
683    pub feerate: u32,
684}
685
686/// Ping request
687/// LDK only
688#[derive(SerBolt, Debug, Encodable, Decodable)]
689#[message_id(1000)]
690pub struct Ping {
691    pub id: u16,
692    pub message: WireString,
693}
694
695/// Ping reply
696/// LDK only
697#[derive(SerBolt, Debug, Encodable, Decodable)]
698#[message_id(1100)]
699pub struct Pong {
700    pub id: u16,
701    pub message: WireString,
702}
703
704///
705/// LDK only
706#[derive(SerBolt, Debug, Encodable, Decodable)]
707#[message_id(1019)]
708pub struct SignRemoteCommitmentTx2 {
709    pub remote_per_commitment_point: PubKey,
710    pub commitment_number: u64,
711    pub feerate: u32,
712    pub to_local_value_sat: u64,
713    pub to_remote_value_sat: u64,
714    pub htlcs: Array<Htlc>,
715}
716
717///
718#[derive(SerBolt, Debug, Encodable, Decodable)]
719#[message_id(1119)]
720pub struct SignCommitmentTxWithHtlcsReply {
721    pub signature: BitcoinSignature,
722    pub htlc_signatures: Array<BitcoinSignature>,
723}
724
725///
726/// CLN only
727#[derive(SerBolt, Debug, Encodable, Decodable)]
728#[message_id(12)]
729pub struct SignDelayedPaymentToUs {
730    pub commitment_number: u64,
731    pub tx: WithSize<Transaction>,
732    pub psbt: WithSize<PsbtWrapper>,
733    pub wscript: Octets,
734}
735
736/// CLN only
737/// Same as [SignDelayedPaymentToUs] but called from lightningd
738#[derive(SerBolt, Debug, Encodable, Decodable)]
739#[message_id(142)]
740pub struct SignAnyDelayedPaymentToUs {
741    pub commitment_number: u64,
742    pub tx: WithSize<Transaction>,
743    pub psbt: WithSize<PsbtWrapper>,
744    pub wscript: Octets,
745    pub input: u32,
746    pub peer_id: PubKey,
747    pub dbid: u64,
748}
749
750///
751/// CLN only
752#[derive(SerBolt, Debug, Encodable, Decodable)]
753#[message_id(13)]
754pub struct SignRemoteHtlcToUs {
755    pub remote_per_commitment_point: PubKey,
756    pub tx: WithSize<Transaction>,
757    pub psbt: WithSize<PsbtWrapper>,
758    pub wscript: Octets,
759    pub option_anchors: bool,
760}
761
762/// CLN only
763/// Same as [SignRemoteHtlcToUs] but called from lightningd
764#[derive(SerBolt, Debug, Encodable, Decodable)]
765#[message_id(143)]
766pub struct SignAnyRemoteHtlcToUs {
767    pub remote_per_commitment_point: PubKey,
768    pub tx: WithSize<Transaction>,
769    pub psbt: WithSize<PsbtWrapper>,
770    pub wscript: Octets,
771    pub option_anchors: bool,
772    pub input: u32,
773    pub peer_id: PubKey,
774    pub dbid: u64,
775}
776
777///
778#[derive(SerBolt, Debug, Encodable, Decodable)]
779#[message_id(16)]
780pub struct SignLocalHtlcTx {
781    pub commitment_number: u64,
782    pub tx: WithSize<Transaction>,
783    pub psbt: WithSize<PsbtWrapper>,
784    pub wscript: Octets,
785    pub option_anchors: bool,
786}
787
788/// CLN only
789/// Same as [SignLocalHtlcTx] but called from lightningd
790#[derive(SerBolt, Debug, Encodable, Decodable)]
791#[message_id(146)]
792pub struct SignAnyLocalHtlcTx {
793    pub commitment_number: u64,
794    pub tx: WithSize<Transaction>,
795    pub psbt: WithSize<PsbtWrapper>,
796    pub wscript: Octets,
797    pub option_anchors: bool,
798    pub input: u32,
799    pub peer_id: PubKey,
800    pub dbid: u64,
801}
802
803/// CLN only
804#[derive(SerBolt, Debug, Encodable, Decodable)]
805#[message_id(149)]
806pub struct SignHtlcTxMingle {
807    pub peer_id: PubKey,
808    pub dbid: u64,
809    pub utxos: Array<Utxo>,
810    pub psbt: WithSize<StreamedPSBT>,
811}
812
813///
814#[derive(SerBolt, Debug, Encodable, Decodable)]
815#[message_id(150)]
816pub struct SignHtlcTxMingleReply {
817    pub psbt: WithSize<PsbtWrapper>,
818}
819
820///
821/// CLN only
822#[derive(SerBolt, Debug, Encodable, Decodable)]
823#[message_id(21)]
824pub struct SignMutualCloseTx {
825    pub tx: WithSize<Transaction>,
826    pub psbt: WithSize<PsbtWrapper>,
827    pub remote_funding_key: PubKey,
828}
829
830///
831/// LDK only
832#[derive(SerBolt, Debug, Encodable, Decodable)]
833#[message_id(1021)]
834pub struct SignMutualCloseTx2 {
835    pub to_local_value_sat: u64,
836    pub to_remote_value_sat: u64,
837    pub local_script: Octets,
838    pub remote_script: Octets,
839    pub local_wallet_path_hint: ArrayBE<u32>,
840}
841
842///
843/// CLN only
844#[derive(SerBolt, Debug, Encodable, Decodable)]
845#[message_id(29)]
846pub struct SignSpliceTx {
847    pub tx: WithSize<Transaction>,
848    pub psbt: WithSize<PsbtWrapper>,
849    pub remote_funding_key: PubKey,
850    pub input_index: u32,
851}
852
853///
854#[derive(SerBolt, Debug, Encodable, Decodable)]
855#[message_id(105)]
856pub struct SignCommitmentTxReply {
857    pub signature: BitcoinSignature,
858}
859
860///
861#[derive(SerBolt, Debug, Encodable, Decodable)]
862#[message_id(112)]
863pub struct SignTxReply {
864    pub signature: BitcoinSignature,
865}
866
867///
868#[derive(SerBolt, Debug, Encodable, Decodable)]
869#[message_id(30)]
870pub struct NewChannel {
871    pub peer_id: PubKey,
872    pub dbid: u64,
873}
874
875///
876#[derive(SerBolt, Debug, Encodable, Decodable)]
877#[message_id(130)]
878pub struct NewChannelReply {}
879
880///
881#[derive(SerBolt, Debug, Encodable, Decodable)]
882#[message_id(10)]
883pub struct GetChannelBasepoints {
884    pub node_id: PubKey,
885    pub dbid: u64,
886}
887
888///
889#[derive(SerBolt, Debug, Encodable, Decodable)]
890#[message_id(110)]
891pub struct GetChannelBasepointsReply {
892    pub basepoints: Basepoints,
893    pub funding: PubKey,
894}
895
896///
897#[derive(SerBolt, Debug, Encodable, Decodable)]
898#[message_id(20)]
899pub struct SignRemoteHtlcTx {
900    pub tx: WithSize<Transaction>,
901    pub psbt: WithSize<PsbtWrapper>,
902    pub wscript: Octets,
903    pub remote_per_commitment_point: PubKey,
904    pub option_anchors: bool,
905}
906
907/// LDK message to sign a local HTLC transaction.
908#[derive(SerBolt, Debug, Encodable, Decodable)]
909#[message_id(20)]
910pub struct SignLocalHtlcTx2 {
911    pub tx: WithSize<Transaction>,
912    pub input: u32,
913    pub per_commitment_number: u64,
914    pub feerate_per_kw: u32,
915    pub offered: bool,
916    pub cltv_expiry: u32,
917    pub htlc_amount_msat: u64,
918    pub payment_hash: Sha256,
919}
920
921///
922#[derive(SerBolt, Debug, Encodable, Decodable)]
923#[message_id(14)]
924pub struct SignPenaltyToUs {
925    pub revocation_secret: DisclosedSecret,
926    pub tx: WithSize<Transaction>,
927    pub psbt: WithSize<PsbtWrapper>,
928    pub wscript: Octets,
929}
930
931/// Same as [SignPenaltyToUs] but called from lightningd
932#[derive(SerBolt, Debug, Encodable, Decodable)]
933#[message_id(144)]
934pub struct SignAnyPenaltyToUs {
935    pub revocation_secret: DisclosedSecret,
936    pub tx: WithSize<Transaction>,
937    pub psbt: WithSize<PsbtWrapper>,
938    pub wscript: Octets,
939    pub input: u32,
940    pub peer_id: PubKey,
941    pub dbid: u64,
942}
943
944///
945#[derive(SerBolt, Debug, Encodable, Decodable)]
946#[message_id(2002)]
947pub struct TipInfo {}
948
949///
950#[derive(SerBolt, Debug, Encodable, Decodable)]
951#[message_id(2102)]
952pub struct TipInfoReply {
953    pub height: u32,
954    pub block_hash: BlockHash,
955}
956
957///
958#[derive(SerBolt, Debug, Encodable, Decodable)]
959#[message_id(2003)]
960pub struct ForwardWatches {}
961
962///
963#[derive(SerBolt, Debug, Encodable, Decodable)]
964#[message_id(2103)]
965pub struct ForwardWatchesReply {
966    pub txids: Array<Txid>,
967    pub outpoints: Array<OutPoint>,
968}
969
970#[derive(SerBolt, Debug, Encodable, Decodable)]
971#[message_id(2004)]
972pub struct ReverseWatches {}
973
974///
975#[derive(SerBolt, Debug, Encodable, Decodable)]
976#[message_id(2104)]
977pub struct ReverseWatchesReply {
978    pub txids: Array<Txid>,
979    pub outpoints: Array<OutPoint>,
980}
981
982/// A debug wrapper around a TxoProof
983pub struct DebugTxoProof(pub TxoProof);
984
985impl Debug for DebugTxoProof {
986    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
987        match &self.0.proof {
988            ProofType::Filter(filt, _) => write!(f, "TxoProof filter len={}", filt.len()),
989            ProofType::Block(_) => write!(f, "TxoProof block"),
990            ProofType::ExternalBlock() => write!(f, "TxoProof external block"),
991        }
992    }
993}
994
995impl Deref for DebugTxoProof {
996    type Target = TxoProof;
997
998    fn deref(&self) -> &Self::Target {
999        &self.0
1000    }
1001}
1002
1003impl Decodable for DebugTxoProof {
1004    fn consensus_decode<D: Read + ?Sized>(
1005        d: &mut D,
1006    ) -> core::result::Result<Self, bitcoin::consensus::encode::Error> {
1007        let proof = TxoProof::consensus_decode(d)?;
1008        Ok(DebugTxoProof(proof))
1009    }
1010}
1011
1012#[derive(SerBolt, Debug, Encodable, Decodable)]
1013#[message_id(2005)]
1014pub struct AddBlock {
1015    /// Bitcoin consensus encoded
1016    pub header: Octets,
1017    /// Bitcoin consensus encoded TXOO TxoProof
1018    pub unspent_proof: Option<DebugTxoProof>,
1019}
1020
1021///
1022#[derive(SerBolt, Debug, Encodable, Decodable)]
1023#[message_id(2105)]
1024pub struct AddBlockReply {}
1025
1026#[derive(SerBolt, Debug, Encodable, Decodable)]
1027#[message_id(2006)]
1028pub struct RemoveBlock {
1029    /// Bitcoin consensus encoded TXOO TxoProof
1030    // FIXME do we need the option?
1031    pub unspent_proof: Option<LargeOctets>,
1032    pub prev_block_header: BlockHeader,
1033    pub prev_filter_header: FilterHeader,
1034}
1035
1036///
1037#[derive(SerBolt, Debug, Encodable, Decodable)]
1038#[message_id(2106)]
1039pub struct RemoveBlockReply {}
1040
1041/// Get a serialized signed heartbeat
1042#[derive(SerBolt, Debug, Encodable, Decodable)]
1043#[message_id(2008)]
1044pub struct GetHeartbeat {}
1045
1046/// A serialized signed heartbeat
1047#[derive(SerBolt, Debug, Encodable, Decodable)]
1048#[message_id(2108)]
1049pub struct GetHeartbeatReply {
1050    pub heartbeat: Octets,
1051}
1052
1053/// Start or continue streaming a full block.
1054/// Used when the compact proof has a false positive.
1055/// The hash and the offset are provided to fail fast
1056/// if there is a communication error.
1057/// The stream of messages is always followed by an `AddBlock` with
1058/// a proof type `ExternalBlock`.
1059#[derive(SerBolt, Debug, Encodable, Decodable)]
1060#[message_id(2009)]
1061pub struct BlockChunk {
1062    pub hash: BlockHash,
1063    pub offset: u32,
1064    pub content: Octets,
1065}
1066
1067///
1068#[derive(SerBolt, Debug, Encodable, Decodable)]
1069#[message_id(2109)]
1070pub struct BlockChunkReply {}
1071
1072/// An unknown message
1073#[derive(Debug, Decodable)]
1074pub struct Unknown {
1075    /// Message type
1076    pub message_type: u16,
1077}
1078
1079#[derive(SerBolt, Debug, Encodable, Decodable)]
1080#[message_id(3000)]
1081pub struct SignerError {
1082    // Error code
1083    pub code: u16,
1084    // Error message
1085    pub message: WireString,
1086}
1087
1088#[derive(SerBolt, Debug, Encodable, Decodable)]
1089#[message_id(65535)]
1090pub struct UnknownPlaceholder {}
1091
1092pub const UNKNOWN_PLACEHOLDER: UnknownPlaceholder = UnknownPlaceholder {};
1093
1094/// An enum representing all messages we can read and write
1095#[derive(ReadMessage, Debug)]
1096pub enum Message {
1097    Ping(Ping),
1098    Pong(Pong),
1099    #[cfg(feature = "developer")]
1100    HsmdDevPreinit(HsmdDevPreinit),
1101    #[cfg(feature = "developer")]
1102    HsmdDevPreinit2(HsmdDevPreinit2),
1103    #[cfg(feature = "developer")]
1104    HsmdDevPreinitReply(HsmdDevPreinitReply),
1105    HsmdInit(HsmdInit),
1106    // HsmdInitReplyV1(HsmdInitReplyV1),
1107    #[allow(deprecated)]
1108    HsmdInitReplyV2(HsmdInitReplyV2),
1109    HsmdInitReplyV4(HsmdInitReplyV4),
1110    HsmdInit2(HsmdInit2),
1111    HsmdInit2Reply(HsmdInit2Reply),
1112    ClientHsmFd(ClientHsmFd),
1113    ClientHsmFdReply(ClientHsmFdReply),
1114    SignInvoice(SignInvoice),
1115    SignInvoiceReply(SignInvoiceReply),
1116    SignWithdrawal(SignWithdrawal),
1117    SignWithdrawalReply(SignWithdrawalReply),
1118    Ecdh(Ecdh),
1119    EcdhReply(EcdhReply),
1120    Memleak(Memleak),
1121    MemleakReply(MemleakReply),
1122    CheckFutureSecret(CheckFutureSecret),
1123    CheckFutureSecretReply(CheckFutureSecretReply),
1124    SignBolt12(SignBolt12),
1125    SignBolt12Reply(SignBolt12Reply),
1126    PreapproveInvoice(PreapproveInvoice),
1127    PreapproveInvoiceReply(PreapproveInvoiceReply),
1128    PreapproveKeysend(PreapproveKeysend),
1129    PreapproveKeysendReply(PreapproveKeysendReply),
1130    DeriveSecret(DeriveSecret),
1131    DeriveSecretReply(DeriveSecretReply),
1132    CheckPubKey(CheckPubKey),
1133    CheckPubKeyReply(CheckPubKeyReply),
1134    SignAnchorspend(SignAnchorspend),
1135    SignAnchorspendReply(SignAnchorspendReply),
1136    SignMessage(SignMessage),
1137    SignMessageReply(SignMessageReply),
1138    SignChannelUpdate(SignChannelUpdate),
1139    SignChannelUpdateReply(SignChannelUpdateReply),
1140    SignChannelAnnouncement(SignChannelAnnouncement),
1141    SignChannelAnnouncementReply(SignChannelAnnouncementReply),
1142    SignAnyChannelAnnouncement(SignAnyChannelAnnouncement),
1143    SignAnyChannelAnnouncementReply(SignAnyChannelAnnouncementReply),
1144    SignNodeAnnouncement(SignNodeAnnouncement),
1145    SignNodeAnnouncementReply(SignNodeAnnouncementReply),
1146    GetPerCommitmentPoint(GetPerCommitmentPoint),
1147    GetPerCommitmentPointReply(GetPerCommitmentPointReply),
1148    GetPerCommitmentPoint2(GetPerCommitmentPoint2),
1149    GetPerCommitmentPoint2Reply(GetPerCommitmentPoint2Reply),
1150    SetupChannel(SetupChannel),
1151    SetupChannelReply(SetupChannelReply),
1152    ForgetChannel(ForgetChannel),
1153    ForgetChannelReply(ForgetChannelReply),
1154    CheckOutpoint(CheckOutpoint),
1155    CheckOutpointReply(CheckOutpointReply),
1156    LockOutpoint(LockOutpoint),
1157    LockOutpointReply(LockOutpointReply),
1158    ValidateCommitmentTx(ValidateCommitmentTx),
1159    ValidateCommitmentTx2(ValidateCommitmentTx2),
1160    ValidateCommitmentTxReply(ValidateCommitmentTxReply),
1161    RevokeCommitmentTx(RevokeCommitmentTx),
1162    RevokeCommitmentTxReply(RevokeCommitmentTxReply),
1163    ValidateRevocation(ValidateRevocation),
1164    ValidateRevocationReply(ValidateRevocationReply),
1165    SignRemoteCommitmentTx(SignRemoteCommitmentTx),
1166    SignRemoteCommitmentTx2(SignRemoteCommitmentTx2),
1167    SignCommitmentTxWithHtlcsReply(SignCommitmentTxWithHtlcsReply),
1168    SignDelayedPaymentToUs(SignDelayedPaymentToUs),
1169    SignAnyDelayedPaymentToUs(SignAnyDelayedPaymentToUs),
1170    SignRemoteHtlcToUs(SignRemoteHtlcToUs),
1171    SignAnyRemoteHtlcToUs(SignAnyRemoteHtlcToUs),
1172    SignLocalHtlcTx(SignLocalHtlcTx),
1173    SignAnyLocalHtlcTx(SignAnyLocalHtlcTx),
1174    SignCommitmentTx(SignCommitmentTx),
1175    SignLocalCommitmentTx2(SignLocalCommitmentTx2),
1176    SignGossipMessage(SignGossipMessage),
1177    SignMutualCloseTx(SignMutualCloseTx),
1178    SignMutualCloseTx2(SignMutualCloseTx2),
1179    SignTxReply(SignTxReply),
1180    SignCommitmentTxReply(SignCommitmentTxReply),
1181    GetChannelBasepoints(GetChannelBasepoints),
1182    GetChannelBasepointsReply(GetChannelBasepointsReply),
1183    NewChannel(NewChannel),
1184    NewChannelReply(NewChannelReply),
1185    SignRemoteHtlcTx(SignRemoteHtlcTx),
1186    SignLocalHtlcTx2(SignLocalHtlcTx2),
1187    SignPenaltyToUs(SignPenaltyToUs),
1188    SignAnyPenaltyToUs(SignAnyPenaltyToUs),
1189    SignSpliceTx(SignSpliceTx),
1190    SignHtlcTxMingle(SignHtlcTxMingle),
1191    SignHtlcTxMingleReply(SignHtlcTxMingleReply),
1192    TipInfo(TipInfo),
1193    TipInfoReply(TipInfoReply),
1194    ForwardWatches(ForwardWatches),
1195    ForwardWatchesReply(ForwardWatchesReply),
1196    ReverseWatches(ReverseWatches),
1197    ReverseWatchesReply(ReverseWatchesReply),
1198    AddBlock(AddBlock),
1199    AddBlockReply(AddBlockReply),
1200    RemoveBlock(RemoveBlock),
1201    RemoveBlockReply(RemoveBlockReply),
1202    GetHeartbeat(GetHeartbeat),
1203    GetHeartbeatReply(GetHeartbeatReply),
1204    NodeInfo(NodeInfo),
1205    NodeInfoReply(NodeInfoReply),
1206    BlockChunk(BlockChunk),
1207    BlockChunkReply(BlockChunkReply),
1208    Unknown(Unknown),
1209    SignerError(SignerError),
1210}
1211
1212/// Read a length framed BOLT message of any type:
1213///
1214/// - u32 packet length
1215/// - u16 packet type
1216/// - data
1217pub fn read<R: Read>(reader: &mut R) -> Result<Message> {
1218    let len = reader.read_u32_be()?;
1219    from_reader(reader, len)
1220}
1221
1222/// Read a specific message type from a length framed BOLT message:
1223///
1224/// - u32 packet length
1225/// - u16 packet type
1226/// - data
1227pub fn read_message<R: Read, T: DeBolt>(reader: &mut R) -> Result<T> {
1228    let len = reader.read_u32_be()?;
1229    check_message_length(len)?;
1230
1231    let mut take = Take::new(Box::new(reader), len as u64);
1232    let message_type = take.read_u16_be()?;
1233    if message_type != T::TYPE {
1234        return Err(Error::UnexpectedType(message_type));
1235    }
1236
1237    let res = T::consensus_decode(&mut take)?;
1238    if !take.is_empty() {
1239        return Err(Error::TrailingBytes(take.remaining() as usize, T::TYPE));
1240    }
1241    Ok(res)
1242}
1243
1244/// Read a raw message from a length framed BOLT message:
1245///
1246/// - u32 packet length (not returned in the result)
1247/// - u16 packet type
1248/// - data
1249pub fn read_raw<R: Read>(reader: &mut R) -> Result<Vec<u8>> {
1250    let len = reader.read_u32_be()?;
1251    let mut data = Vec::new();
1252    data.resize(len as usize, 0);
1253    reader.read_exact(&mut data)?;
1254    Ok(data)
1255}
1256
1257/// Read a BOLT message from a vector:
1258///
1259/// - u16 packet type
1260/// - data
1261pub fn from_vec(mut v: Vec<u8>) -> Result<Message> {
1262    let len = v.len();
1263    let mut cursor = io::Cursor::new(&mut v);
1264    from_reader(&mut cursor, len as u32)
1265}
1266
1267pub fn message_name_from_vec(v: &[u8]) -> String {
1268    if v.len() < 2 {
1269        return "ShortRead".to_owned();
1270    }
1271    let message_type = u16::from_be_bytes([v[0], v[1]]);
1272    Message::message_name(message_type).to_owned()
1273}
1274
1275/// Read a BOLT message from a reader:
1276///
1277/// - u16 packet type
1278/// - data
1279pub fn from_reader<R: Read>(reader: &mut R, len: u32) -> Result<Message> {
1280    check_message_length(len)?;
1281    let mut take = Take::new(Box::new(reader), len as u64);
1282
1283    let message_type = take.read_u16_be()?;
1284    let message = Message::read_message(&mut take, message_type)?;
1285    if !take.is_empty() {
1286        return Err(Error::TrailingBytes(take.remaining() as usize, message_type));
1287    }
1288    Ok(message)
1289}
1290
1291fn check_message_length(len: u32) -> Result<()> {
1292    if len < 2 {
1293        return Err(Error::ShortRead);
1294    }
1295    if len > MAX_MESSAGE_SIZE {
1296        error!("message too large {}", len);
1297        return Err(Error::MessageTooLarge);
1298    }
1299    Ok(())
1300}
1301
1302pub fn write<W: Write, T: DeBolt>(writer: &mut W, value: T) -> Result<()> {
1303    let message_type = T::TYPE;
1304    let mut buf = message_type.to_be_bytes().to_vec();
1305    let mut val_buf = to_vec(&value)?;
1306    buf.append(&mut val_buf);
1307    write_vec(writer, buf)
1308}
1309
1310pub fn write_vec<W: Write>(writer: &mut W, buf: Vec<u8>) -> Result<()> {
1311    let len: u32 = buf.len() as u32;
1312    writer.write_all(&len.to_be_bytes())?;
1313    writer.write_all(&buf)?;
1314    Ok(())
1315}
1316
1317/// A serial request header
1318#[derive(Debug)]
1319pub struct SerialRequestHeader {
1320    pub sequence: u16,
1321    pub peer_id: [u8; 33],
1322    pub dbid: u64,
1323}
1324
1325/// Write a serial request header prefixed by two magic bytes
1326pub fn write_serial_request_header<W: Write>(
1327    writer: &mut W,
1328    srh: &SerialRequestHeader,
1329) -> Result<()> {
1330    writer.write_all(&0xaa55u16.to_be_bytes())?;
1331    writer.write_all(&srh.sequence.to_be_bytes())?;
1332    writer.write_all(&srh.peer_id)?;
1333    writer.write_all(&srh.dbid.to_be_bytes())?;
1334    Ok(())
1335}
1336
1337/// Write a serial response header that includes two magic bytes and two sequence bytes
1338pub fn write_serial_response_header<W: Write>(writer: &mut W, sequence: u16) -> Result<()> {
1339    writer.write_all(&0x5aa5u16.to_be_bytes())?;
1340    writer.write_all(&sequence.to_be_bytes())?;
1341    Ok(())
1342}
1343
1344/// Read and return the serial request header
1345/// Returns BadFraming if the magic is wrong.
1346pub fn read_serial_request_header<R: Read>(reader: &mut R) -> Result<SerialRequestHeader> {
1347    let magic = reader.read_u16_be()?;
1348    if magic != 0xaa55 {
1349        error!("bad magic {:02x}", magic);
1350        return Err(Error::BadFraming);
1351    }
1352    let sequence = reader.read_u16_be()?;
1353    let mut peer_id = [0u8; 33];
1354    reader.read_exact(&mut peer_id)?;
1355    let dbid = reader.read_u64_be()?;
1356    Ok(SerialRequestHeader { sequence, peer_id, dbid })
1357}
1358
1359/// Read the serial response header and match the expected sequence number
1360/// Returns BadFraming if the magic or sequence are wrong.
1361pub fn read_serial_response_header<R: Read>(reader: &mut R, expected_sequence: u16) -> Result<()> {
1362    let magic = reader.read_u16_be()?;
1363    if magic != 0x5aa5u16 {
1364        error!("bad magic {:02x}", magic);
1365        return Err(Error::BadFraming);
1366    }
1367    let sequence = reader.read_u16_be()?;
1368    if sequence != expected_sequence {
1369        error!("sequence {} != expected {}", sequence, expected_sequence);
1370        return Err(Error::BadFraming);
1371    }
1372    Ok(())
1373}
1374
1375#[cfg(test)]
1376mod tests {
1377    use crate::msgs::Message;
1378    use test_log::test;
1379
1380    use super::*;
1381
1382    #[test]
1383    fn message_name_from_vec_test() {
1384        // Test with a short vector
1385        let short_vec = vec![0x01];
1386        assert_eq!(message_name_from_vec(&short_vec), "ShortRead");
1387
1388        // Test with a valid message type
1389        let valid_vec = vec![0x00, 11];
1390        assert_eq!(message_name_from_vec(&valid_vec), "HsmdInit");
1391
1392        // Test with an unknown message type
1393        let unknown_vec = vec![0xFF, 0xFF];
1394        assert_eq!(message_name_from_vec(&unknown_vec), "Unknown");
1395    }
1396
1397    #[test]
1398    fn roundtrip_test() {
1399        let msg = SignChannelAnnouncementReply {
1400            node_signature: Signature([0; 64]),
1401            bitcoin_signature: Signature([1; 64]),
1402        };
1403
1404        let ser = msg.as_vec();
1405        let dmsg = from_vec(ser).unwrap();
1406        if let Message::SignChannelAnnouncementReply(dmsg) = dmsg {
1407            assert_eq!(dmsg.node_signature.0, msg.node_signature.0);
1408            assert_eq!(dmsg.bitcoin_signature.0, msg.bitcoin_signature.0);
1409        } else {
1410            panic!("bad deser type")
1411        }
1412    }
1413
1414    #[test]
1415    fn name_test() {
1416        assert_eq!(Message::NodeInfo(NodeInfo {}).inner().name(), "NodeInfo");
1417        assert_eq!(
1418            Message::Unknown(Unknown { message_type: 0 }).inner().name(),
1419            "UnknownPlaceholder"
1420        );
1421    }
1422
1423    #[test]
1424    fn tlv_roundtrip_test() {
1425        // Create an options struct, set some fields, others are not set
1426        let mut options = HsmdDevPreinit2Options::default();
1427        options.network_name = Some(WireString("testnet".as_bytes().to_vec()));
1428        options.seed = Some(DevSecret([42u8; 32]));
1429        let msg = HsmdDevPreinit2 { options };
1430        let ser = msg.as_vec();
1431
1432        // Make sure the encoded version doesn't change
1433        assert_eq!(hex::encode(&ser), "0063fa202a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2afb08746573746e657400");
1434
1435        // Decode the options struct, check that fields are correct
1436        let dmsg = from_vec(ser).unwrap();
1437        if let Message::HsmdDevPreinit2(dmsg) = dmsg {
1438            assert_eq!(dmsg.options.derivation_style, None);
1439            assert_eq!(dmsg.options.network_name, Some(WireString("testnet".as_bytes().to_vec())));
1440            assert_eq!(dmsg.options.seed, Some(DevSecret([42u8; 32])));
1441            assert!(dmsg.options.allowlist.is_none());
1442        } else {
1443            panic!("bad deser type")
1444        }
1445    }
1446
1447    #[derive(SerBolt, Debug, Encodable, Decodable)]
1448    #[message_id(9999)]
1449    pub struct TestTlvWithDupTags {
1450        pub options: TestTlvOptionsWithDupTags,
1451    }
1452
1453    // duplicate tag val!  This should fail
1454    #[derive(SerBoltTlvOptions, Default, Debug)]
1455    pub struct TestTlvOptionsWithDupTags {
1456        #[tlv_tag = 9]
1457        pub field1: Option<bool>,
1458        #[tlv_tag = 10]
1459        pub field2: Option<bool>,
1460        #[tlv_tag = 10]
1461        pub field3: Option<bool>,
1462        #[tlv_tag = 12]
1463        pub field4: Option<bool>,
1464    }
1465
1466    #[test]
1467    #[should_panic(expected = "assertion failed: t < 10u64")]
1468    fn ser_bolt_tlv_options_dup_tags_test() {
1469        let mut options = TestTlvOptionsWithDupTags::default();
1470        options.field3 = Some(true);
1471        options.field2 = Some(false);
1472        let msg = TestTlvWithDupTags { options };
1473        let _ser = msg.as_vec();
1474    }
1475
1476    #[derive(SerBolt, Debug, Encodable, Decodable)]
1477    #[message_id(9999)]
1478    pub struct TestTlvWithDescTags {
1479        pub options: TestTlvOptionsWithDescTags,
1480    }
1481
1482    // descending tag order! This should be reordered internally and should work
1483    #[derive(SerBoltTlvOptions, Default, Debug)]
1484    pub struct TestTlvOptionsWithDescTags {
1485        #[tlv_tag = 12]
1486        pub field1: Option<bool>,
1487        #[tlv_tag = 11]
1488        pub field2: Option<bool>,
1489        #[tlv_tag = 10]
1490        pub field3: Option<bool>,
1491    }
1492
1493    #[test]
1494    fn ser_bolt_tlv_options_desc_tags_test() {
1495        let mut options = TestTlvOptionsWithDescTags::default();
1496        options.field3 = Some(true);
1497        options.field2 = Some(false);
1498        let msg = TestTlvWithDescTags { options };
1499        let _ser = msg.as_vec();
1500    }
1501
1502    // Test sending an even tag when the receiver doesn't know it
1503
1504    #[derive(SerBoltTlvOptions, Default, Debug)]
1505    pub struct TestTlvOptionsEvenSender {
1506        #[tlv_tag = 12]
1507        pub field1: Option<bool>,
1508        #[tlv_tag = 11]
1509        pub field2: Option<bool>,
1510        #[tlv_tag = 10]
1511        pub field3: Option<bool>,
1512        #[tlv_tag = 42]
1513        pub mandatory: Option<bool>,
1514    }
1515
1516    #[derive(SerBoltTlvOptions, Default, Debug)]
1517    pub struct TestTlvOptionsOddOnlyReceiver {
1518        #[tlv_tag = 12]
1519        pub field1: Option<bool>,
1520        #[tlv_tag = 11]
1521        pub field2: Option<bool>,
1522        #[tlv_tag = 10]
1523        pub field3: Option<bool>,
1524    }
1525
1526    #[test]
1527    fn ser_bolt_tlv_even_is_mandatory_test() {
1528        // it's ok if you don't send the even tag
1529        let mut options = TestTlvOptionsEvenSender::default();
1530        options.field1 = Some(true);
1531        let tlvdata = crate::msgs::bitcoin::consensus::serialize(&options);
1532        let dmsg: TestTlvOptionsOddOnlyReceiver =
1533            crate::msgs::bitcoin::consensus::deserialize(&tlvdata).unwrap();
1534        assert_eq!(dmsg.field1, Some(true));
1535        assert_eq!(dmsg.field2, None);
1536
1537        // but if the sender turns on an even tag ...
1538        options.mandatory = Some(true);
1539        let tlvdata = crate::msgs::bitcoin::consensus::serialize(&options);
1540        let rv =
1541            crate::msgs::bitcoin::consensus::deserialize::<TestTlvOptionsOddOnlyReceiver>(&tlvdata);
1542        match rv {
1543            Ok(_) => panic!("Expected an error, but got Ok"),
1544            Err(e) => match e {
1545                bitcoin::consensus::encode::Error::ParseFailed(expected_msg) =>
1546                    assert_eq!(expected_msg, "decode_tlv_stream failed"),
1547                _ => panic!("Unexpected error type"),
1548            },
1549        }
1550    }
1551}