c43a5dc9c4d4ff5c0b379d6cdc94f31c904bdc12
[rust-lightning] / msgs.rs
1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use secp256k1;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::blockdata::script::Script;
6
7 use std::error::Error;
8 use std::{cmp, fmt};
9 use std::io::Read;
10 use std::result::Result;
11
12 use util::{byte_utils, events};
13 use util::ser::{Readable, Writeable, Writer};
14
15 #[derive(Debug)]
16 pub enum DecodeError {
17         /// Unknown realm byte in an OnionHopData packet
18         UnknownRealmByte,
19         /// Unknown feature mandating we fail to parse message
20         UnknownRequiredFeature,
21         /// Failed to decode a public key (ie it's invalid)
22         BadPublicKey,
23         /// Failed to decode a signature (ie it's invalid)
24         BadSignature,
25         /// Value expected to be text wasn't decodable as text
26         BadText,
27         /// Buffer too short
28         ShortRead,
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)
33         BadLengthDescriptor,
34         /// Error from std::io
35         Io(::std::io::Error),
36         /// 1 or 0 is not found for boolean value
37         InvalidValue,
38 }
39
40 /// Tracks localfeatures which are only in init messages
41 #[derive(Clone, PartialEq)]
42 pub struct LocalFeatures {
43         flags: Vec<u8>,
44 }
45
46 impl LocalFeatures {
47         pub(crate) fn new() -> LocalFeatures {
48                 LocalFeatures {
49                         flags: Vec::new(),
50                 }
51         }
52
53         pub(crate) fn supports_data_loss_protect(&self) -> bool {
54                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
55         }
56         pub(crate) fn requires_data_loss_protect(&self) -> bool {
57                 self.flags.len() > 0 && (self.flags[0] & 1) != 0
58         }
59
60         pub(crate) fn initial_routing_sync(&self) -> bool {
61                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
62         }
63         pub(crate) fn set_initial_routing_sync(&mut self) {
64                 if self.flags.len() == 0 {
65                         self.flags.resize(1, 1 << 3);
66                 } else {
67                         self.flags[0] |= 1 << 3;
68                 }
69         }
70
71         pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
72                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
73         }
74         pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
75                 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
76         }
77
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 {
81                                 return true;
82                         } else if idx == 0 && (byte & 0x14) != 0 {
83                                 return true;
84                         }
85                 }
86                 return false;
87         }
88
89         pub(crate) fn supports_unknown_bits(&self) -> bool {
90                 for (idx, &byte) in self.flags.iter().enumerate() {
91                         if idx != 0 && byte != 0 {
92                                 return true;
93                         } else if idx == 0 && (byte & 0xc4) != 0 {
94                                 return true;
95                         }
96                 }
97                 return false;
98         }
99 }
100
101 /// Tracks globalfeatures which are in init messages and routing announcements
102 #[derive(Clone, PartialEq)]
103 pub struct GlobalFeatures {
104         flags: Vec<u8>,
105 }
106
107 impl GlobalFeatures {
108         pub(crate) fn new() -> GlobalFeatures {
109                 GlobalFeatures {
110                         flags: Vec::new(),
111                 }
112         }
113
114         pub(crate) fn requires_unknown_bits(&self) -> bool {
115                 for &byte in self.flags.iter() {
116                         if (byte & 0x55) != 0 {
117                                 return true;
118                         }
119                 }
120                 return false;
121         }
122
123         pub(crate) fn supports_unknown_bits(&self) -> bool {
124                 for &byte in self.flags.iter() {
125                         if byte != 0 {
126                                 return true;
127                         }
128                 }
129                 return false;
130         }
131 }
132
133 pub struct Init {
134         pub(crate) global_features: GlobalFeatures,
135         pub(crate) local_features: LocalFeatures,
136 }
137
138 pub struct ErrorMessage {
139         pub(crate) channel_id: [u8; 32],
140         pub(crate) data: String,
141 }
142
143 pub struct Ping {
144         pub(crate) ponglen: u16,
145         pub(crate) byteslen: u16,
146 }
147
148 pub struct Pong {
149         pub(crate) byteslen: u16,
150 }
151
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>,
172 }
173
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>,
190 }
191
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,
197 }
198
199 pub struct FundingSigned {
200         pub(crate) channel_id: [u8; 32],
201         pub(crate) signature: Signature,
202 }
203
204 pub struct FundingLocked {
205         pub(crate) channel_id: [u8; 32],
206         pub(crate) next_per_commitment_point: PublicKey,
207 }
208
209 pub struct Shutdown {
210         pub(crate) channel_id: [u8; 32],
211         pub(crate) scriptpubkey: Script,
212 }
213
214 pub struct ClosingSigned {
215         pub(crate) channel_id: [u8; 32],
216         pub(crate) fee_satoshis: u64,
217         pub(crate) signature: Signature,
218 }
219
220 #[derive(Clone)]
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,
228 }
229
230 #[derive(Clone)]
231 pub struct UpdateFulfillHTLC {
232         pub(crate) channel_id: [u8; 32],
233         pub(crate) htlc_id: u64,
234         pub(crate) payment_preimage: [u8; 32],
235 }
236
237 #[derive(Clone)]
238 pub struct UpdateFailHTLC {
239         pub(crate) channel_id: [u8; 32],
240         pub(crate) htlc_id: u64,
241         pub(crate) reason: OnionErrorPacket,
242 }
243
244 #[derive(Clone)]
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,
250 }
251
252 #[derive(Clone)]
253 pub struct CommitmentSigned {
254         pub(crate) channel_id: [u8; 32],
255         pub(crate) signature: Signature,
256         pub(crate) htlc_signatures: Vec<Signature>,
257 }
258
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,
263 }
264
265 pub struct UpdateFee {
266         pub(crate) channel_id: [u8; 32],
267         pub(crate) feerate_per_kw: u32,
268 }
269
270 pub(crate) struct DataLossProtect {
271         pub(crate) your_last_per_commitment_secret: [u8; 32],
272         pub(crate) my_current_per_commitment_point: PublicKey,
273 }
274
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>,
280 }
281
282 #[derive(Clone)]
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,
288 }
289
290 #[derive(Clone)]
291 pub enum NetAddress {
292         IPv4 {
293                 addr: [u8; 4],
294                 port: u16,
295         },
296         IPv6 {
297                 addr: [u8; 16],
298                 port: u16,
299         },
300         OnionV2 {
301                 addr: [u8; 10],
302                 port: u16,
303         },
304         OnionV3 {
305                 ed25519_pubkey: [u8; 32],
306                 checksum: u16,
307                 version: u8,
308                 port: u16,
309         },
310 }
311 impl NetAddress {
312         fn get_id(&self) -> u8 {
313                 match self {
314                         &NetAddress::IPv4 {..} => { 1 },
315                         &NetAddress::IPv6 {..} => { 2 },
316                         &NetAddress::OnionV2 {..} => { 3 },
317                         &NetAddress::OnionV3 {..} => { 4 },
318                 }
319         }
320 }
321
322 pub struct UnsignedNodeAnnouncement {
323         pub features: GlobalFeatures,
324         pub timestamp: u32,
325         pub node_id: PublicKey,
326         pub rgb: [u8; 3],
327         pub alias: [u8; 32],
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>,
333 }
334 pub struct NodeAnnouncement {
335         pub(crate) signature: Signature,
336         pub(crate) contents: UnsignedNodeAnnouncement,
337 }
338
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>,
349 }
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,
357 }
358
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>,
370 }
371 #[derive(PartialEq, Clone)]
372 pub struct ChannelUpdate {
373         pub(crate) signature: Signature,
374         pub(crate) contents: UnsignedChannelUpdate,
375 }
376
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.
380         DisconnectPeer {
381                 msg: Option<ErrorMessage>
382         },
383         /// The peer did something harmless that we weren't able to process, just log and ignore
384         IgnoreError,
385         /// The peer did something incorrect. Tell them.
386         SendErrorMessage {
387                 msg: ErrorMessage
388         },
389 }
390
391 pub struct HandleError { //TODO: rename me
392         pub err: &'static str,
393         pub action: Option<ErrorAction>, //TODO: Make this required
394 }
395
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,
404 }
405
406 pub enum HTLCFailChannelUpdate {
407         ChannelUpdateMessage {
408                 msg: ChannelUpdate,
409         },
410         ChannelClosed {
411                 short_channel_id: u64,
412         },
413 }
414
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 {
419         //Channel init:
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>;
425
426         // Channl close:
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>;
429
430         // HTLC handling:
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>;
437
438         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
439
440         // Channel-to-announce:
441         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
442
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);
449
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>;
452
453         // Error:
454         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
455 }
456
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);
464 }
465
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
471 }
472
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):
476
477         use super::OnionRealm0HopData;
478         pub struct OnionHopData {
479                 pub(crate) realm: u8,
480                 pub(crate) data: OnionRealm0HopData,
481                 pub(crate) hmac: [u8; 32],
482         }
483         unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
484
485         pub struct DecodedOnionErrorPacket {
486                 pub(crate) hmac: [u8; 32],
487                 pub(crate) failuremsg: Vec<u8>,
488                 pub(crate) pad: Vec<u8>,
489         }
490 }
491 #[cfg(feature = "fuzztarget")]
492 pub use self::fuzzy_internal_msgs::*;
493 #[cfg(not(feature = "fuzztarget"))]
494 pub(crate) use self::fuzzy_internal_msgs::*;
495
496 #[derive(Clone)]
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],
505 }
506
507 #[derive(Clone)]
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>,
512 }
513
514 impl Error for DecodeError {
515         fn description(&self) -> &str {
516                 match *self {
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",
527                 }
528         }
529 }
530 impl fmt::Display for DecodeError {
531         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
532                 f.write_str(self.description())
533         }
534 }
535
536 impl fmt::Debug for HandleError {
537         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
538                 f.write_str(self.err)
539         }
540 }
541
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
546                 } else {
547                         DecodeError::Io(e)
548                 }
549         }
550 }
551
552 impl_writeable_len_match!(AcceptChannel, {
553                 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
554                 {_, 270}
555         }, {
556         temporary_channel_id,
557         dust_limit_satoshis,
558         max_htlc_value_in_flight_msat,
559         channel_reserve_satoshis,
560         htlc_minimum_msat,
561         minimum_depth,
562         to_self_delay,
563         max_accepted_htlcs,
564         funding_pubkey,
565         revocation_basepoint,
566         payment_basepoint,
567         delayed_payment_basepoint,
568         htlc_basepoint,
569         first_per_commitment_point,
570         shutdown_scriptpubkey
571 });
572
573 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
574         channel_id,
575         short_channel_id,
576         node_signature,
577         bitcoin_signature
578 });
579
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)?;
589                 }
590                 Ok(())
591         }
592 }
593
594 impl<R: Read> Readable<R> for ChannelReestablish{
595         fn read(r: &mut R) -> Result<Self, DecodeError> {
596                 Ok(Self {
597                         channel_id: Readable::read(r)?,
598                         next_local_commitment_number: Readable::read(r)?,
599                         next_remote_commitment_number: Readable::read(r)?,
600                         data_loss_protect: {
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)?,
606                                                 }),
607                                         Err(DecodeError::ShortRead) => None,
608                                         Err(e) => return Err(e)
609                                 }
610                         }
611                 })
612         }
613 }
614
615 impl_writeable!(ClosingSigned, 32+8+64, {
616         channel_id,
617         fee_satoshis,
618         signature
619 });
620
621 impl_writeable_len_match!(CommitmentSigned, {
622                 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
623         }, {
624         channel_id,
625         signature,
626         htlc_signatures
627 });
628
629 impl_writeable_len_match!(DecodedOnionErrorPacket, {
630                 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
631         }, {
632         hmac,
633         failuremsg,
634         pad
635 });
636
637 impl_writeable!(FundingCreated, 32+32+2+64, {
638         temporary_channel_id,
639         funding_txid,
640         funding_output_index,
641         signature
642 });
643
644 impl_writeable!(FundingSigned, 32+64, {
645         channel_id,
646         signature
647 });
648
649 impl_writeable!(FundingLocked, 32+33, {
650         channel_id,
651         next_per_commitment_point
652 });
653
654 impl_writeable_len_match!(GlobalFeatures, {
655                 { GlobalFeatures { ref flags }, flags.len() + 2 }
656         }, {
657         flags
658 });
659
660 impl_writeable_len_match!(LocalFeatures, {
661                 { LocalFeatures { ref flags }, flags.len() + 2 }
662         }, {
663         flags
664 });
665
666 impl_writeable_len_match!(Init, {
667                 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
668         }, {
669         global_features,
670         local_features
671 });
672
673 impl_writeable_len_match!(OpenChannel, {
674                 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
675                 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
676         }, {
677         chain_hash,
678         temporary_channel_id,
679         funding_satoshis,
680         push_msat,
681         dust_limit_satoshis,
682         max_htlc_value_in_flight_msat,
683         channel_reserve_satoshis,
684         htlc_minimum_msat,
685         feerate_per_kw,
686         to_self_delay,
687         max_accepted_htlcs,
688         funding_pubkey,
689         revocation_basepoint,
690         payment_basepoint,
691         delayed_payment_basepoint,
692         htlc_basepoint,
693         first_per_commitment_point,
694         channel_flags,
695         shutdown_scriptpubkey
696 });
697
698 impl_writeable!(RevokeAndACK, 32+32+33, {
699         channel_id,
700         per_commitment_secret,
701         next_per_commitment_point
702 });
703
704 impl_writeable_len_match!(Shutdown, {
705                 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
706         }, {
707         channel_id,
708         scriptpubkey
709 });
710
711 impl_writeable_len_match!(UpdateFailHTLC, {
712                 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
713         }, {
714         channel_id,
715         htlc_id,
716         reason
717 });
718
719 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
720         channel_id,
721         htlc_id,
722         sha256_of_onion,
723         failure_code
724 });
725
726 impl_writeable!(UpdateFee, 32+4, {
727         channel_id,
728         feerate_per_kw
729 });
730
731 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
732         channel_id,
733         htlc_id,
734         payment_preimage
735 });
736
737 impl_writeable_len_match!(OnionErrorPacket, {
738                 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
739         }, {
740         data
741 });
742
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)?,
750                 }
751                 w.write_all(&self.hop_data)?;
752                 self.hmac.write(w)?;
753                 Ok(())
754         }
755 }
756
757 impl<R: Read> Readable<R> for OnionPacket {
758         fn read(r: &mut R) -> Result<Self, DecodeError> {
759                 Ok(OnionPacket {
760                         version: Readable::read(r)?,
761                         public_key: {
762                                 let mut buf = [0u8;33];
763                                 r.read_exact(&mut buf)?;
764                                 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
765                         },
766                         hop_data: Readable::read(r)?,
767                         hmac: Readable::read(r)?,
768                 })
769         }
770 }
771
772 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
773         channel_id,
774         htlc_id,
775         amount_msat,
776         payment_hash,
777         cltv_expiry,
778         onion_routing_packet
779 });
780
781 impl Writeable for OnionRealm0HopData {
782         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
783                 w.size_hint(32);
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])?;
788                 Ok(())
789         }
790 }
791
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])?;
800                                 v
801                         }
802                 })
803         }
804 }
805
806 impl Writeable for OnionHopData {
807         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
808                 w.size_hint(65);
809                 self.realm.write(w)?;
810                 self.data.write(w)?;
811                 self.hmac.write(w)?;
812                 Ok(())
813         }
814 }
815
816 impl<R: Read> Readable<R> for OnionHopData {
817         fn read(r: &mut R) -> Result<Self, DecodeError> {
818                 Ok(OnionHopData {
819                         realm: {
820                                 let r: u8 = Readable::read(r)?;
821                                 if r != 0 {
822                                         return Err(DecodeError::UnknownRealmByte);
823                                 }
824                                 r
825                         },
826                         data: Readable::read(r)?,
827                         hmac: Readable::read(r)?,
828                 })
829         }
830 }
831
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
837                 Ok(())
838         }
839 }
840
841 impl<R: Read> Readable<R> for Ping {
842         fn read(r: &mut R) -> Result<Self, DecodeError> {
843                 Ok(Ping {
844                         ponglen: Readable::read(r)?,
845                         byteslen: {
846                                 let byteslen = Readable::read(r)?;
847                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
848                                 byteslen
849                         }
850                 })
851         }
852 }
853
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
858                 Ok(())
859         }
860 }
861
862 impl<R: Read> Readable<R> for Pong {
863         fn read(r: &mut R) -> Result<Self, DecodeError> {
864                 Ok(Pong {
865                         byteslen: {
866                                 let byteslen = Readable::read(r)?;
867                                 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
868                                 byteslen
869                         }
870                 })
871         }
872 }
873
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[..])?;
885                 Ok(())
886         }
887 }
888
889 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
890         fn read(r: &mut R) -> Result<Self, DecodeError> {
891                 Ok(Self {
892                         features: {
893                                 let f: GlobalFeatures = Readable::read(r)?;
894                                 if f.requires_unknown_bits() {
895                                         return Err(DecodeError::UnknownRequiredFeature);
896                                 }
897                                 f
898                         },
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)?,
905                         excess_data: {
906                                 let mut excess_data = vec![];
907                                 r.read_to_end(&mut excess_data)?;
908                                 excess_data
909                         },
910                 })
911         }
912 }
913
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 }
917         }, {
918         node_signature_1,
919         node_signature_2,
920         bitcoin_signature_1,
921         bitcoin_signature_2,
922         contents
923 });
924
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[..])?;
937                 Ok(())
938         }
939 }
940
941 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
942         fn read(r: &mut R) -> Result<Self, DecodeError> {
943                 Ok(Self {
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)?,
952                         excess_data: {
953                                 let mut excess_data = vec![];
954                                 r.read_to_end(&mut excess_data)?;
955                                 excess_data
956                         },
957                 })
958         }
959 }
960
961 impl_writeable_len_match!(ChannelUpdate, {
962                 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
963                         64 + excess_data.len() + 64 }
964         }, {
965         signature,
966         contents
967 });
968
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())?;
975                 Ok(())
976         }
977 }
978
979 impl<R: Read> Readable<R> for ErrorMessage {
980         fn read(r: &mut R) -> Result<Self, DecodeError> {
981                 Ok(Self {
982                         channel_id: Readable::read(r)?,
983                         data: {
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()) {
989                                         Ok(s) => s,
990                                         Err(_) => return Err(DecodeError::BadText),
991                                 }
992                         }
993                 })
994         }
995 }
996
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)?;
1005
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() {
1011                         match addr {
1012                                 &NetAddress::IPv4{addr, port} => {
1013                                         addr_slice.push(1);
1014                                         addr_slice.extend_from_slice(&addr);
1015                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1016                                 },
1017                                 &NetAddress::IPv6{addr, port} => {
1018                                         addr_slice.push(2);
1019                                         addr_slice.extend_from_slice(&addr);
1020                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1021                                 },
1022                                 &NetAddress::OnionV2{addr, port} => {
1023                                         addr_slice.push(3);
1024                                         addr_slice.extend_from_slice(&addr);
1025                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1026                                 },
1027                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1028                                         addr_slice.push(4);
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));
1033                                 },
1034                         }
1035                 }
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[..])?;
1040                 Ok(())
1041         }
1042 }
1043
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);
1049                 }
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)?;
1055
1056                 let addrlen: u16 = Readable::read(r)?;
1057                 let mut addr_readpos = 0;
1058                 let mut addresses = Vec::with_capacity(4);
1059                 let mut f: u8 = 0;
1060                 let mut excess = 0;
1061                 loop {
1062                         if addrlen <= addr_readpos { break; }
1063                         f = Readable::read(r)?;
1064                         match f {
1065                                 1 => {
1066                                         if addresses.len() > 0 {
1067                                                 return Err(DecodeError::ExtraAddressesPerType);
1068                                         }
1069                                         if addrlen < addr_readpos + 1 + 6 {
1070                                                 return Err(DecodeError::BadLengthDescriptor);
1071                                         }
1072                                         addresses.push(NetAddress::IPv4 {
1073                                                 addr: {
1074                                                         let mut addr = [0; 4];
1075                                                         r.read_exact(&mut addr)?;
1076                                                         addr
1077                                                 },
1078                                                 port: Readable::read(r)?,
1079                                         });
1080                                         addr_readpos += 1 + 6
1081                                 },
1082                                 2 => {
1083                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1084                                                 return Err(DecodeError::ExtraAddressesPerType);
1085                                         }
1086                                         if addrlen < addr_readpos + 1 + 18 {
1087                                                 return Err(DecodeError::BadLengthDescriptor);
1088                                         }
1089                                         addresses.push(NetAddress::IPv6 {
1090                                                 addr: {
1091                                                         let mut addr = [0; 16];
1092                                                         r.read_exact(&mut addr)?;
1093                                                         addr
1094                                                 },
1095                                                 port: Readable::read(r)?,
1096                                         });
1097                                         addr_readpos += 1 + 18
1098                                 },
1099                                 3 => {
1100                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1101                                                 return Err(DecodeError::ExtraAddressesPerType);
1102                                         }
1103                                         if addrlen < addr_readpos + 1 + 12 {
1104                                                 return Err(DecodeError::BadLengthDescriptor);
1105                                         }
1106                                         addresses.push(NetAddress::OnionV2 {
1107                                                 addr: {
1108                                                         let mut addr = [0; 10];
1109                                                         r.read_exact(&mut addr)?;
1110                                                         addr
1111                                                 },
1112                                                 port: Readable::read(r)?,
1113                                         });
1114                                         addr_readpos += 1 + 12
1115                                 },
1116                                 4 => {
1117                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1118                                                 return Err(DecodeError::ExtraAddressesPerType);
1119                                         }
1120                                         if addrlen < addr_readpos + 1 + 37 {
1121                                                 return Err(DecodeError::BadLengthDescriptor);
1122                                         }
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)?,
1128                                         });
1129                                         addr_readpos += 1 + 37
1130                                 },
1131                                 _ => { excess = 1; break; }
1132                         }
1133                 }
1134
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..])?;
1139                         if excess == 1 {
1140                                 excess_address_data[0] = f;
1141                         }
1142                         excess_address_data
1143                 } else {
1144                         if excess == 1 {
1145                                 excess_data.push(f);
1146                         }
1147                         Vec::new()
1148                 };
1149
1150                 Ok(UnsignedNodeAnnouncement {
1151                         features: features,
1152                         timestamp: timestamp,
1153                         node_id: node_id,
1154                         rgb: rgb,
1155                         alias: alias,
1156                         addresses: addresses,
1157                         excess_address_data: excess_address_data,
1158                         excess_data: {
1159                                 r.read_to_end(&mut excess_data)?;
1160                                 excess_data
1161                         },
1162                 })
1163         }
1164 }
1165
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() }
1169         }, {
1170         signature,
1171         contents
1172 });
1173
1174 #[cfg(test)]
1175 mod tests {
1176         use hex;
1177         use ln::msgs;
1178         use util::ser::Writeable;
1179         use secp256k1::key::{PublicKey,SecretKey};
1180         use secp256k1::Secp256k1;
1181
1182         #[test]
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,
1189                 };
1190
1191                 let encoded_value = cr.encode();
1192                 assert_eq!(
1193                         encoded_value,
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]
1195                 );
1196         }
1197
1198         #[test]
1199         fn encoding_channel_reestablish_with_secret() {
1200                 let public_key = {
1201                         let secp_ctx = Secp256k1::new();
1202                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1203                 };
1204
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}),
1210                 };
1211
1212                 let encoded_value = cr.encode();
1213                 assert_eq!(
1214                         encoded_value,
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]
1216                 );
1217         }
1218 }