Skip to main content

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