1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::serialize;
6 use bitcoin::blockdata::script::Script;
11 use std::result::Result;
13 use util::{byte_utils, internal_traits, events};
14 use util::ser::{Readable, Writeable, Writer};
16 pub trait MsgEncodable {
17 fn encode(&self) -> Vec<u8>;
19 fn encoded_len(&self) -> usize { self.encode().len() }
21 fn encode_with_len(&self) -> Vec<u8> {
22 let enc = self.encode();
23 let mut res = Vec::with_capacity(enc.len() + 2);
24 res.extend_from_slice(&byte_utils::be16_to_array(enc.len() as u16));
25 res.extend_from_slice(&enc);
30 pub enum DecodeError {
31 /// Unknown realm byte in an OnionHopData packet
33 /// Unknown feature mandating we fail to parse message
34 UnknownRequiredFeature,
35 /// Failed to decode a public key (ie it's invalid)
37 /// Failed to decode a signature (ie it's invalid)
39 /// Value expected to be text wasn't decodable as text
43 /// node_announcement included more than one address of a given type!
44 ExtraAddressesPerType,
45 /// A length descriptor in the packet didn't describe the later data correctly
46 /// (currently only generated in node_announcement)
48 /// Error from std::io
50 /// 1 or 0 is not found for boolean value
54 /// Tracks localfeatures which are only in init messages
55 #[derive(Clone, PartialEq)]
56 pub struct LocalFeatures {
61 pub fn new() -> LocalFeatures {
67 pub fn supports_data_loss_protect(&self) -> bool {
68 self.flags.len() > 0 && (self.flags[0] & 3) != 0
70 pub fn requires_data_loss_protect(&self) -> bool {
71 self.flags.len() > 0 && (self.flags[0] & 1) != 0
74 pub fn initial_routing_sync(&self) -> bool {
75 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
77 pub fn set_initial_routing_sync(&mut self) {
78 if self.flags.len() == 0 {
79 self.flags.resize(1, 1 << 3);
81 self.flags[0] |= 1 << 3;
85 pub fn supports_upfront_shutdown_script(&self) -> bool {
86 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
88 pub fn requires_upfront_shutdown_script(&self) -> bool {
89 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
92 pub fn requires_unknown_bits(&self) -> bool {
93 for (idx, &byte) in self.flags.iter().enumerate() {
94 if idx != 0 && (byte & 0x55) != 0 {
96 } else if idx == 0 && (byte & 0x14) != 0 {
103 pub fn supports_unknown_bits(&self) -> bool {
104 for (idx, &byte) in self.flags.iter().enumerate() {
105 if idx != 0 && byte != 0 {
107 } else if idx == 0 && (byte & 0xc4) != 0 {
115 /// Tracks globalfeatures which are in init messages and routing announcements
116 #[derive(Clone, PartialEq)]
117 pub struct GlobalFeatures {
121 impl GlobalFeatures {
122 pub fn new() -> GlobalFeatures {
128 pub fn requires_unknown_bits(&self) -> bool {
129 for &byte in self.flags.iter() {
130 if (byte & 0x55) != 0 {
137 pub fn supports_unknown_bits(&self) -> bool {
138 for &byte in self.flags.iter() {
148 pub global_features: GlobalFeatures,
149 pub local_features: LocalFeatures,
152 pub struct ErrorMessage {
153 pub channel_id: [u8; 32],
166 pub struct OpenChannel {
167 pub chain_hash: Sha256dHash,
168 pub temporary_channel_id: [u8; 32],
169 pub funding_satoshis: u64,
171 pub dust_limit_satoshis: u64,
172 pub max_htlc_value_in_flight_msat: u64,
173 pub channel_reserve_satoshis: u64,
174 pub htlc_minimum_msat: u64,
175 pub feerate_per_kw: u32,
176 pub to_self_delay: u16,
177 pub max_accepted_htlcs: u16,
178 pub funding_pubkey: PublicKey,
179 pub revocation_basepoint: PublicKey,
180 pub payment_basepoint: PublicKey,
181 pub delayed_payment_basepoint: PublicKey,
182 pub htlc_basepoint: PublicKey,
183 pub first_per_commitment_point: PublicKey,
184 pub channel_flags: u8,
185 pub shutdown_scriptpubkey: Option<Script>,
188 pub struct AcceptChannel {
189 pub temporary_channel_id: [u8; 32],
190 pub dust_limit_satoshis: u64,
191 pub max_htlc_value_in_flight_msat: u64,
192 pub channel_reserve_satoshis: u64,
193 pub htlc_minimum_msat: u64,
194 pub minimum_depth: u32,
195 pub to_self_delay: u16,
196 pub max_accepted_htlcs: u16,
197 pub funding_pubkey: PublicKey,
198 pub revocation_basepoint: PublicKey,
199 pub payment_basepoint: PublicKey,
200 pub delayed_payment_basepoint: PublicKey,
201 pub htlc_basepoint: PublicKey,
202 pub first_per_commitment_point: PublicKey,
203 pub shutdown_scriptpubkey: Option<Script>,
206 pub struct FundingCreated {
207 pub temporary_channel_id: [u8; 32],
208 pub funding_txid: Sha256dHash,
209 pub funding_output_index: u16,
210 pub signature: Signature,
213 pub struct FundingSigned {
214 pub channel_id: [u8; 32],
215 pub signature: Signature,
218 pub struct FundingLocked {
219 pub channel_id: [u8; 32],
220 pub next_per_commitment_point: PublicKey,
223 pub struct Shutdown {
224 pub channel_id: [u8; 32],
225 pub scriptpubkey: Script,
228 pub struct ClosingSigned {
229 pub channel_id: [u8; 32],
230 pub fee_satoshis: u64,
231 pub signature: Signature,
235 pub struct UpdateAddHTLC {
236 pub channel_id: [u8; 32],
238 pub amount_msat: u64,
239 pub payment_hash: [u8; 32],
240 pub cltv_expiry: u32,
241 pub onion_routing_packet: OnionPacket,
245 pub struct UpdateFulfillHTLC {
246 pub channel_id: [u8; 32],
248 pub payment_preimage: [u8; 32],
252 pub struct UpdateFailHTLC {
253 pub channel_id: [u8; 32],
255 pub reason: OnionErrorPacket,
259 pub struct UpdateFailMalformedHTLC {
260 pub channel_id: [u8; 32],
262 pub sha256_of_onion: [u8; 32],
263 pub failure_code: u16,
267 pub struct CommitmentSigned {
268 pub channel_id: [u8; 32],
269 pub signature: Signature,
270 pub htlc_signatures: Vec<Signature>,
273 pub struct RevokeAndACK {
274 pub channel_id: [u8; 32],
275 pub per_commitment_secret: [u8; 32],
276 pub next_per_commitment_point: PublicKey,
279 pub struct UpdateFee {
280 pub channel_id: [u8; 32],
281 pub feerate_per_kw: u32,
284 pub struct DataLossProtect {
285 pub your_last_per_commitment_secret: [u8; 32],
286 pub my_current_per_commitment_point: PublicKey,
289 pub struct ChannelReestablish {
290 pub channel_id: [u8; 32],
291 pub next_local_commitment_number: u64,
292 pub next_remote_commitment_number: u64,
293 pub data_loss_protect: Option<DataLossProtect>,
297 pub struct AnnouncementSignatures {
298 pub channel_id: [u8; 32],
299 pub short_channel_id: u64,
300 pub node_signature: Signature,
301 pub bitcoin_signature: Signature,
305 pub enum NetAddress {
319 ed25519_pubkey: [u8; 32],
326 fn get_id(&self) -> u8 {
328 &NetAddress::IPv4 {..} => { 1 },
329 &NetAddress::IPv6 {..} => { 2 },
330 &NetAddress::OnionV2 {..} => { 3 },
331 &NetAddress::OnionV3 {..} => { 4 },
336 pub struct UnsignedNodeAnnouncement {
337 pub features: GlobalFeatures,
339 pub node_id: PublicKey,
342 /// List of addresses on which this node is reachable. Note that you may only have up to one
343 /// address of each type, if you have more, they may be silently discarded or we may panic!
344 pub addresses: Vec<NetAddress>,
345 pub excess_address_data: Vec<u8>,
346 pub excess_data: Vec<u8>,
348 pub struct NodeAnnouncement {
349 pub signature: Signature,
350 pub contents: UnsignedNodeAnnouncement,
353 #[derive(PartialEq, Clone)]
354 pub struct UnsignedChannelAnnouncement {
355 pub features: GlobalFeatures,
356 pub chain_hash: Sha256dHash,
357 pub short_channel_id: u64,
358 pub node_id_1: PublicKey,
359 pub node_id_2: PublicKey,
360 pub bitcoin_key_1: PublicKey,
361 pub bitcoin_key_2: PublicKey,
362 pub excess_data: Vec<u8>,
364 #[derive(PartialEq, Clone)]
365 pub struct ChannelAnnouncement {
366 pub node_signature_1: Signature,
367 pub node_signature_2: Signature,
368 pub bitcoin_signature_1: Signature,
369 pub bitcoin_signature_2: Signature,
370 pub contents: UnsignedChannelAnnouncement,
373 #[derive(PartialEq, Clone)]
374 pub struct UnsignedChannelUpdate {
375 pub chain_hash: Sha256dHash,
376 pub short_channel_id: u64,
379 pub cltv_expiry_delta: u16,
380 pub htlc_minimum_msat: u64,
381 pub fee_base_msat: u32,
382 pub fee_proportional_millionths: u32,
383 pub excess_data: Vec<u8>,
385 #[derive(PartialEq, Clone)]
386 pub struct ChannelUpdate {
387 pub signature: Signature,
388 pub contents: UnsignedChannelUpdate,
391 /// Used to put an error message in a HandleError
392 pub enum ErrorAction {
393 /// The peer took some action which made us think they were useless. Disconnect them.
395 msg: Option<ErrorMessage>
397 /// The peer did something harmless that we weren't able to process, just log and ignore
399 /// The peer did something incorrect. Tell them.
405 pub struct HandleError { //TODO: rename me
406 pub err: &'static str,
407 pub action: Option<ErrorAction>, //TODO: Make this required
410 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
411 /// transaction updates if they were pending.
412 pub struct CommitmentUpdate {
413 pub update_add_htlcs: Vec<UpdateAddHTLC>,
414 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
415 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
416 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
417 pub commitment_signed: CommitmentSigned,
420 pub enum HTLCFailChannelUpdate {
421 ChannelUpdateMessage {
425 short_channel_id: u64,
429 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
430 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
431 /// paralell when the two calls have the same their_node_id.
432 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
434 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
435 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
436 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
437 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
438 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
441 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
442 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
445 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
446 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
447 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
448 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
449 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
450 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
452 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
454 // Channel-to-announce:
455 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
457 // Connection loss/reestablish:
458 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
459 /// is believed to be possible in the future (eg they're sending us messages we don't
460 /// understand or indicate they require unknown feature bits), no_connection_possible is set
461 /// and any outstanding channels should be failed.
462 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
464 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
465 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
468 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
471 pub trait RoutingMessageHandler : Send + Sync {
472 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
473 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
474 /// or returning an Err otherwise.
475 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
476 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
477 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
480 pub struct OnionRealm0HopData {
481 pub short_channel_id: u64,
482 pub amt_to_forward: u64,
483 pub outgoing_cltv_value: u32,
484 // 12 bytes of 0-padding
487 pub struct OnionHopData {
489 pub data: OnionRealm0HopData,
492 unsafe impl internal_traits::NoDealloc for OnionHopData{}
495 pub struct OnionPacket {
497 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
498 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
499 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
500 pub public_key: Result<PublicKey, secp256k1::Error>,
501 pub hop_data: [u8; 20*65],
505 pub struct DecodedOnionErrorPacket {
507 pub failuremsg: Vec<u8>,
512 pub struct OnionErrorPacket {
513 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
514 // (TODO) We limit it in decode to much lower...
518 impl Error for DecodeError {
519 fn description(&self) -> &str {
521 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
522 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
523 DecodeError::BadPublicKey => "Invalid public key in packet",
524 DecodeError::BadSignature => "Invalid signature in packet",
525 DecodeError::BadText => "Invalid text in packet",
526 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
527 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
528 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
529 DecodeError::Io(ref e) => e.description(),
530 DecodeError::InvalidValue => "0 or 1 is not found for boolean",
534 impl fmt::Display for DecodeError {
535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536 f.write_str(self.description())
540 impl fmt::Debug for HandleError {
541 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
542 f.write_str(self.err)
546 impl From<::std::io::Error> for DecodeError {
547 fn from(e: ::std::io::Error) -> Self {
548 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
549 DecodeError::ShortRead
556 impl MsgEncodable for GlobalFeatures {
557 fn encode(&self) -> Vec<u8> {
558 let mut res = Vec::with_capacity(self.flags.len() + 2);
559 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
560 res.extend_from_slice(&self.flags[..]);
563 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
566 impl MsgEncodable for ChannelReestablish {
567 fn encode(&self) -> Vec<u8> {
568 let mut res = Vec::with_capacity(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
570 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
571 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
572 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
574 if let &Some(ref data_loss_protect) = &self.data_loss_protect {
575 res.extend_from_slice(&data_loss_protect.your_last_per_commitment_secret[..]);
576 res.extend_from_slice(&data_loss_protect.my_current_per_commitment_point.serialize());
582 impl MsgEncodable for UnsignedNodeAnnouncement {
583 fn encode(&self) -> Vec<u8> {
584 let features = self.features.encode();
585 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len()*7 + self.excess_address_data.len() + self.excess_data.len());
586 res.extend_from_slice(&features[..]);
587 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
588 res.extend_from_slice(&self.node_id.serialize());
589 res.extend_from_slice(&self.rgb);
590 res.extend_from_slice(&self.alias);
591 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
592 let mut addrs_to_encode = self.addresses.clone();
593 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
594 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
595 for addr in addrs_to_encode.iter() {
597 &NetAddress::IPv4{addr, port} => {
599 addr_slice.extend_from_slice(&addr);
600 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
602 &NetAddress::IPv6{addr, port} => {
604 addr_slice.extend_from_slice(&addr);
605 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
607 &NetAddress::OnionV2{addr, port} => {
609 addr_slice.extend_from_slice(&addr);
610 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
612 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
614 addr_slice.extend_from_slice(&ed25519_pubkey);
615 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
616 addr_slice.push(version);
617 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
621 res.extend_from_slice(&byte_utils::be16_to_array((addr_slice.len() + self.excess_address_data.len()) as u16));
622 res.extend_from_slice(&addr_slice[..]);
623 res.extend_from_slice(&self.excess_address_data[..]);
624 res.extend_from_slice(&self.excess_data[..]);
629 impl MsgEncodable for UnsignedChannelAnnouncement {
630 fn encode(&self) -> Vec<u8> {
631 let features = self.features.encode();
632 let mut res = Vec::with_capacity(172 + features.len() + self.excess_data.len());
633 res.extend_from_slice(&features[..]);
634 res.extend_from_slice(&self.chain_hash[..]);
635 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
636 res.extend_from_slice(&self.node_id_1.serialize());
637 res.extend_from_slice(&self.node_id_2.serialize());
638 res.extend_from_slice(&self.bitcoin_key_1.serialize());
639 res.extend_from_slice(&self.bitcoin_key_2.serialize());
640 res.extend_from_slice(&self.excess_data[..]);
645 impl MsgEncodable for UnsignedChannelUpdate {
646 fn encode(&self) -> Vec<u8> {
647 let mut res = Vec::with_capacity(64 + self.excess_data.len());
648 res.extend_from_slice(&self.chain_hash[..]);
649 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
650 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
651 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
652 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
653 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
654 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
655 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
656 res.extend_from_slice(&self.excess_data[..]);
661 impl MsgEncodable for ChannelUpdate {
662 fn encode(&self) -> Vec<u8> {
663 let mut res = Vec::with_capacity(128);
664 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
665 res.extend_from_slice(&self.contents.encode()[..]);
670 impl MsgEncodable for OnionRealm0HopData {
671 fn encode(&self) -> Vec<u8> {
672 let mut res = Vec::with_capacity(32);
673 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
674 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
675 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
681 impl MsgEncodable for OnionHopData {
682 fn encode(&self) -> Vec<u8> {
683 let mut res = Vec::with_capacity(65);
684 res.push(self.realm);
685 res.extend_from_slice(&self.data.encode()[..]);
686 res.extend_from_slice(&self.hmac);
691 impl MsgEncodable for OnionPacket {
692 fn encode(&self) -> Vec<u8> {
693 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
694 res.push(self.version);
695 match self.public_key {
696 Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
697 Err(_) => res.extend_from_slice(&[0; 33]),
699 res.extend_from_slice(&self.hop_data);
700 res.extend_from_slice(&self.hmac);
705 impl MsgEncodable for DecodedOnionErrorPacket {
706 fn encode(&self) -> Vec<u8> {
707 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
708 res.extend_from_slice(&self.hmac);
709 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
710 res.extend_from_slice(&self.failuremsg);
711 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
712 res.extend_from_slice(&self.pad);
717 impl_writeable_len_match!(AcceptChannel, {
718 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
721 temporary_channel_id,
723 max_htlc_value_in_flight_msat,
724 channel_reserve_satoshis,
730 revocation_basepoint,
732 delayed_payment_basepoint,
734 first_per_commitment_point,
735 shutdown_scriptpubkey
738 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
745 impl<W: Writer> Writeable<W> for ChannelReestablish {
746 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
747 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
748 self.channel_id.write(w)?;
749 self.next_local_commitment_number.write(w)?;
750 self.next_remote_commitment_number.write(w)?;
751 if let Some(ref data_loss_protect) = self.data_loss_protect {
752 data_loss_protect.your_last_per_commitment_secret.write(w)?;
753 data_loss_protect.my_current_per_commitment_point.write(w)?;
759 impl<R: Read> Readable<R> for ChannelReestablish{
760 fn read(r: &mut R) -> Result<Self, DecodeError> {
762 channel_id: Readable::read(r)?,
763 next_local_commitment_number: Readable::read(r)?,
764 next_remote_commitment_number: Readable::read(r)?,
766 match <[u8; 32] as Readable<R>>::read(r) {
767 Ok(your_last_per_commitment_secret) =>
768 Some(DataLossProtect {
769 your_last_per_commitment_secret,
770 my_current_per_commitment_point: Readable::read(r)?,
772 Err(DecodeError::ShortRead) => None,
773 Err(e) => return Err(e)
780 impl_writeable!(ClosingSigned, 32+8+64, {
786 impl_writeable_len_match!(CommitmentSigned, {
787 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
794 impl_writeable_len_match!(DecodedOnionErrorPacket, {
795 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
802 impl_writeable!(FundingCreated, 32+32+2+64, {
803 temporary_channel_id,
805 funding_output_index,
809 impl_writeable!(FundingSigned, 32+64, {
814 impl_writeable!(FundingLocked, 32+33, {
816 next_per_commitment_point
819 impl_writeable_len_match!(GlobalFeatures, {
820 { GlobalFeatures { ref flags }, flags.len() + 2 }
825 impl_writeable_len_match!(LocalFeatures, {
826 { LocalFeatures { ref flags }, flags.len() + 2 }
831 impl_writeable_len_match!(Init, {
832 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
838 impl_writeable_len_match!(OpenChannel, {
839 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
840 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
843 temporary_channel_id,
847 max_htlc_value_in_flight_msat,
848 channel_reserve_satoshis,
854 revocation_basepoint,
856 delayed_payment_basepoint,
858 first_per_commitment_point,
860 shutdown_scriptpubkey
863 impl_writeable!(RevokeAndACK, 32+32+33, {
865 per_commitment_secret,
866 next_per_commitment_point
869 impl_writeable_len_match!(Shutdown, {
870 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
876 impl_writeable_len_match!(UpdateFailHTLC, {
877 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
884 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
891 impl_writeable!(UpdateFee, 32+4, {
896 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
902 impl_writeable_len_match!(OnionErrorPacket, {
903 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
908 impl<W: Writer> Writeable<W> for OnionPacket {
909 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
910 w.size_hint(1 + 33 + 20*65 + 32);
911 self.version.write(w)?;
912 match self.public_key {
913 Ok(pubkey) => pubkey.write(w)?,
914 Err(_) => [0u8;33].write(w)?,
916 w.write_all(&self.hop_data)?;
922 impl<R: Read> Readable<R> for OnionPacket {
923 fn read(r: &mut R) -> Result<Self, DecodeError> {
925 version: Readable::read(r)?,
927 let mut buf = [0u8;33];
928 r.read_exact(&mut buf)?;
929 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
931 hop_data: Readable::read(r)?,
932 hmac: Readable::read(r)?,
937 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
946 impl<W: Writer> Writeable<W> for OnionRealm0HopData {
947 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
949 self.short_channel_id.write(w)?;
950 self.amt_to_forward.write(w)?;
951 self.outgoing_cltv_value.write(w)?;
952 w.write_all(&[0;12])?;
957 impl<R: Read> Readable<R> for OnionRealm0HopData {
958 fn read(r: &mut R) -> Result<Self, DecodeError> {
959 Ok(OnionRealm0HopData {
960 short_channel_id: Readable::read(r)?,
961 amt_to_forward: Readable::read(r)?,
962 outgoing_cltv_value: {
963 let v: u32 = Readable::read(r)?;
964 r.read_exact(&mut [0; 12])?;
971 impl<W: Writer> Writeable<W> for OnionHopData {
972 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
974 self.realm.write(w)?;
981 impl<R: Read> Readable<R> for OnionHopData {
982 fn read(r: &mut R) -> Result<Self, DecodeError> {
985 let r: u8 = Readable::read(r)?;
987 return Err(DecodeError::UnknownRealmByte);
991 data: Readable::read(r)?,
992 hmac: Readable::read(r)?,
997 impl<W: Writer> Writeable<W> for Ping {
998 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
999 w.size_hint(self.byteslen as usize + 4);
1000 self.ponglen.write(w)?;
1001 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1006 impl<R: Read> Readable<R> for Ping {
1007 fn read(r: &mut R) -> Result<Self, DecodeError> {
1009 ponglen: Readable::read(r)?,
1011 let byteslen = Readable::read(r)?;
1012 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1019 impl<W: Writer> Writeable<W> for Pong {
1020 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1021 w.size_hint(self.byteslen as usize + 2);
1022 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1027 impl<R: Read> Readable<R> for Pong {
1028 fn read(r: &mut R) -> Result<Self, DecodeError> {
1031 let byteslen = Readable::read(r)?;
1032 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1039 impl<W: Writer> Writeable<W> for UnsignedChannelAnnouncement {
1040 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1041 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1042 self.features.write(w)?;
1043 self.chain_hash.write(w)?;
1044 self.short_channel_id.write(w)?;
1045 self.node_id_1.write(w)?;
1046 self.node_id_2.write(w)?;
1047 self.bitcoin_key_1.write(w)?;
1048 self.bitcoin_key_2.write(w)?;
1049 w.write_all(&self.excess_data[..])?;
1054 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1055 fn read(r: &mut R) -> Result<Self, DecodeError> {
1058 let f: GlobalFeatures = Readable::read(r)?;
1059 if f.requires_unknown_bits() {
1060 return Err(DecodeError::UnknownRequiredFeature);
1064 chain_hash: Readable::read(r)?,
1065 short_channel_id: Readable::read(r)?,
1066 node_id_1: Readable::read(r)?,
1067 node_id_2: Readable::read(r)?,
1068 bitcoin_key_1: Readable::read(r)?,
1069 bitcoin_key_2: Readable::read(r)?,
1071 let mut excess_data = vec![];
1072 r.read_to_end(&mut excess_data)?;
1079 impl_writeable_len_match!(ChannelAnnouncement, {
1080 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1081 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1085 bitcoin_signature_1,
1086 bitcoin_signature_2,
1090 impl<W: Writer> Writeable<W> for UnsignedChannelUpdate {
1091 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1092 w.size_hint(64 + self.excess_data.len());
1093 self.chain_hash.write(w)?;
1094 self.short_channel_id.write(w)?;
1095 self.timestamp.write(w)?;
1096 self.flags.write(w)?;
1097 self.cltv_expiry_delta.write(w)?;
1098 self.htlc_minimum_msat.write(w)?;
1099 self.fee_base_msat.write(w)?;
1100 self.fee_proportional_millionths.write(w)?;
1101 w.write_all(&self.excess_data[..])?;
1106 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1107 fn read(r: &mut R) -> Result<Self, DecodeError> {
1109 chain_hash: Readable::read(r)?,
1110 short_channel_id: Readable::read(r)?,
1111 timestamp: Readable::read(r)?,
1112 flags: Readable::read(r)?,
1113 cltv_expiry_delta: Readable::read(r)?,
1114 htlc_minimum_msat: Readable::read(r)?,
1115 fee_base_msat: Readable::read(r)?,
1116 fee_proportional_millionths: Readable::read(r)?,
1118 let mut excess_data = vec![];
1119 r.read_to_end(&mut excess_data)?;
1126 impl_writeable_len_match!(ChannelUpdate, {
1127 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1128 64 + excess_data.len() + 64 }
1134 impl<W: Writer> Writeable<W> for ErrorMessage {
1135 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1136 w.size_hint(32 + 2 + self.data.len());
1137 self.channel_id.write(w)?;
1138 (self.data.len() as u16).write(w)?;
1139 w.write_all(self.data.as_bytes())?;
1144 impl<R: Read> Readable<R> for ErrorMessage {
1145 fn read(r: &mut R) -> Result<Self, DecodeError> {
1147 channel_id: Readable::read(r)?,
1149 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1150 let mut data = vec![];
1151 let data_len = r.read_to_end(&mut data)?;
1152 sz = cmp::min(data_len, sz);
1153 match String::from_utf8(data[..sz as usize].to_vec()) {
1155 Err(_) => return Err(DecodeError::BadText),
1162 impl<W: Writer> Writeable<W> for UnsignedNodeAnnouncement {
1163 fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1164 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1165 self.features.write(w)?;
1166 self.timestamp.write(w)?;
1167 self.node_id.write(w)?;
1168 w.write_all(&self.rgb)?;
1169 self.alias.write(w)?;
1171 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1172 let mut addrs_to_encode = self.addresses.clone();
1173 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1174 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1175 for addr in addrs_to_encode.iter() {
1177 &NetAddress::IPv4{addr, port} => {
1179 addr_slice.extend_from_slice(&addr);
1180 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1182 &NetAddress::IPv6{addr, port} => {
1184 addr_slice.extend_from_slice(&addr);
1185 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1187 &NetAddress::OnionV2{addr, port} => {
1189 addr_slice.extend_from_slice(&addr);
1190 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1192 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1194 addr_slice.extend_from_slice(&ed25519_pubkey);
1195 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1196 addr_slice.push(version);
1197 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1201 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1202 w.write_all(&addr_slice[..])?;
1203 w.write_all(&self.excess_address_data[..])?;
1204 w.write_all(&self.excess_data[..])?;
1209 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1210 fn read(r: &mut R) -> Result<Self, DecodeError> {
1211 let features: GlobalFeatures = Readable::read(r)?;
1212 if features.requires_unknown_bits() {
1213 return Err(DecodeError::UnknownRequiredFeature);
1215 let timestamp: u32 = Readable::read(r)?;
1216 let node_id: PublicKey = Readable::read(r)?;
1217 let mut rgb = [0; 3];
1218 r.read_exact(&mut rgb)?;
1219 let alias: [u8; 32] = Readable::read(r)?;
1221 let addrlen: u16 = Readable::read(r)?;
1222 let mut addr_readpos = 0;
1223 let mut addresses = Vec::with_capacity(4);
1227 if addrlen <= addr_readpos { break; }
1228 f = Readable::read(r)?;
1231 if addresses.len() > 0 {
1232 return Err(DecodeError::ExtraAddressesPerType);
1234 if addrlen < addr_readpos + 1 + 6 {
1235 return Err(DecodeError::BadLengthDescriptor);
1237 addresses.push(NetAddress::IPv4 {
1239 let mut addr = [0; 4];
1240 r.read_exact(&mut addr)?;
1243 port: Readable::read(r)?,
1245 addr_readpos += 1 + 6
1248 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1249 return Err(DecodeError::ExtraAddressesPerType);
1251 if addrlen < addr_readpos + 1 + 18 {
1252 return Err(DecodeError::BadLengthDescriptor);
1254 addresses.push(NetAddress::IPv6 {
1256 let mut addr = [0; 16];
1257 r.read_exact(&mut addr)?;
1260 port: Readable::read(r)?,
1262 addr_readpos += 1 + 18
1265 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1266 return Err(DecodeError::ExtraAddressesPerType);
1268 if addrlen < addr_readpos + 1 + 12 {
1269 return Err(DecodeError::BadLengthDescriptor);
1271 addresses.push(NetAddress::OnionV2 {
1273 let mut addr = [0; 10];
1274 r.read_exact(&mut addr)?;
1277 port: Readable::read(r)?,
1279 addr_readpos += 1 + 12
1282 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1283 return Err(DecodeError::ExtraAddressesPerType);
1285 if addrlen < addr_readpos + 1 + 37 {
1286 return Err(DecodeError::BadLengthDescriptor);
1288 addresses.push(NetAddress::OnionV3 {
1289 ed25519_pubkey: Readable::read(r)?,
1290 checksum: Readable::read(r)?,
1291 version: Readable::read(r)?,
1292 port: Readable::read(r)?,
1294 addr_readpos += 1 + 37
1296 _ => { excess = 1; break; }
1300 let mut excess_data = vec![];
1301 let excess_address_data = if addr_readpos < addrlen {
1302 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1303 r.read_exact(&mut excess_address_data[excess..])?;
1305 excess_address_data[0] = f;
1310 excess_data.push(f);
1315 Ok(UnsignedNodeAnnouncement {
1317 timestamp: timestamp,
1321 addresses: addresses,
1322 excess_address_data: excess_address_data,
1324 r.read_to_end(&mut excess_data)?;
1331 impl_writeable_len_match!(NodeAnnouncement, {
1332 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1333 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1342 use ln::msgs::MsgEncodable;
1344 use secp256k1::key::{PublicKey,SecretKey};
1345 use secp256k1::Secp256k1;
1348 fn encoding_channel_reestablish_no_secret() {
1349 let cr = msgs::ChannelReestablish {
1350 channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
1351 next_local_commitment_number: 3,
1352 next_remote_commitment_number: 4,
1353 data_loss_protect: None,
1356 let encoded_value = cr.encode();
1359 vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4]
1364 fn encoding_channel_reestablish_with_secret() {
1366 let secp_ctx = Secp256k1::new();
1367 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1370 let cr = msgs::ChannelReestablish {
1371 channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
1372 next_local_commitment_number: 3,
1373 next_remote_commitment_number: 4,
1374 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1377 let encoded_value = cr.encode();
1380 vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30, 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143]