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