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, internal_traits, 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 fn new() -> LocalFeatures {
53 pub fn supports_data_loss_protect(&self) -> bool {
54 self.flags.len() > 0 && (self.flags[0] & 3) != 0
56 pub fn requires_data_loss_protect(&self) -> bool {
57 self.flags.len() > 0 && (self.flags[0] & 1) != 0
60 pub fn initial_routing_sync(&self) -> bool {
61 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
63 pub 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 fn supports_upfront_shutdown_script(&self) -> bool {
72 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
74 pub fn requires_upfront_shutdown_script(&self) -> bool {
75 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
78 pub 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 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 fn new() -> GlobalFeatures {
114 pub fn requires_unknown_bits(&self) -> bool {
115 for &byte in self.flags.iter() {
116 if (byte & 0x55) != 0 {
123 pub fn supports_unknown_bits(&self) -> bool {
124 for &byte in self.flags.iter() {
134 pub global_features: GlobalFeatures,
135 pub local_features: LocalFeatures,
138 pub struct ErrorMessage {
139 pub channel_id: [u8; 32],
152 pub struct OpenChannel {
153 pub chain_hash: Sha256dHash,
154 pub temporary_channel_id: [u8; 32],
155 pub funding_satoshis: u64,
157 pub dust_limit_satoshis: u64,
158 pub max_htlc_value_in_flight_msat: u64,
159 pub channel_reserve_satoshis: u64,
160 pub htlc_minimum_msat: u64,
161 pub feerate_per_kw: u32,
162 pub to_self_delay: u16,
163 pub max_accepted_htlcs: u16,
164 pub funding_pubkey: PublicKey,
165 pub revocation_basepoint: PublicKey,
166 pub payment_basepoint: PublicKey,
167 pub delayed_payment_basepoint: PublicKey,
168 pub htlc_basepoint: PublicKey,
169 pub first_per_commitment_point: PublicKey,
170 pub channel_flags: u8,
171 pub shutdown_scriptpubkey: Option<Script>,
174 pub struct AcceptChannel {
175 pub temporary_channel_id: [u8; 32],
176 pub dust_limit_satoshis: u64,
177 pub max_htlc_value_in_flight_msat: u64,
178 pub channel_reserve_satoshis: u64,
179 pub htlc_minimum_msat: u64,
180 pub minimum_depth: u32,
181 pub to_self_delay: u16,
182 pub max_accepted_htlcs: u16,
183 pub funding_pubkey: PublicKey,
184 pub revocation_basepoint: PublicKey,
185 pub payment_basepoint: PublicKey,
186 pub delayed_payment_basepoint: PublicKey,
187 pub htlc_basepoint: PublicKey,
188 pub first_per_commitment_point: PublicKey,
189 pub shutdown_scriptpubkey: Option<Script>,
192 pub struct FundingCreated {
193 pub temporary_channel_id: [u8; 32],
194 pub funding_txid: Sha256dHash,
195 pub funding_output_index: u16,
196 pub signature: Signature,
199 pub struct FundingSigned {
200 pub channel_id: [u8; 32],
201 pub signature: Signature,
204 pub struct FundingLocked {
205 pub channel_id: [u8; 32],
206 pub next_per_commitment_point: PublicKey,
209 pub struct Shutdown {
210 pub channel_id: [u8; 32],
211 pub scriptpubkey: Script,
214 pub struct ClosingSigned {
215 pub channel_id: [u8; 32],
216 pub fee_satoshis: u64,
217 pub signature: Signature,
221 pub struct UpdateAddHTLC {
222 pub channel_id: [u8; 32],
224 pub amount_msat: u64,
225 pub payment_hash: [u8; 32],
226 pub cltv_expiry: u32,
227 pub onion_routing_packet: OnionPacket,
231 pub struct UpdateFulfillHTLC {
232 pub channel_id: [u8; 32],
234 pub payment_preimage: [u8; 32],
238 pub struct UpdateFailHTLC {
239 pub channel_id: [u8; 32],
241 pub reason: OnionErrorPacket,
245 pub struct UpdateFailMalformedHTLC {
246 pub channel_id: [u8; 32],
248 pub sha256_of_onion: [u8; 32],
249 pub failure_code: u16,
253 pub struct CommitmentSigned {
254 pub channel_id: [u8; 32],
255 pub signature: Signature,
256 pub htlc_signatures: Vec<Signature>,
259 pub struct RevokeAndACK {
260 pub channel_id: [u8; 32],
261 pub per_commitment_secret: [u8; 32],
262 pub next_per_commitment_point: PublicKey,
265 pub struct UpdateFee {
266 pub channel_id: [u8; 32],
267 pub feerate_per_kw: u32,
270 pub struct DataLossProtect {
271 pub your_last_per_commitment_secret: [u8; 32],
272 pub my_current_per_commitment_point: PublicKey,
275 pub struct ChannelReestablish {
276 pub channel_id: [u8; 32],
277 pub next_local_commitment_number: u64,
278 pub next_remote_commitment_number: u64,
279 pub data_loss_protect: Option<DataLossProtect>,
283 pub struct AnnouncementSignatures {
284 pub channel_id: [u8; 32],
285 pub short_channel_id: u64,
286 pub node_signature: Signature,
287 pub 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 addresses: Vec<NetAddress>,
331 pub excess_address_data: Vec<u8>,
332 pub excess_data: Vec<u8>,
334 pub struct NodeAnnouncement {
335 pub signature: Signature,
336 pub contents: UnsignedNodeAnnouncement,
339 #[derive(PartialEq, Clone)]
340 pub struct UnsignedChannelAnnouncement {
341 pub features: GlobalFeatures,
342 pub chain_hash: Sha256dHash,
343 pub short_channel_id: u64,
344 pub node_id_1: PublicKey,
345 pub node_id_2: PublicKey,
346 pub bitcoin_key_1: PublicKey,
347 pub bitcoin_key_2: PublicKey,
348 pub excess_data: Vec<u8>,
350 #[derive(PartialEq, Clone)]
351 pub struct ChannelAnnouncement {
352 pub node_signature_1: Signature,
353 pub node_signature_2: Signature,
354 pub bitcoin_signature_1: Signature,
355 pub bitcoin_signature_2: Signature,
356 pub contents: UnsignedChannelAnnouncement,
359 #[derive(PartialEq, Clone)]
360 pub struct UnsignedChannelUpdate {
361 pub chain_hash: Sha256dHash,
362 pub short_channel_id: u64,
365 pub cltv_expiry_delta: u16,
366 pub htlc_minimum_msat: u64,
367 pub fee_base_msat: u32,
368 pub fee_proportional_millionths: u32,
369 pub excess_data: Vec<u8>,
371 #[derive(PartialEq, Clone)]
372 pub struct ChannelUpdate {
373 pub signature: Signature,
374 pub 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 update_add_htlcs: Vec<UpdateAddHTLC>,
400 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
401 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
402 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
403 pub 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 struct OnionRealm0HopData {
467 pub short_channel_id: u64,
468 pub amt_to_forward: u64,
469 pub outgoing_cltv_value: u32,
470 // 12 bytes of 0-padding
473 pub struct OnionHopData {
475 pub data: OnionRealm0HopData,
478 unsafe impl internal_traits::NoDealloc for OnionHopData{}
481 pub struct OnionPacket {
483 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
484 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
485 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
486 pub public_key: Result<PublicKey, secp256k1::Error>,
487 pub hop_data: [u8; 20*65],
491 pub struct DecodedOnionErrorPacket {
493 pub failuremsg: Vec<u8>,
498 pub struct OnionErrorPacket {
499 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
500 // (TODO) We limit it in decode to much lower...
504 impl Error for DecodeError {
505 fn description(&self) -> &str {
507 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
508 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
509 DecodeError::BadPublicKey => "Invalid public key in packet",
510 DecodeError::BadSignature => "Invalid signature in packet",
511 DecodeError::BadText => "Invalid text in packet",
512 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
513 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
514 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
515 DecodeError::Io(ref e) => e.description(),
516 DecodeError::InvalidValue => "0 or 1 is not found for boolean",
520 impl fmt::Display for DecodeError {
521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522 f.write_str(self.description())
526 impl fmt::Debug for HandleError {
527 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
528 f.write_str(self.err)
532 impl From<::std::io::Error> for DecodeError {
533 fn from(e: ::std::io::Error) -> Self {
534 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
535 DecodeError::ShortRead
542 impl_writeable_len_match!(AcceptChannel, {
543 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
546 temporary_channel_id,
548 max_htlc_value_in_flight_msat,
549 channel_reserve_satoshis,
555 revocation_basepoint,
557 delayed_payment_basepoint,
559 first_per_commitment_point,
560 shutdown_scriptpubkey
563 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
570 impl Writeable for ChannelReestablish {
571 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
572 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
573 self.channel_id.write(w)?;
574 self.next_local_commitment_number.write(w)?;
575 self.next_remote_commitment_number.write(w)?;
576 if let Some(ref data_loss_protect) = self.data_loss_protect {
577 data_loss_protect.your_last_per_commitment_secret.write(w)?;
578 data_loss_protect.my_current_per_commitment_point.write(w)?;
584 impl<R: Read> Readable<R> for ChannelReestablish{
585 fn read(r: &mut R) -> Result<Self, DecodeError> {
587 channel_id: Readable::read(r)?,
588 next_local_commitment_number: Readable::read(r)?,
589 next_remote_commitment_number: Readable::read(r)?,
591 match <[u8; 32] as Readable<R>>::read(r) {
592 Ok(your_last_per_commitment_secret) =>
593 Some(DataLossProtect {
594 your_last_per_commitment_secret,
595 my_current_per_commitment_point: Readable::read(r)?,
597 Err(DecodeError::ShortRead) => None,
598 Err(e) => return Err(e)
605 impl_writeable!(ClosingSigned, 32+8+64, {
611 impl_writeable_len_match!(CommitmentSigned, {
612 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
619 impl_writeable_len_match!(DecodedOnionErrorPacket, {
620 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
627 impl_writeable!(FundingCreated, 32+32+2+64, {
628 temporary_channel_id,
630 funding_output_index,
634 impl_writeable!(FundingSigned, 32+64, {
639 impl_writeable!(FundingLocked, 32+33, {
641 next_per_commitment_point
644 impl_writeable_len_match!(GlobalFeatures, {
645 { GlobalFeatures { ref flags }, flags.len() + 2 }
650 impl_writeable_len_match!(LocalFeatures, {
651 { LocalFeatures { ref flags }, flags.len() + 2 }
656 impl_writeable_len_match!(Init, {
657 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
663 impl_writeable_len_match!(OpenChannel, {
664 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
665 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
668 temporary_channel_id,
672 max_htlc_value_in_flight_msat,
673 channel_reserve_satoshis,
679 revocation_basepoint,
681 delayed_payment_basepoint,
683 first_per_commitment_point,
685 shutdown_scriptpubkey
688 impl_writeable!(RevokeAndACK, 32+32+33, {
690 per_commitment_secret,
691 next_per_commitment_point
694 impl_writeable_len_match!(Shutdown, {
695 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
701 impl_writeable_len_match!(UpdateFailHTLC, {
702 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
709 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
716 impl_writeable!(UpdateFee, 32+4, {
721 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
727 impl_writeable_len_match!(OnionErrorPacket, {
728 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
733 impl Writeable for OnionPacket {
734 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
735 w.size_hint(1 + 33 + 20*65 + 32);
736 self.version.write(w)?;
737 match self.public_key {
738 Ok(pubkey) => pubkey.write(w)?,
739 Err(_) => [0u8;33].write(w)?,
741 w.write_all(&self.hop_data)?;
747 impl<R: Read> Readable<R> for OnionPacket {
748 fn read(r: &mut R) -> Result<Self, DecodeError> {
750 version: Readable::read(r)?,
752 let mut buf = [0u8;33];
753 r.read_exact(&mut buf)?;
754 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
756 hop_data: Readable::read(r)?,
757 hmac: Readable::read(r)?,
762 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
771 impl Writeable for OnionRealm0HopData {
772 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
774 self.short_channel_id.write(w)?;
775 self.amt_to_forward.write(w)?;
776 self.outgoing_cltv_value.write(w)?;
777 w.write_all(&[0;12])?;
782 impl<R: Read> Readable<R> for OnionRealm0HopData {
783 fn read(r: &mut R) -> Result<Self, DecodeError> {
784 Ok(OnionRealm0HopData {
785 short_channel_id: Readable::read(r)?,
786 amt_to_forward: Readable::read(r)?,
787 outgoing_cltv_value: {
788 let v: u32 = Readable::read(r)?;
789 r.read_exact(&mut [0; 12])?;
796 impl Writeable for OnionHopData {
797 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
799 self.realm.write(w)?;
806 impl<R: Read> Readable<R> for OnionHopData {
807 fn read(r: &mut R) -> Result<Self, DecodeError> {
810 let r: u8 = Readable::read(r)?;
812 return Err(DecodeError::UnknownRealmByte);
816 data: Readable::read(r)?,
817 hmac: Readable::read(r)?,
822 impl Writeable for Ping {
823 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
824 w.size_hint(self.byteslen as usize + 4);
825 self.ponglen.write(w)?;
826 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
831 impl<R: Read> Readable<R> for Ping {
832 fn read(r: &mut R) -> Result<Self, DecodeError> {
834 ponglen: Readable::read(r)?,
836 let byteslen = Readable::read(r)?;
837 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
844 impl Writeable for Pong {
845 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
846 w.size_hint(self.byteslen as usize + 2);
847 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
852 impl<R: Read> Readable<R> for Pong {
853 fn read(r: &mut R) -> Result<Self, DecodeError> {
856 let byteslen = Readable::read(r)?;
857 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
864 impl Writeable for UnsignedChannelAnnouncement {
865 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
866 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
867 self.features.write(w)?;
868 self.chain_hash.write(w)?;
869 self.short_channel_id.write(w)?;
870 self.node_id_1.write(w)?;
871 self.node_id_2.write(w)?;
872 self.bitcoin_key_1.write(w)?;
873 self.bitcoin_key_2.write(w)?;
874 w.write_all(&self.excess_data[..])?;
879 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
880 fn read(r: &mut R) -> Result<Self, DecodeError> {
883 let f: GlobalFeatures = Readable::read(r)?;
884 if f.requires_unknown_bits() {
885 return Err(DecodeError::UnknownRequiredFeature);
889 chain_hash: Readable::read(r)?,
890 short_channel_id: Readable::read(r)?,
891 node_id_1: Readable::read(r)?,
892 node_id_2: Readable::read(r)?,
893 bitcoin_key_1: Readable::read(r)?,
894 bitcoin_key_2: Readable::read(r)?,
896 let mut excess_data = vec![];
897 r.read_to_end(&mut excess_data)?;
904 impl_writeable_len_match!(ChannelAnnouncement, {
905 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
906 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
915 impl Writeable for UnsignedChannelUpdate {
916 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
917 w.size_hint(64 + self.excess_data.len());
918 self.chain_hash.write(w)?;
919 self.short_channel_id.write(w)?;
920 self.timestamp.write(w)?;
921 self.flags.write(w)?;
922 self.cltv_expiry_delta.write(w)?;
923 self.htlc_minimum_msat.write(w)?;
924 self.fee_base_msat.write(w)?;
925 self.fee_proportional_millionths.write(w)?;
926 w.write_all(&self.excess_data[..])?;
931 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
932 fn read(r: &mut R) -> Result<Self, DecodeError> {
934 chain_hash: Readable::read(r)?,
935 short_channel_id: Readable::read(r)?,
936 timestamp: Readable::read(r)?,
937 flags: Readable::read(r)?,
938 cltv_expiry_delta: Readable::read(r)?,
939 htlc_minimum_msat: Readable::read(r)?,
940 fee_base_msat: Readable::read(r)?,
941 fee_proportional_millionths: Readable::read(r)?,
943 let mut excess_data = vec![];
944 r.read_to_end(&mut excess_data)?;
951 impl_writeable_len_match!(ChannelUpdate, {
952 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
953 64 + excess_data.len() + 64 }
959 impl Writeable for ErrorMessage {
960 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
961 w.size_hint(32 + 2 + self.data.len());
962 self.channel_id.write(w)?;
963 (self.data.len() as u16).write(w)?;
964 w.write_all(self.data.as_bytes())?;
969 impl<R: Read> Readable<R> for ErrorMessage {
970 fn read(r: &mut R) -> Result<Self, DecodeError> {
972 channel_id: Readable::read(r)?,
974 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
975 let mut data = vec![];
976 let data_len = r.read_to_end(&mut data)?;
977 sz = cmp::min(data_len, sz);
978 match String::from_utf8(data[..sz as usize].to_vec()) {
980 Err(_) => return Err(DecodeError::BadText),
987 impl Writeable for UnsignedNodeAnnouncement {
988 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
989 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
990 self.features.write(w)?;
991 self.timestamp.write(w)?;
992 self.node_id.write(w)?;
993 w.write_all(&self.rgb)?;
994 self.alias.write(w)?;
996 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
997 let mut addrs_to_encode = self.addresses.clone();
998 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
999 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1000 for addr in addrs_to_encode.iter() {
1002 &NetAddress::IPv4{addr, port} => {
1004 addr_slice.extend_from_slice(&addr);
1005 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1007 &NetAddress::IPv6{addr, port} => {
1009 addr_slice.extend_from_slice(&addr);
1010 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1012 &NetAddress::OnionV2{addr, port} => {
1014 addr_slice.extend_from_slice(&addr);
1015 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1017 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1019 addr_slice.extend_from_slice(&ed25519_pubkey);
1020 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1021 addr_slice.push(version);
1022 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1026 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1027 w.write_all(&addr_slice[..])?;
1028 w.write_all(&self.excess_address_data[..])?;
1029 w.write_all(&self.excess_data[..])?;
1034 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1035 fn read(r: &mut R) -> Result<Self, DecodeError> {
1036 let features: GlobalFeatures = Readable::read(r)?;
1037 if features.requires_unknown_bits() {
1038 return Err(DecodeError::UnknownRequiredFeature);
1040 let timestamp: u32 = Readable::read(r)?;
1041 let node_id: PublicKey = Readable::read(r)?;
1042 let mut rgb = [0; 3];
1043 r.read_exact(&mut rgb)?;
1044 let alias: [u8; 32] = Readable::read(r)?;
1046 let addrlen: u16 = Readable::read(r)?;
1047 let mut addr_readpos = 0;
1048 let mut addresses = Vec::with_capacity(4);
1052 if addrlen <= addr_readpos { break; }
1053 f = Readable::read(r)?;
1056 if addresses.len() > 0 {
1057 return Err(DecodeError::ExtraAddressesPerType);
1059 if addrlen < addr_readpos + 1 + 6 {
1060 return Err(DecodeError::BadLengthDescriptor);
1062 addresses.push(NetAddress::IPv4 {
1064 let mut addr = [0; 4];
1065 r.read_exact(&mut addr)?;
1068 port: Readable::read(r)?,
1070 addr_readpos += 1 + 6
1073 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1074 return Err(DecodeError::ExtraAddressesPerType);
1076 if addrlen < addr_readpos + 1 + 18 {
1077 return Err(DecodeError::BadLengthDescriptor);
1079 addresses.push(NetAddress::IPv6 {
1081 let mut addr = [0; 16];
1082 r.read_exact(&mut addr)?;
1085 port: Readable::read(r)?,
1087 addr_readpos += 1 + 18
1090 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1091 return Err(DecodeError::ExtraAddressesPerType);
1093 if addrlen < addr_readpos + 1 + 12 {
1094 return Err(DecodeError::BadLengthDescriptor);
1096 addresses.push(NetAddress::OnionV2 {
1098 let mut addr = [0; 10];
1099 r.read_exact(&mut addr)?;
1102 port: Readable::read(r)?,
1104 addr_readpos += 1 + 12
1107 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1108 return Err(DecodeError::ExtraAddressesPerType);
1110 if addrlen < addr_readpos + 1 + 37 {
1111 return Err(DecodeError::BadLengthDescriptor);
1113 addresses.push(NetAddress::OnionV3 {
1114 ed25519_pubkey: Readable::read(r)?,
1115 checksum: Readable::read(r)?,
1116 version: Readable::read(r)?,
1117 port: Readable::read(r)?,
1119 addr_readpos += 1 + 37
1121 _ => { excess = 1; break; }
1125 let mut excess_data = vec![];
1126 let excess_address_data = if addr_readpos < addrlen {
1127 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1128 r.read_exact(&mut excess_address_data[excess..])?;
1130 excess_address_data[0] = f;
1135 excess_data.push(f);
1140 Ok(UnsignedNodeAnnouncement {
1142 timestamp: timestamp,
1146 addresses: addresses,
1147 excess_address_data: excess_address_data,
1149 r.read_to_end(&mut excess_data)?;
1156 impl_writeable_len_match!(NodeAnnouncement, {
1157 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1158 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1168 use util::ser::Writeable;
1169 use secp256k1::key::{PublicKey,SecretKey};
1170 use secp256k1::Secp256k1;
1173 fn encoding_channel_reestablish_no_secret() {
1174 let cr = msgs::ChannelReestablish {
1175 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],
1176 next_local_commitment_number: 3,
1177 next_remote_commitment_number: 4,
1178 data_loss_protect: None,
1181 let encoded_value = cr.encode();
1184 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]
1189 fn encoding_channel_reestablish_with_secret() {
1191 let secp_ctx = Secp256k1::new();
1192 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1195 let cr = msgs::ChannelReestablish {
1196 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],
1197 next_local_commitment_number: 3,
1198 next_remote_commitment_number: 4,
1199 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1202 let encoded_value = cr.encode();
1205 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]