1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::blockdata::script::Script;
10 use std::result::Result;
12 use util::{byte_utils, events};
13 use util::ser::{Readable, Writeable, Writer};
16 pub enum DecodeError {
17 /// Unknown realm byte in an OnionHopData packet
19 /// Unknown feature mandating we fail to parse message
20 UnknownRequiredFeature,
21 /// Failed to decode a public key (ie it's invalid)
23 /// Failed to decode a signature (ie it's invalid)
25 /// Value expected to be text wasn't decodable as text
29 /// node_announcement included more than one address of a given type!
30 ExtraAddressesPerType,
31 /// A length descriptor in the packet didn't describe the later data correctly
32 /// (currently only generated in node_announcement)
34 /// Error from std::io
36 /// 1 or 0 is not found for boolean value
40 /// Tracks localfeatures which are only in init messages
41 #[derive(Clone, PartialEq)]
42 pub struct LocalFeatures {
47 pub(crate) fn new() -> LocalFeatures {
53 pub(crate) fn supports_data_loss_protect(&self) -> bool {
54 self.flags.len() > 0 && (self.flags[0] & 3) != 0
56 pub(crate) fn requires_data_loss_protect(&self) -> bool {
57 self.flags.len() > 0 && (self.flags[0] & 1) != 0
60 pub(crate) fn initial_routing_sync(&self) -> bool {
61 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
63 pub(crate) fn set_initial_routing_sync(&mut self) {
64 if self.flags.len() == 0 {
65 self.flags.resize(1, 1 << 3);
67 self.flags[0] |= 1 << 3;
71 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
72 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
74 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
75 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
78 pub(crate) fn requires_unknown_bits(&self) -> bool {
79 for (idx, &byte) in self.flags.iter().enumerate() {
80 if idx != 0 && (byte & 0x55) != 0 {
82 } else if idx == 0 && (byte & 0x14) != 0 {
89 pub(crate) fn supports_unknown_bits(&self) -> bool {
90 for (idx, &byte) in self.flags.iter().enumerate() {
91 if idx != 0 && byte != 0 {
93 } else if idx == 0 && (byte & 0xc4) != 0 {
101 /// Tracks globalfeatures which are in init messages and routing announcements
102 #[derive(Clone, PartialEq)]
103 pub struct GlobalFeatures {
107 impl GlobalFeatures {
108 pub(crate) fn new() -> GlobalFeatures {
114 pub(crate) fn requires_unknown_bits(&self) -> bool {
115 for &byte in self.flags.iter() {
116 if (byte & 0x55) != 0 {
123 pub(crate) fn supports_unknown_bits(&self) -> bool {
124 for &byte in self.flags.iter() {
134 pub(crate) global_features: GlobalFeatures,
135 pub(crate) local_features: LocalFeatures,
138 pub struct ErrorMessage {
139 pub(crate) channel_id: [u8; 32],
140 pub(crate) data: String,
144 pub(crate) ponglen: u16,
145 pub(crate) byteslen: u16,
149 pub(crate) byteslen: u16,
152 pub struct OpenChannel {
153 pub(crate) chain_hash: Sha256dHash,
154 pub(crate) temporary_channel_id: [u8; 32],
155 pub(crate) funding_satoshis: u64,
156 pub(crate) push_msat: u64,
157 pub(crate) dust_limit_satoshis: u64,
158 pub(crate) max_htlc_value_in_flight_msat: u64,
159 pub(crate) channel_reserve_satoshis: u64,
160 pub(crate) htlc_minimum_msat: u64,
161 pub(crate) feerate_per_kw: u32,
162 pub(crate) to_self_delay: u16,
163 pub(crate) max_accepted_htlcs: u16,
164 pub(crate) funding_pubkey: PublicKey,
165 pub(crate) revocation_basepoint: PublicKey,
166 pub(crate) payment_basepoint: PublicKey,
167 pub(crate) delayed_payment_basepoint: PublicKey,
168 pub(crate) htlc_basepoint: PublicKey,
169 pub(crate) first_per_commitment_point: PublicKey,
170 pub(crate) channel_flags: u8,
171 pub(crate) shutdown_scriptpubkey: Option<Script>,
174 pub struct AcceptChannel {
175 pub(crate) temporary_channel_id: [u8; 32],
176 pub(crate) dust_limit_satoshis: u64,
177 pub(crate) max_htlc_value_in_flight_msat: u64,
178 pub(crate) channel_reserve_satoshis: u64,
179 pub(crate) htlc_minimum_msat: u64,
180 pub(crate) minimum_depth: u32,
181 pub(crate) to_self_delay: u16,
182 pub(crate) max_accepted_htlcs: u16,
183 pub(crate) funding_pubkey: PublicKey,
184 pub(crate) revocation_basepoint: PublicKey,
185 pub(crate) payment_basepoint: PublicKey,
186 pub(crate) delayed_payment_basepoint: PublicKey,
187 pub(crate) htlc_basepoint: PublicKey,
188 pub(crate) first_per_commitment_point: PublicKey,
189 pub(crate) shutdown_scriptpubkey: Option<Script>,
192 pub struct FundingCreated {
193 pub(crate) temporary_channel_id: [u8; 32],
194 pub(crate) funding_txid: Sha256dHash,
195 pub(crate) funding_output_index: u16,
196 pub(crate) signature: Signature,
199 pub struct FundingSigned {
200 pub(crate) channel_id: [u8; 32],
201 pub(crate) signature: Signature,
204 pub struct FundingLocked {
205 pub(crate) channel_id: [u8; 32],
206 pub(crate) next_per_commitment_point: PublicKey,
209 pub struct Shutdown {
210 pub(crate) channel_id: [u8; 32],
211 pub(crate) scriptpubkey: Script,
214 pub struct ClosingSigned {
215 pub(crate) channel_id: [u8; 32],
216 pub(crate) fee_satoshis: u64,
217 pub(crate) signature: Signature,
221 pub struct UpdateAddHTLC {
222 pub(crate) channel_id: [u8; 32],
223 pub(crate) htlc_id: u64,
224 pub(crate) amount_msat: u64,
225 pub(crate) payment_hash: [u8; 32],
226 pub(crate) cltv_expiry: u32,
227 pub(crate) onion_routing_packet: OnionPacket,
231 pub struct UpdateFulfillHTLC {
232 pub(crate) channel_id: [u8; 32],
233 pub(crate) htlc_id: u64,
234 pub(crate) payment_preimage: [u8; 32],
238 pub struct UpdateFailHTLC {
239 pub(crate) channel_id: [u8; 32],
240 pub(crate) htlc_id: u64,
241 pub(crate) reason: OnionErrorPacket,
245 pub struct UpdateFailMalformedHTLC {
246 pub(crate) channel_id: [u8; 32],
247 pub(crate) htlc_id: u64,
248 pub(crate) sha256_of_onion: [u8; 32],
249 pub(crate) failure_code: u16,
253 pub struct CommitmentSigned {
254 pub(crate) channel_id: [u8; 32],
255 pub(crate) signature: Signature,
256 pub(crate) htlc_signatures: Vec<Signature>,
259 pub struct RevokeAndACK {
260 pub(crate) channel_id: [u8; 32],
261 pub(crate) per_commitment_secret: [u8; 32],
262 pub(crate) next_per_commitment_point: PublicKey,
265 pub struct UpdateFee {
266 pub(crate) channel_id: [u8; 32],
267 pub(crate) feerate_per_kw: u32,
270 pub(crate) struct DataLossProtect {
271 pub(crate) your_last_per_commitment_secret: [u8; 32],
272 pub(crate) my_current_per_commitment_point: PublicKey,
275 pub struct ChannelReestablish {
276 pub(crate) channel_id: [u8; 32],
277 pub(crate) next_local_commitment_number: u64,
278 pub(crate) next_remote_commitment_number: u64,
279 pub(crate) data_loss_protect: Option<DataLossProtect>,
283 pub struct AnnouncementSignatures {
284 pub(crate) channel_id: [u8; 32],
285 pub(crate) short_channel_id: u64,
286 pub(crate) node_signature: Signature,
287 pub(crate) bitcoin_signature: Signature,
291 pub enum NetAddress {
305 ed25519_pubkey: [u8; 32],
312 fn get_id(&self) -> u8 {
314 &NetAddress::IPv4 {..} => { 1 },
315 &NetAddress::IPv6 {..} => { 2 },
316 &NetAddress::OnionV2 {..} => { 3 },
317 &NetAddress::OnionV3 {..} => { 4 },
322 pub struct UnsignedNodeAnnouncement {
323 pub features: GlobalFeatures,
325 pub node_id: PublicKey,
328 /// List of addresses on which this node is reachable. Note that you may only have up to one
329 /// address of each type, if you have more, they may be silently discarded or we may panic!
330 pub(crate) addresses: Vec<NetAddress>,
331 pub(crate) excess_address_data: Vec<u8>,
332 pub(crate) excess_data: Vec<u8>,
334 pub struct NodeAnnouncement {
335 pub(crate) signature: Signature,
336 pub(crate) contents: UnsignedNodeAnnouncement,
339 #[derive(PartialEq, Clone)]
340 pub struct UnsignedChannelAnnouncement {
341 pub(crate) features: GlobalFeatures,
342 pub(crate) chain_hash: Sha256dHash,
343 pub(crate) short_channel_id: u64,
344 pub node_id_1: PublicKey,
345 pub node_id_2: PublicKey,
346 pub(crate) bitcoin_key_1: PublicKey,
347 pub(crate) bitcoin_key_2: PublicKey,
348 pub(crate) excess_data: Vec<u8>,
350 #[derive(PartialEq, Clone)]
351 pub struct ChannelAnnouncement {
352 pub(crate) node_signature_1: Signature,
353 pub(crate) node_signature_2: Signature,
354 pub(crate) bitcoin_signature_1: Signature,
355 pub(crate) bitcoin_signature_2: Signature,
356 pub(crate) contents: UnsignedChannelAnnouncement,
359 #[derive(PartialEq, Clone)]
360 pub(crate) struct UnsignedChannelUpdate {
361 pub(crate) chain_hash: Sha256dHash,
362 pub(crate) short_channel_id: u64,
363 pub(crate) timestamp: u32,
364 pub(crate) flags: u16,
365 pub(crate) cltv_expiry_delta: u16,
366 pub(crate) htlc_minimum_msat: u64,
367 pub(crate) fee_base_msat: u32,
368 pub(crate) fee_proportional_millionths: u32,
369 pub(crate) excess_data: Vec<u8>,
371 #[derive(PartialEq, Clone)]
372 pub struct ChannelUpdate {
373 pub(crate) signature: Signature,
374 pub(crate) contents: UnsignedChannelUpdate,
377 /// Used to put an error message in a HandleError
378 pub enum ErrorAction {
379 /// The peer took some action which made us think they were useless. Disconnect them.
381 msg: Option<ErrorMessage>
383 /// The peer did something harmless that we weren't able to process, just log and ignore
385 /// The peer did something incorrect. Tell them.
391 pub struct HandleError { //TODO: rename me
392 pub err: &'static str,
393 pub action: Option<ErrorAction>, //TODO: Make this required
396 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
397 /// transaction updates if they were pending.
398 pub struct CommitmentUpdate {
399 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
400 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
401 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
402 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
403 pub(crate) commitment_signed: CommitmentSigned,
406 pub enum HTLCFailChannelUpdate {
407 ChannelUpdateMessage {
411 short_channel_id: u64,
415 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
416 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
417 /// paralell when the two calls have the same their_node_id.
418 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
420 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
421 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
422 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
423 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
424 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
427 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
428 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
431 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
432 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
433 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
434 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
435 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
436 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
438 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
440 // Channel-to-announce:
441 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
443 // Connection loss/reestablish:
444 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
445 /// is believed to be possible in the future (eg they're sending us messages we don't
446 /// understand or indicate they require unknown feature bits), no_connection_possible is set
447 /// and any outstanding channels should be failed.
448 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
450 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
451 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
454 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
457 pub trait RoutingMessageHandler : Send + Sync {
458 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
459 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
460 /// or returning an Err otherwise.
461 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
462 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
463 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
466 pub(crate) struct OnionRealm0HopData {
467 pub(crate) short_channel_id: u64,
468 pub(crate) amt_to_forward: u64,
469 pub(crate) outgoing_cltv_value: u32,
470 // 12 bytes of 0-padding
473 mod fuzzy_internal_msgs {
474 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
475 // them from untrusted input):
477 use super::OnionRealm0HopData;
478 pub struct OnionHopData {
479 pub(crate) realm: u8,
480 pub(crate) data: OnionRealm0HopData,
481 pub(crate) hmac: [u8; 32],
483 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
485 pub struct DecodedOnionErrorPacket {
486 pub(crate) hmac: [u8; 32],
487 pub(crate) failuremsg: Vec<u8>,
488 pub(crate) pad: Vec<u8>,
491 #[cfg(feature = "fuzztarget")]
492 pub use self::fuzzy_internal_msgs::*;
493 #[cfg(not(feature = "fuzztarget"))]
494 pub(crate) use self::fuzzy_internal_msgs::*;
497 pub(crate) struct OnionPacket {
498 pub(crate) version: u8,
499 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
500 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
501 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
502 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
503 pub(crate) hop_data: [u8; 20*65],
504 pub(crate) hmac: [u8; 32],
508 pub(crate) struct OnionErrorPacket {
509 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
510 // (TODO) We limit it in decode to much lower...
511 pub(crate) data: Vec<u8>,
514 impl Error for DecodeError {
515 fn description(&self) -> &str {
517 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
518 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
519 DecodeError::BadPublicKey => "Invalid public key in packet",
520 DecodeError::BadSignature => "Invalid signature in packet",
521 DecodeError::BadText => "Invalid text in packet",
522 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
523 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
524 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
525 DecodeError::Io(ref e) => e.description(),
526 DecodeError::InvalidValue => "0 or 1 is not found for boolean",
530 impl fmt::Display for DecodeError {
531 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
532 f.write_str(self.description())
536 impl fmt::Debug for HandleError {
537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
538 f.write_str(self.err)
542 impl From<::std::io::Error> for DecodeError {
543 fn from(e: ::std::io::Error) -> Self {
544 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
545 DecodeError::ShortRead
552 impl_writeable_len_match!(AcceptChannel, {
553 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
556 temporary_channel_id,
558 max_htlc_value_in_flight_msat,
559 channel_reserve_satoshis,
565 revocation_basepoint,
567 delayed_payment_basepoint,
569 first_per_commitment_point,
570 shutdown_scriptpubkey
573 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
580 impl Writeable for ChannelReestablish {
581 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
582 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
583 self.channel_id.write(w)?;
584 self.next_local_commitment_number.write(w)?;
585 self.next_remote_commitment_number.write(w)?;
586 if let Some(ref data_loss_protect) = self.data_loss_protect {
587 data_loss_protect.your_last_per_commitment_secret.write(w)?;
588 data_loss_protect.my_current_per_commitment_point.write(w)?;
594 impl<R: Read> Readable<R> for ChannelReestablish{
595 fn read(r: &mut R) -> Result<Self, DecodeError> {
597 channel_id: Readable::read(r)?,
598 next_local_commitment_number: Readable::read(r)?,
599 next_remote_commitment_number: Readable::read(r)?,
601 match <[u8; 32] as Readable<R>>::read(r) {
602 Ok(your_last_per_commitment_secret) =>
603 Some(DataLossProtect {
604 your_last_per_commitment_secret,
605 my_current_per_commitment_point: Readable::read(r)?,
607 Err(DecodeError::ShortRead) => None,
608 Err(e) => return Err(e)
615 impl_writeable!(ClosingSigned, 32+8+64, {
621 impl_writeable_len_match!(CommitmentSigned, {
622 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
629 impl_writeable_len_match!(DecodedOnionErrorPacket, {
630 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
637 impl_writeable!(FundingCreated, 32+32+2+64, {
638 temporary_channel_id,
640 funding_output_index,
644 impl_writeable!(FundingSigned, 32+64, {
649 impl_writeable!(FundingLocked, 32+33, {
651 next_per_commitment_point
654 impl_writeable_len_match!(GlobalFeatures, {
655 { GlobalFeatures { ref flags }, flags.len() + 2 }
660 impl_writeable_len_match!(LocalFeatures, {
661 { LocalFeatures { ref flags }, flags.len() + 2 }
666 impl_writeable_len_match!(Init, {
667 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
673 impl_writeable_len_match!(OpenChannel, {
674 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
675 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
678 temporary_channel_id,
682 max_htlc_value_in_flight_msat,
683 channel_reserve_satoshis,
689 revocation_basepoint,
691 delayed_payment_basepoint,
693 first_per_commitment_point,
695 shutdown_scriptpubkey
698 impl_writeable!(RevokeAndACK, 32+32+33, {
700 per_commitment_secret,
701 next_per_commitment_point
704 impl_writeable_len_match!(Shutdown, {
705 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
711 impl_writeable_len_match!(UpdateFailHTLC, {
712 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
719 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
726 impl_writeable!(UpdateFee, 32+4, {
731 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
737 impl_writeable_len_match!(OnionErrorPacket, {
738 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
743 impl Writeable for OnionPacket {
744 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
745 w.size_hint(1 + 33 + 20*65 + 32);
746 self.version.write(w)?;
747 match self.public_key {
748 Ok(pubkey) => pubkey.write(w)?,
749 Err(_) => [0u8;33].write(w)?,
751 w.write_all(&self.hop_data)?;
757 impl<R: Read> Readable<R> for OnionPacket {
758 fn read(r: &mut R) -> Result<Self, DecodeError> {
760 version: Readable::read(r)?,
762 let mut buf = [0u8;33];
763 r.read_exact(&mut buf)?;
764 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
766 hop_data: Readable::read(r)?,
767 hmac: Readable::read(r)?,
772 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
781 impl Writeable for OnionRealm0HopData {
782 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
784 self.short_channel_id.write(w)?;
785 self.amt_to_forward.write(w)?;
786 self.outgoing_cltv_value.write(w)?;
787 w.write_all(&[0;12])?;
792 impl<R: Read> Readable<R> for OnionRealm0HopData {
793 fn read(r: &mut R) -> Result<Self, DecodeError> {
794 Ok(OnionRealm0HopData {
795 short_channel_id: Readable::read(r)?,
796 amt_to_forward: Readable::read(r)?,
797 outgoing_cltv_value: {
798 let v: u32 = Readable::read(r)?;
799 r.read_exact(&mut [0; 12])?;
806 impl Writeable for OnionHopData {
807 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
809 self.realm.write(w)?;
816 impl<R: Read> Readable<R> for OnionHopData {
817 fn read(r: &mut R) -> Result<Self, DecodeError> {
820 let r: u8 = Readable::read(r)?;
822 return Err(DecodeError::UnknownRealmByte);
826 data: Readable::read(r)?,
827 hmac: Readable::read(r)?,
832 impl Writeable for Ping {
833 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
834 w.size_hint(self.byteslen as usize + 4);
835 self.ponglen.write(w)?;
836 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
841 impl<R: Read> Readable<R> for Ping {
842 fn read(r: &mut R) -> Result<Self, DecodeError> {
844 ponglen: Readable::read(r)?,
846 let byteslen = Readable::read(r)?;
847 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
854 impl Writeable for Pong {
855 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
856 w.size_hint(self.byteslen as usize + 2);
857 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
862 impl<R: Read> Readable<R> for Pong {
863 fn read(r: &mut R) -> Result<Self, DecodeError> {
866 let byteslen = Readable::read(r)?;
867 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
874 impl Writeable for UnsignedChannelAnnouncement {
875 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
876 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
877 self.features.write(w)?;
878 self.chain_hash.write(w)?;
879 self.short_channel_id.write(w)?;
880 self.node_id_1.write(w)?;
881 self.node_id_2.write(w)?;
882 self.bitcoin_key_1.write(w)?;
883 self.bitcoin_key_2.write(w)?;
884 w.write_all(&self.excess_data[..])?;
889 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
890 fn read(r: &mut R) -> Result<Self, DecodeError> {
893 let f: GlobalFeatures = Readable::read(r)?;
894 if f.requires_unknown_bits() {
895 return Err(DecodeError::UnknownRequiredFeature);
899 chain_hash: Readable::read(r)?,
900 short_channel_id: Readable::read(r)?,
901 node_id_1: Readable::read(r)?,
902 node_id_2: Readable::read(r)?,
903 bitcoin_key_1: Readable::read(r)?,
904 bitcoin_key_2: Readable::read(r)?,
906 let mut excess_data = vec![];
907 r.read_to_end(&mut excess_data)?;
914 impl_writeable_len_match!(ChannelAnnouncement, {
915 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
916 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
925 impl Writeable for UnsignedChannelUpdate {
926 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
927 w.size_hint(64 + self.excess_data.len());
928 self.chain_hash.write(w)?;
929 self.short_channel_id.write(w)?;
930 self.timestamp.write(w)?;
931 self.flags.write(w)?;
932 self.cltv_expiry_delta.write(w)?;
933 self.htlc_minimum_msat.write(w)?;
934 self.fee_base_msat.write(w)?;
935 self.fee_proportional_millionths.write(w)?;
936 w.write_all(&self.excess_data[..])?;
941 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
942 fn read(r: &mut R) -> Result<Self, DecodeError> {
944 chain_hash: Readable::read(r)?,
945 short_channel_id: Readable::read(r)?,
946 timestamp: Readable::read(r)?,
947 flags: Readable::read(r)?,
948 cltv_expiry_delta: Readable::read(r)?,
949 htlc_minimum_msat: Readable::read(r)?,
950 fee_base_msat: Readable::read(r)?,
951 fee_proportional_millionths: Readable::read(r)?,
953 let mut excess_data = vec![];
954 r.read_to_end(&mut excess_data)?;
961 impl_writeable_len_match!(ChannelUpdate, {
962 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
963 64 + excess_data.len() + 64 }
969 impl Writeable for ErrorMessage {
970 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
971 w.size_hint(32 + 2 + self.data.len());
972 self.channel_id.write(w)?;
973 (self.data.len() as u16).write(w)?;
974 w.write_all(self.data.as_bytes())?;
979 impl<R: Read> Readable<R> for ErrorMessage {
980 fn read(r: &mut R) -> Result<Self, DecodeError> {
982 channel_id: Readable::read(r)?,
984 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
985 let mut data = vec![];
986 let data_len = r.read_to_end(&mut data)?;
987 sz = cmp::min(data_len, sz);
988 match String::from_utf8(data[..sz as usize].to_vec()) {
990 Err(_) => return Err(DecodeError::BadText),
997 impl Writeable for UnsignedNodeAnnouncement {
998 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
999 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1000 self.features.write(w)?;
1001 self.timestamp.write(w)?;
1002 self.node_id.write(w)?;
1003 w.write_all(&self.rgb)?;
1004 self.alias.write(w)?;
1006 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1007 let mut addrs_to_encode = self.addresses.clone();
1008 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1009 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1010 for addr in addrs_to_encode.iter() {
1012 &NetAddress::IPv4{addr, port} => {
1014 addr_slice.extend_from_slice(&addr);
1015 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1017 &NetAddress::IPv6{addr, port} => {
1019 addr_slice.extend_from_slice(&addr);
1020 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1022 &NetAddress::OnionV2{addr, port} => {
1024 addr_slice.extend_from_slice(&addr);
1025 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1027 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1029 addr_slice.extend_from_slice(&ed25519_pubkey);
1030 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1031 addr_slice.push(version);
1032 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1036 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1037 w.write_all(&addr_slice[..])?;
1038 w.write_all(&self.excess_address_data[..])?;
1039 w.write_all(&self.excess_data[..])?;
1044 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1045 fn read(r: &mut R) -> Result<Self, DecodeError> {
1046 let features: GlobalFeatures = Readable::read(r)?;
1047 if features.requires_unknown_bits() {
1048 return Err(DecodeError::UnknownRequiredFeature);
1050 let timestamp: u32 = Readable::read(r)?;
1051 let node_id: PublicKey = Readable::read(r)?;
1052 let mut rgb = [0; 3];
1053 r.read_exact(&mut rgb)?;
1054 let alias: [u8; 32] = Readable::read(r)?;
1056 let addrlen: u16 = Readable::read(r)?;
1057 let mut addr_readpos = 0;
1058 let mut addresses = Vec::with_capacity(4);
1062 if addrlen <= addr_readpos { break; }
1063 f = Readable::read(r)?;
1066 if addresses.len() > 0 {
1067 return Err(DecodeError::ExtraAddressesPerType);
1069 if addrlen < addr_readpos + 1 + 6 {
1070 return Err(DecodeError::BadLengthDescriptor);
1072 addresses.push(NetAddress::IPv4 {
1074 let mut addr = [0; 4];
1075 r.read_exact(&mut addr)?;
1078 port: Readable::read(r)?,
1080 addr_readpos += 1 + 6
1083 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1084 return Err(DecodeError::ExtraAddressesPerType);
1086 if addrlen < addr_readpos + 1 + 18 {
1087 return Err(DecodeError::BadLengthDescriptor);
1089 addresses.push(NetAddress::IPv6 {
1091 let mut addr = [0; 16];
1092 r.read_exact(&mut addr)?;
1095 port: Readable::read(r)?,
1097 addr_readpos += 1 + 18
1100 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1101 return Err(DecodeError::ExtraAddressesPerType);
1103 if addrlen < addr_readpos + 1 + 12 {
1104 return Err(DecodeError::BadLengthDescriptor);
1106 addresses.push(NetAddress::OnionV2 {
1108 let mut addr = [0; 10];
1109 r.read_exact(&mut addr)?;
1112 port: Readable::read(r)?,
1114 addr_readpos += 1 + 12
1117 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1118 return Err(DecodeError::ExtraAddressesPerType);
1120 if addrlen < addr_readpos + 1 + 37 {
1121 return Err(DecodeError::BadLengthDescriptor);
1123 addresses.push(NetAddress::OnionV3 {
1124 ed25519_pubkey: Readable::read(r)?,
1125 checksum: Readable::read(r)?,
1126 version: Readable::read(r)?,
1127 port: Readable::read(r)?,
1129 addr_readpos += 1 + 37
1131 _ => { excess = 1; break; }
1135 let mut excess_data = vec![];
1136 let excess_address_data = if addr_readpos < addrlen {
1137 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1138 r.read_exact(&mut excess_address_data[excess..])?;
1140 excess_address_data[0] = f;
1145 excess_data.push(f);
1150 Ok(UnsignedNodeAnnouncement {
1152 timestamp: timestamp,
1156 addresses: addresses,
1157 excess_address_data: excess_address_data,
1159 r.read_to_end(&mut excess_data)?;
1166 impl_writeable_len_match!(NodeAnnouncement, {
1167 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1168 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1178 use util::ser::Writeable;
1179 use secp256k1::key::{PublicKey,SecretKey};
1180 use secp256k1::Secp256k1;
1183 fn encoding_channel_reestablish_no_secret() {
1184 let cr = msgs::ChannelReestablish {
1185 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],
1186 next_local_commitment_number: 3,
1187 next_remote_commitment_number: 4,
1188 data_loss_protect: None,
1191 let encoded_value = cr.encode();
1194 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]
1199 fn encoding_channel_reestablish_with_secret() {
1201 let secp_ctx = Secp256k1::new();
1202 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1205 let cr = msgs::ChannelReestablish {
1206 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],
1207 next_local_commitment_number: 3,
1208 next_remote_commitment_number: 4,
1209 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1212 let encoded_value = cr.encode();
1215 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]