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
35pub const CODE_ORPHAN_BLOCK: u16 = 401;
37
38pub const PROTOCOL_VERSION_REVOKE: u32 = 5; pub const PROTOCOL_VERSION_NO_SECRET: u32 = 6; pub const DEFAULT_MAX_PROTOCOL_VERSION: u32 = PROTOCOL_VERSION_NO_SECRET;
45
46pub const MIN_PROTOCOL_VERSION: u32 = 2;
48
49pub 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#[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 pub node_id: PubKey,
78}
79
80#[cfg(feature = "developer")]
83#[derive(SerBolt, Debug, Encodable, Decodable)]
84#[message_id(99)]
85pub struct HsmdDevPreinit2 {
86 pub options: HsmdDevPreinit2Options,
87}
88
89#[cfg(feature = "developer")]
91#[derive(SerBoltTlvOptions, Default, Debug, Clone)]
92pub struct HsmdDevPreinit2Options {
93 #[tlv_tag = 1]
95 pub fail_preapprove: Option<bool>,
96 #[tlv_tag = 3]
97 pub no_preapprove_check: Option<bool>,
98
99 #[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#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
151#[message_id(114)]
152pub struct HsmdInitReplyV4 {
153 pub hsm_version: u32,
155 pub hsm_capabilities: ArrayBE<u32>,
158 pub node_id: PubKey,
159 pub bip32: ExtKey,
160 pub bolt12: PubKey,
161}
162
163#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
186#[message_id(1012)]
187pub struct NodeInfo {}
188
189#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
210#[message_id(109)]
211pub struct ClientHsmFdReply {
212 }
214
215#[derive(SerBolt, Debug, Encodable, Decodable)]
217#[message_id(8)]
218pub struct SignInvoice {
219 pub u5bytes: Octets,
220 pub hrp: Octets,
221}
222
223#[derive(SerBolt, Debug, Encodable, Decodable)]
225#[message_id(108)]
226pub struct SignInvoiceReply {
227 pub signature: RecoverableSignature,
228}
229
230#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
240#[message_id(107)]
241pub struct SignWithdrawalReply {
242 pub psbt: WithSize<PsbtWrapper>,
243}
244
245#[derive(SerBolt, Debug, Encodable, Decodable)]
247#[message_id(1)]
248pub struct Ecdh {
249 pub point: PubKey,
250}
251
252#[derive(SerBolt, Debug, Encodable, Decodable)]
254#[message_id(100)]
255pub struct EcdhReply {
256 pub secret: Secret,
257}
258
259#[derive(SerBolt, Debug, Encodable, Decodable)]
262#[message_id(33)]
263pub struct Memleak {}
264
265#[derive(SerBolt, Debug, Encodable, Decodable)]
267#[message_id(133)]
268pub struct MemleakReply {
269 pub result: bool,
270}
271
272#[derive(SerBolt, Debug, Encodable, Decodable)]
274#[message_id(22)]
275pub struct CheckFutureSecret {
276 pub commitment_number: u64,
277 pub secret: DisclosedSecret,
278}
279
280#[derive(SerBolt, Debug, Encodable, Decodable)]
282#[message_id(122)]
283pub struct CheckFutureSecretReply {
284 pub result: bool,
285}
286
287#[derive(SerBolt, Debug, Encodable, Decodable)]
289#[message_id(23)]
290pub struct SignMessage {
291 pub message: Octets,
292}
293
294#[derive(SerBolt, Debug, Encodable, Decodable)]
296#[message_id(123)]
297pub struct SignMessageReply {
298 pub signature: RecoverableSignature,
299}
300
301#[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#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
337#[message_id(38)]
338pub struct PreapproveInvoice {
339 pub invstring: WireString,
340}
341
342#[derive(SerBolt, Debug, Encodable, Decodable)]
344#[message_id(138)]
345pub struct PreapproveInvoiceReply {
346 pub result: bool,
347}
348
349#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
360#[message_id(139)]
361pub struct PreapproveKeysendReply {
362 pub result: bool,
363}
364
365#[derive(SerBolt, Debug, Encodable, Decodable)]
367#[message_id(27)]
368pub struct DeriveSecret {
369 pub info: Octets,
370}
371
372#[derive(SerBolt, Debug, Encodable, Decodable)]
374#[message_id(127)]
375pub struct DeriveSecretReply {
376 pub secret: Secret,
377}
378
379#[derive(SerBolt, Debug, Encodable, Decodable)]
381#[message_id(28)]
382pub struct CheckPubKey {
383 pub index: u32,
384 pub pubkey: PubKey,
385}
386
387#[derive(SerBolt, Debug, Encodable, Decodable)]
389#[message_id(128)]
390pub struct CheckPubKeyReply {
391 pub ok: bool,
392}
393
394#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
406#[message_id(148)]
407pub struct SignAnchorspendReply {
408 pub psbt: WithSize<PsbtWrapper>,
409}
410
411#[derive(SerBolt, Debug, Encodable, Decodable)]
413#[message_id(3)]
414pub struct SignChannelUpdate {
415 pub update: Octets,
416}
417
418#[derive(SerBolt, Debug, Encodable, Decodable)]
420#[message_id(103)]
421pub struct SignChannelUpdateReply {
422 pub update: Octets,
423}
424
425#[derive(SerBolt, Debug, Encodable, Decodable)]
427#[message_id(2)]
428pub struct SignChannelAnnouncement {
429 pub announcement: Octets,
430}
431
432#[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#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
460#[message_id(6)]
461pub struct SignNodeAnnouncement {
462 pub announcement: Octets,
463}
464
465#[derive(SerBolt, Debug, Encodable, Decodable)]
467#[message_id(106)]
468pub struct SignNodeAnnouncementReply {
469 pub signature: Signature,
470}
471
472#[derive(SerBolt, Debug, Encodable, Decodable)]
474#[message_id(18)]
475pub struct GetPerCommitmentPoint {
476 pub commitment_number: u64,
477}
478
479#[derive(SerBolt, Debug, Encodable, Decodable)]
482#[message_id(1018)]
483pub struct GetPerCommitmentPoint2 {
484 pub commitment_number: u64,
485}
486
487#[derive(SerBolt, Debug, Encodable, Decodable)]
489#[message_id(118)]
490pub struct GetPerCommitmentPointReply {
491 pub point: PubKey,
492 pub secret: Option<DisclosedSecret>,
493}
494
495#[derive(SerBolt, Debug, Encodable, Decodable)]
497#[message_id(1118)]
498pub struct GetPerCommitmentPoint2Reply {
499 pub point: PubKey,
500}
501
502#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
523#[message_id(131)]
524pub struct SetupChannelReply {}
525
526#[derive(SerBolt, Debug, Encodable, Decodable)]
528#[message_id(34)]
529pub struct ForgetChannel {
530 pub node_id: PubKey,
531 pub dbid: u64,
532}
533
534#[derive(SerBolt, Debug, Encodable, Decodable)]
536#[message_id(134)]
537pub struct ForgetChannelReply {}
538
539#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
549#[message_id(132)]
550pub struct CheckOutpointReply {
551 pub is_buried: bool,
552}
553
554#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
564#[message_id(137)]
565pub struct LockOutpointReply {}
566
567#[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#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
606#[message_id(40)]
607pub struct RevokeCommitmentTx {
608 pub commitment_number: u64,
609}
610
611#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
629#[message_id(136)]
630pub struct ValidateRevocationReply {}
631
632#[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 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#[derive(SerBolt, Debug, Encodable, Decodable)]
669#[message_id(1005)]
670pub struct SignLocalCommitmentTx2 {
671 pub commitment_number: u64,
672}
673
674#[derive(SerBolt, Debug, Encodable, Decodable)]
676#[message_id(1006)]
677pub struct SignGossipMessage {
678 pub message: Octets,
679}
680
681#[derive(SerBolt, Debug, Encodable, Decodable)]
683#[message_id(1106)]
684pub struct SignGossipMessageReply {
685 pub signature: Signature,
686}
687
688#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
706#[message_id(1000)]
707pub struct Ping {
708 pub id: u16,
709 pub message: WireString,
710}
711
712#[derive(SerBolt, Debug, Encodable, Decodable)]
715#[message_id(1100)]
716pub struct Pong {
717 pub id: u16,
718 pub message: WireString,
719}
720
721#[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#[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#[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#[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#[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#[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#[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#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
832#[message_id(150)]
833pub struct SignHtlcTxMingleReply {
834 pub psbt: WithSize<PsbtWrapper>,
835}
836
837#[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#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
872#[message_id(105)]
873pub struct SignCommitmentTxReply {
874 pub signature: BitcoinSignature,
875}
876
877#[derive(SerBolt, Debug, Encodable, Decodable)]
879#[message_id(112)]
880pub struct SignTxReply {
881 pub signature: BitcoinSignature,
882}
883
884#[derive(SerBolt, Debug, Encodable, Decodable)]
886#[message_id(30)]
887pub struct NewChannel {
888 pub peer_id: PubKey,
889 pub dbid: u64,
890}
891
892#[derive(SerBolt, Debug, Encodable, Decodable)]
894#[message_id(130)]
895pub struct NewChannelReply {}
896
897#[derive(SerBolt, Debug, Encodable, Decodable)]
899#[message_id(10)]
900pub struct GetChannelBasepoints {
901 pub node_id: PubKey,
902 pub dbid: u64,
903}
904
905#[derive(SerBolt, Debug, Encodable, Decodable)]
907#[message_id(110)]
908pub struct GetChannelBasepointsReply {
909 pub basepoints: Basepoints,
910 pub funding: PubKey,
911}
912
913#[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#[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#[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#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
962#[message_id(2002)]
963pub struct TipInfo {}
964
965#[derive(SerBolt, Debug, Encodable, Decodable)]
967#[message_id(2102)]
968pub struct TipInfoReply {
969 pub height: u32,
970 pub block_hash: BlockHash,
971}
972
973#[derive(SerBolt, Debug, Encodable, Decodable)]
975#[message_id(2003)]
976pub struct ForwardWatches {}
977
978#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
992#[message_id(2104)]
993pub struct ReverseWatchesReply {
994 pub txids: Array<Txid>,
995 pub outpoints: Array<OutPoint>,
996}
997
998pub 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 pub header: Octets,
1033 pub unspent_proof: Option<DebugTxoProof>,
1035}
1036
1037#[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 pub unspent_proof: Option<LargeOctets>,
1048 pub prev_block_header: BlockHeader,
1049 pub prev_filter_header: FilterHeader,
1050}
1051
1052#[derive(SerBolt, Debug, Encodable, Decodable)]
1054#[message_id(2106)]
1055pub struct RemoveBlockReply {}
1056
1057#[derive(SerBolt, Debug, Encodable, Decodable)]
1059#[message_id(2008)]
1060pub struct GetHeartbeat {}
1061
1062#[derive(SerBolt, Debug, Encodable, Decodable)]
1064#[message_id(2108)]
1065pub struct GetHeartbeatReply {
1066 pub heartbeat: Octets,
1067}
1068
1069#[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#[derive(SerBolt, Debug, Encodable, Decodable)]
1085#[message_id(2109)]
1086pub struct BlockChunkReply {}
1087
1088#[derive(Debug, Decodable)]
1090pub struct Unknown {
1091 pub message_type: u16,
1093}
1094
1095#[derive(SerBolt, Debug, Encodable, Decodable)]
1096#[message_id(3000)]
1097pub struct SignerError {
1098 pub code: u16,
1100 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#[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 #[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
1230pub fn read<R: Read>(reader: &mut R) -> Result<Message> {
1236 let len = reader.read_u32_be()?;
1237 from_reader(reader, len)
1238}
1239
1240pub 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
1262pub 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
1275pub 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
1293pub 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#[derive(Debug)]
1337pub struct SerialRequestHeader {
1338 pub sequence: u16,
1339 pub peer_id: [u8; 33],
1340 pub dbid: u64,
1341}
1342
1343pub 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
1355pub 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
1362pub 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
1377pub 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 super::*;
1396 use alloc::{format, vec::Vec};
1397 use bitcoin::consensus::Encodable;
1398 use core::fmt::Debug;
1399 use serde_bolt::{io::Cursor, Array, WireString};
1400 use test_log::test;
1401
1402 fn sample_array<T: Encodable + Decodable + Debug + Clone>(item: T, count: usize) -> Array<T> {
1403 Array(vec![item; count])
1404 }
1405
1406 fn roundtrip<T: SerBolt + DeBolt>(msg: T) -> T {
1407 let ser = msg.as_vec();
1408 T::from_vec(ser).unwrap()
1409 }
1410
1411 #[test]
1412 fn message_name_from_vec_test() {
1413 let short_vec = vec![0x01];
1415 assert_eq!(message_name_from_vec(&short_vec), "ShortRead");
1416
1417 let valid_vec = vec![0x00, 11];
1419 assert_eq!(message_name_from_vec(&valid_vec), "HsmdInit");
1420
1421 let unknown_vec = vec![0xFF, 0xFF];
1423 assert_eq!(message_name_from_vec(&unknown_vec), "Unknown");
1424 }
1425
1426 #[test]
1427 fn roundtrip_test() {
1428 let msg = SignChannelAnnouncementReply {
1429 node_signature: Signature([0; 64]),
1430 bitcoin_signature: Signature([1; 64]),
1431 };
1432
1433 let ser = msg.as_vec();
1434 let dmsg = from_vec(ser).unwrap();
1435 if let Message::SignChannelAnnouncementReply(dmsg) = dmsg {
1436 assert_eq!(dmsg.node_signature.0, msg.node_signature.0);
1437 assert_eq!(dmsg.bitcoin_signature.0, msg.bitcoin_signature.0);
1438 } else {
1439 panic!("bad deser type")
1440 }
1441 }
1442
1443 #[test]
1444 fn name_test() {
1445 assert_eq!(Message::NodeInfo(NodeInfo {}).inner().name(), "NodeInfo");
1446 assert_eq!(
1447 Message::Unknown(Unknown { message_type: 0 }).inner().name(),
1448 "UnknownPlaceholder"
1449 );
1450 }
1451
1452 #[test]
1453 fn tlv_roundtrip_test() {
1454 #[cfg(feature = "developer")]
1455 {
1456 let mut options = HsmdDevPreinit2Options::default();
1457 options.network_name = Some(WireString("testnet".as_bytes().to_vec()));
1458 options.seed = Some(DevSecret([42u8; 32]));
1459 options.fail_preapprove = Some(true);
1460 options.no_preapprove_check = Some(false);
1461 options.derivation_style = Some(1);
1462 options.allowlist = Some(sample_array(WireString("test".as_bytes().to_vec()), 1));
1463 let msg = HsmdDevPreinit2 { options };
1464 let dmsg = roundtrip(msg);
1465 assert_eq!(dmsg.options.network_name, Some(WireString("testnet".as_bytes().to_vec())));
1466 assert_eq!(dmsg.options.seed, Some(DevSecret([42u8; 32])));
1467 assert_eq!(dmsg.options.fail_preapprove, Some(true));
1468 assert_eq!(dmsg.options.no_preapprove_check, Some(false));
1469 assert_eq!(dmsg.options.derivation_style, Some(1));
1470 assert_eq!(
1471 dmsg.options.allowlist,
1472 Some(sample_array(WireString("test".as_bytes().to_vec()), 1))
1473 );
1474 }
1475 }
1476
1477 #[test]
1478 fn read_write_functions_test() {
1479 let msg = SignChannelAnnouncementReply {
1480 node_signature: Signature([0x48; 64]),
1481 bitcoin_signature: Signature([0x48; 64]),
1482 };
1483 let ser = msg.as_vec();
1484 let len = (ser.len() as u32).to_be_bytes().to_vec();
1485 let mut buf = len;
1486 buf.extend(ser.clone());
1487
1488 let expected_node_signature = "48484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848";
1489 let expected_bitcoin_signature = "48484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848";
1490 let expexted_raw = vec![
1491 0, 102, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
1492 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
1493 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
1494 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
1495 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
1496 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72,
1497 ];
1498
1499 let mut cursor = Cursor::new(buf.clone());
1501 let dmsg = read(&mut cursor).unwrap();
1502 if let Message::SignChannelAnnouncementReply(dmsg) = dmsg {
1503 assert_eq!(format!("{:?}", dmsg.node_signature), expected_node_signature);
1504 assert_eq!(format!("{:?}", dmsg.bitcoin_signature), expected_bitcoin_signature);
1505 } else {
1506 panic!("bad deser type")
1507 }
1508
1509 let mut cursor = Cursor::new(buf.clone());
1511 let dmsg: SignChannelAnnouncementReply = read_message(&mut cursor).unwrap();
1512 assert_eq!(format!("{:?}", dmsg.node_signature), expected_node_signature);
1513 assert_eq!(format!("{:?}", dmsg.bitcoin_signature), expected_bitcoin_signature);
1514
1515 let mut cursor = Cursor::new(buf.clone());
1517 let raw = read_raw(&mut cursor).unwrap();
1518 assert_eq!(raw, expexted_raw);
1519
1520 let mut write_buf = Vec::new();
1522 write(&mut write_buf, msg).unwrap();
1523 let mut cursor = Cursor::new(write_buf);
1524 let dmsg: SignChannelAnnouncementReply = read_message(&mut cursor).unwrap();
1525 assert_eq!(format!("{:?}", dmsg.node_signature), expected_node_signature);
1526 assert_eq!(format!("{:?}", dmsg.bitcoin_signature), expected_bitcoin_signature);
1527
1528 let mut write_buf = Vec::new();
1530 write_vec(&mut write_buf, ser.clone()).unwrap();
1531 let mut cursor = Cursor::new(write_buf);
1532 let raw = read_raw(&mut cursor).unwrap();
1533 assert_eq!(raw, expexted_raw);
1534 }
1535
1536 #[test]
1537 fn serial_header_tests() {
1538 let srh = SerialRequestHeader { sequence: 123, peer_id: [2u8; 33], dbid: 456 };
1539 let mut buf = Vec::new();
1540 write_serial_request_header(&mut buf, &srh).unwrap();
1541 let mut cursor = Cursor::new(buf);
1542 let read_srh = read_serial_request_header(&mut cursor).unwrap();
1543 assert_eq!(read_srh.sequence, 123);
1544 assert_eq!(read_srh.dbid, 456);
1545
1546 let mut buf = Vec::new();
1547 write_serial_response_header(&mut buf, 123).unwrap();
1548 let mut cursor = Cursor::new(buf);
1549 read_serial_response_header(&mut cursor, 123).unwrap();
1550
1551 let mut buf = vec![0x00, 0x00];
1553 buf.extend(123u16.to_be_bytes());
1554 let mut cursor = Cursor::new(buf);
1555 assert!(matches!(read_serial_request_header(&mut cursor), Err(Error::BadFraming)));
1556
1557 let mut buf = Vec::new();
1559 write_serial_response_header(&mut buf, 123).unwrap();
1560 let mut cursor = Cursor::new(buf);
1561 assert!(matches!(read_serial_response_header(&mut cursor, 124), Err(Error::BadFraming)));
1562 }
1563
1564 #[test]
1565 fn error_cases_test() {
1566 let mut cursor = Cursor::new(vec![0x00, 0x00, 0x00, 0x01]);
1568 assert!(matches!(read(&mut cursor), Err(Error::ShortRead)));
1569
1570 let mut cursor = Cursor::new((MAX_MESSAGE_SIZE + 1).to_be_bytes().to_vec());
1572 assert!(matches!(read(&mut cursor), Err(Error::MessageTooLarge)));
1573
1574 let msg = SignChannelAnnouncementReply {
1576 node_signature: Signature([0x48; 64]),
1577 bitcoin_signature: Signature([0x48; 64]),
1578 };
1579 let mut ser = msg.as_vec();
1580 ser.push(0x00); let len = (ser.len() as u32).to_be_bytes().to_vec();
1582 let mut buf = len;
1583 buf.extend(ser);
1584 let mut cursor = Cursor::new(buf.clone());
1585 assert!(matches!(read(&mut cursor), Err(Error::TrailingBytes(1, 102))));
1586
1587 let mut cursor = Cursor::new(buf.clone());
1589 let result: Result<SignInvoiceReply> = read_message(&mut cursor);
1590 assert!(matches!(result, Err(Error::UnexpectedType(102))));
1591 }
1592
1593 #[derive(SerBolt, Debug, Encodable, Decodable)]
1594 #[message_id(9999)]
1595 pub struct TestTlvWithDupTags {
1596 pub options: TestTlvOptionsWithDupTags,
1597 }
1598
1599 #[derive(SerBoltTlvOptions, Default, Debug)]
1601 pub struct TestTlvOptionsWithDupTags {
1602 #[tlv_tag = 9]
1603 pub field1: Option<bool>,
1604 #[tlv_tag = 10]
1605 pub field2: Option<bool>,
1606 #[tlv_tag = 10]
1607 pub field3: Option<bool>,
1608 #[tlv_tag = 12]
1609 pub field4: Option<bool>,
1610 }
1611
1612 #[test]
1613 #[should_panic(expected = "assertion failed: t < 10u64")]
1614 fn ser_bolt_tlv_options_dup_tags_test() {
1615 let mut options = TestTlvOptionsWithDupTags::default();
1616 options.field3 = Some(true);
1617 options.field2 = Some(false);
1618 let msg = TestTlvWithDupTags { options };
1619 let _ser = msg.as_vec();
1620 }
1621
1622 #[derive(SerBolt, Debug, Encodable, Decodable)]
1623 #[message_id(9999)]
1624 pub struct TestTlvWithDescTags {
1625 pub options: TestTlvOptionsWithDescTags,
1626 }
1627
1628 #[derive(SerBoltTlvOptions, Default, Debug)]
1630 pub struct TestTlvOptionsWithDescTags {
1631 #[tlv_tag = 12]
1632 pub field1: Option<bool>,
1633 #[tlv_tag = 11]
1634 pub field2: Option<bool>,
1635 #[tlv_tag = 10]
1636 pub field3: Option<bool>,
1637 }
1638
1639 #[test]
1640 fn ser_bolt_tlv_options_desc_tags_test() {
1641 let mut options = TestTlvOptionsWithDescTags::default();
1642 options.field3 = Some(true);
1643 options.field2 = Some(false);
1644 let msg = TestTlvWithDescTags { options };
1645 let _ser = msg.as_vec();
1646 }
1647
1648 #[derive(SerBoltTlvOptions, Default, Debug)]
1651 pub struct TestTlvOptionsEvenSender {
1652 #[tlv_tag = 12]
1653 pub field1: Option<bool>,
1654 #[tlv_tag = 11]
1655 pub field2: Option<bool>,
1656 #[tlv_tag = 10]
1657 pub field3: Option<bool>,
1658 #[tlv_tag = 42]
1659 pub mandatory: Option<bool>,
1660 }
1661
1662 #[derive(SerBoltTlvOptions, Default, Debug)]
1663 pub struct TestTlvOptionsOddOnlyReceiver {
1664 #[tlv_tag = 12]
1665 pub field1: Option<bool>,
1666 #[tlv_tag = 11]
1667 pub field2: Option<bool>,
1668 #[tlv_tag = 10]
1669 pub field3: Option<bool>,
1670 }
1671
1672 #[test]
1673 fn ser_bolt_tlv_even_is_mandatory_test() {
1674 let mut options = TestTlvOptionsEvenSender::default();
1676 options.field1 = Some(true);
1677 let tlvdata = crate::msgs::bitcoin::consensus::serialize(&options);
1678 let dmsg: TestTlvOptionsOddOnlyReceiver =
1679 crate::msgs::bitcoin::consensus::deserialize(&tlvdata).unwrap();
1680 assert_eq!(dmsg.field1, Some(true));
1681 assert_eq!(dmsg.field2, None);
1682
1683 options.mandatory = Some(true);
1685 let tlvdata = crate::msgs::bitcoin::consensus::serialize(&options);
1686 let rv =
1687 crate::msgs::bitcoin::consensus::deserialize::<TestTlvOptionsOddOnlyReceiver>(&tlvdata);
1688 match rv {
1689 Ok(_) => panic!("Expected an error, but got Ok"),
1690 Err(e) => match e {
1691 bitcoin::consensus::encode::Error::ParseFailed(expected_msg) => {
1692 assert_eq!(expected_msg, "decode_tlv_stream failed")
1693 }
1694 _ => panic!("Unexpected error type"),
1695 },
1696 }
1697 }
1698}