Skip to content

Commit bab89ae

Browse files
authored
Merge pull request #12 from TheBlueMatt/2018-03-fixes
Few random fixes
2 parents ad9dda2 + deb23a9 commit bab89ae

File tree

7 files changed

+130
-85
lines changed

7 files changed

+130
-85
lines changed

src/chain/chaininterface.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,9 @@ pub trait ChainWatchInterface: Sync + Send {
2525
//TODO: unregister
2626
}
2727

28-
/// An interface to send a transaction to connected Bitcoin peers.
29-
/// This is for final settlement. An error might indicate that no peers can be reached or
30-
/// that peers rejected the transaction.
28+
/// An interface to send a transaction to the Bitcoin network.
3129
pub trait BroadcasterInterface: Sync + Send {
32-
/// Sends a transaction out to (hopefully) be mined
30+
/// Sends a transaction out to (hopefully) be mined.
3331
fn broadcast_transaction(&self, tx: &Transaction);
3432
}
3533

@@ -105,8 +103,9 @@ impl ChainWatchInterfaceUtil {
105103
}
106104
}
107105

108-
/// notify listener that a block was connected
109-
/// notification will repeat if notified listener register new listeners
106+
/// Notify listeners that a block was connected.
107+
/// Handles re-scanning the block and calling block_connected again if listeners register new
108+
/// watch data during the callbacks for you (see ChainListener::block_connected for more info).
110109
pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
111110
let mut reentered = true;
112111
while reentered {
@@ -125,7 +124,7 @@ impl ChainWatchInterfaceUtil {
125124
}
126125
}
127126

128-
/// notify listener that a block was disconnected
127+
/// Notify listeners that a block was disconnected.
129128
pub fn block_disconnected(&self, header: &BlockHeader) {
130129
let listeners = self.listeners.lock().unwrap().clone();
131130
for listener in listeners.iter() {
@@ -136,8 +135,10 @@ impl ChainWatchInterfaceUtil {
136135
}
137136
}
138137

139-
/// call listeners for connected blocks if they are still around.
140-
/// returns true if notified listeners registered additional listener
138+
/// Notify listeners that a block was connected.
139+
/// Returns true if notified listeners registered additional watch data (implying that the
140+
/// block must be re-scanned and this function called again prior to further block_connected
141+
/// calls, see ChainListener::block_connected for more info).
141142
pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
142143
let last_seen = self.reentered.load(Ordering::Relaxed);
143144

@@ -151,7 +152,7 @@ impl ChainWatchInterfaceUtil {
151152
return last_seen != self.reentered.load(Ordering::Relaxed);
152153
}
153154

154-
/// Checks if a given transaction matches the current filter
155+
/// Checks if a given transaction matches the current filter.
155156
pub fn does_match_tx(&self, tx: &Transaction) -> bool {
156157
let watched = self.watched.lock().unwrap();
157158
self.does_match_tx_unguarded (tx, &watched)

src/ln/channel.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ impl Channel {
374374
if msg.htlc_minimum_msat >= (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 {
375375
return Err(HandleError{err: "Minimum htlc value is full channel value", msg: None});
376376
}
377-
Channel::check_remote_fee(fee_estimator, msg.feerate_per_kw).unwrap();
377+
Channel::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
378378
if msg.to_self_delay > MAX_LOCAL_BREAKDOWN_TIMEOUT {
379379
return Err(HandleError{err: "They wanted our payments to be delayed by a needlessly long period", msg: None});
380380
}

src/ln/channelmanager.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1211,6 +1211,7 @@ impl ChannelMessageHandler for ChannelManager {
12111211

12121212
#[cfg(test)]
12131213
mod tests {
1214+
use chain::chaininterface;
12141215
use ln::channelmanager::{ChannelManager,OnionKeys};
12151216
use ln::router::{Route, RouteHop, Router};
12161217
use ln::msgs;
@@ -1389,17 +1390,17 @@ mod tests {
13891390
}
13901391

13911392
static mut CHAN_COUNT: u16 = 0;
1392-
fn confirm_transaction(chain: &test_utils::TestWatchInterface, tx: &Transaction) {
1393+
fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction) {
13931394
let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
13941395
let chan_id = unsafe { CHAN_COUNT };
1395-
chain.watch_util.block_connected_checked(&header, 1, &[tx; 1], &[chan_id as u32; 1]);
1396+
chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id as u32; 1]);
13961397
for i in 2..100 {
13971398
header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1398-
chain.watch_util.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
1399+
chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
13991400
}
14001401
}
14011402

1402-
fn create_chan_between_nodes(node_a: &ChannelManager, chain_a: &test_utils::TestWatchInterface, node_b: &ChannelManager, chain_b: &test_utils::TestWatchInterface) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
1403+
fn create_chan_between_nodes(node_a: &ChannelManager, chain_a: &chaininterface::ChainWatchInterfaceUtil, node_b: &ChannelManager, chain_b: &chaininterface::ChainWatchInterfaceUtil) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
14031404
let open_chan = node_a.create_channel(node_b.get_our_node_id(), (1 << 24) - 1, 42).unwrap();
14041405
let accept_chan = node_b.handle_open_channel(&node_a.get_our_node_id(), &open_chan).unwrap();
14051406
node_a.handle_accept_channel(&node_b.get_our_node_id(), &accept_chan).unwrap();
@@ -1615,7 +1616,7 @@ mod tests {
16151616
let secp_ctx = Secp256k1::new();
16161617

16171618
let feeest_1 = Arc::new(test_utils::TestFeeEstimator { sat_per_vbyte: 1 });
1618-
let chain_monitor_1 = Arc::new(test_utils::TestWatchInterface::new());
1619+
let chain_monitor_1 = Arc::new(chaininterface::ChainWatchInterfaceUtil::new());
16191620
let chan_monitor_1 = Arc::new(test_utils::TestChannelMonitor{});
16201621
let node_id_1 = {
16211622
let mut key_slice = [0; 32];
@@ -1626,7 +1627,7 @@ mod tests {
16261627
let router_1 = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id_1).unwrap());
16271628

16281629
let feeest_2 = Arc::new(test_utils::TestFeeEstimator { sat_per_vbyte: 1 });
1629-
let chain_monitor_2 = Arc::new(test_utils::TestWatchInterface::new());
1630+
let chain_monitor_2 = Arc::new(chaininterface::ChainWatchInterfaceUtil::new());
16301631
let chan_monitor_2 = Arc::new(test_utils::TestChannelMonitor{});
16311632
let node_id_2 = {
16321633
let mut key_slice = [0; 32];
@@ -1637,7 +1638,7 @@ mod tests {
16371638
let router_2 = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id_2).unwrap());
16381639

16391640
let feeest_3 = Arc::new(test_utils::TestFeeEstimator { sat_per_vbyte: 1 });
1640-
let chain_monitor_3 = Arc::new(test_utils::TestWatchInterface::new());
1641+
let chain_monitor_3 = Arc::new(chaininterface::ChainWatchInterfaceUtil::new());
16411642
let chan_monitor_3 = Arc::new(test_utils::TestChannelMonitor{});
16421643
let node_id_3 = {
16431644
let mut key_slice = [0; 32];
@@ -1648,7 +1649,7 @@ mod tests {
16481649
let router_3 = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id_3).unwrap());
16491650

16501651
let feeest_4 = Arc::new(test_utils::TestFeeEstimator { sat_per_vbyte: 1 });
1651-
let chain_monitor_4 = Arc::new(test_utils::TestWatchInterface::new());
1652+
let chain_monitor_4 = Arc::new(chaininterface::ChainWatchInterfaceUtil::new());
16521653
let chan_monitor_4 = Arc::new(test_utils::TestChannelMonitor{});
16531654
let node_id_4 = {
16541655
let mut key_slice = [0; 32];

src/ln/channelmonitor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,7 @@ impl ChannelMonitor {
456456
for txin in tx.input.iter() {
457457
if self.funding_txo.is_none() || (txin.prev_hash == self.funding_txo.unwrap().0 && txin.prev_index == self.funding_txo.unwrap().1 as u32) {
458458
for tx in self.check_spend_transaction(tx, height).iter() {
459-
broadcaster.broadcast_transaction(tx); // TODO: use result
459+
broadcaster.broadcast_transaction(tx);
460460
}
461461
}
462462
}

src/ln/msgs.rs

Lines changed: 90 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ pub enum DecodeError {
2020
UnknownRealmByte,
2121
/// Failed to decode a public key (ie it's invalid)
2222
BadPublicKey,
23+
/// Failed to decode a signature (ie it's invalid)
24+
BadSignature,
2325
/// Buffer not of right length (either too short or too long)
2426
WrongLength,
2527
}
@@ -408,6 +410,7 @@ impl Error for DecodeError {
408410
match *self {
409411
DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
410412
DecodeError::BadPublicKey => "Invalid public key in packet",
413+
DecodeError::BadSignature => "Invalid signature in packet",
411414
DecodeError::WrongLength => "Data was wrong length for packet",
412415
}
413416
}
@@ -433,11 +436,20 @@ macro_rules! secp_pubkey {
433436
};
434437
}
435438

439+
macro_rules! secp_signature {
440+
( $ctx: expr, $slice: expr ) => {
441+
match Signature::from_compact($ctx, $slice) {
442+
Ok(sig) => sig,
443+
Err(_) => return Err(DecodeError::BadSignature)
444+
}
445+
};
446+
}
447+
436448
impl MsgDecodable for LocalFeatures {
437449
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
438450
if v.len() < 3 { return Err(DecodeError::WrongLength); }
439451
let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
440-
if v.len() != len + 2 { return Err(DecodeError::WrongLength); }
452+
if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
441453
let mut flags = Vec::with_capacity(len);
442454
flags.extend_from_slice(&v[2..]);
443455
Ok(Self {
@@ -458,7 +470,7 @@ impl MsgDecodable for GlobalFeatures {
458470
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
459471
if v.len() < 3 { return Err(DecodeError::WrongLength); }
460472
let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
461-
if v.len() != len + 2 { return Err(DecodeError::WrongLength); }
473+
if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
462474
let mut flags = Vec::with_capacity(len);
463475
flags.extend_from_slice(&v[2..]);
464476
Ok(Self {
@@ -478,13 +490,10 @@ impl MsgEncodable for GlobalFeatures {
478490
impl MsgDecodable for Init {
479491
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
480492
let global_features = GlobalFeatures::decode(v)?;
481-
if global_features.flags.len() + 4 <= v.len() {
493+
if v.len() < global_features.flags.len() + 4 {
482494
return Err(DecodeError::WrongLength);
483495
}
484496
let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
485-
if global_features.flags.len() + local_features.flags.len() + 4 != v.len() {
486-
return Err(DecodeError::WrongLength);
487-
}
488497
Ok(Self {
489498
global_features: global_features,
490499
local_features: local_features,
@@ -502,24 +511,20 @@ impl MsgEncodable for Init {
502511

503512
impl MsgDecodable for OpenChannel {
504513
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
505-
if v.len() != 2*32+6*8+4+2*2+6*33+1 {
514+
if v.len() < 2*32+6*8+4+2*2+6*33+1 {
506515
return Err(DecodeError::WrongLength);
507516
}
508517
let ctx = Secp256k1::without_caps();
509-
let funding_pubkey = secp_pubkey!(&ctx, &v[120..153]);
510-
let revocation_basepoint = secp_pubkey!(&ctx, &v[153..186]);
511-
let payment_basepoint = secp_pubkey!(&ctx, &v[186..219]);
512-
let delayed_payment_basepoint = secp_pubkey!(&ctx, &v[219..252]);
513-
let htlc_basepoint = secp_pubkey!(&ctx, &v[252..285]);
514-
let first_per_commitment_point = secp_pubkey!(&ctx, &v[285..318]);
515518

516519
let mut shutdown_scriptpubkey = None;
517520
if v.len() >= 321 {
518521
let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
519-
if v.len() != 321+len {
522+
if v.len() < 321+len {
520523
return Err(DecodeError::WrongLength);
521524
}
522525
shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
526+
} else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
527+
return Err(DecodeError::WrongLength);
523528
}
524529

525530
Ok(OpenChannel {
@@ -534,12 +539,12 @@ impl MsgDecodable for OpenChannel {
534539
feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
535540
to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
536541
max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
537-
funding_pubkey: funding_pubkey,
538-
revocation_basepoint: revocation_basepoint,
539-
payment_basepoint: payment_basepoint,
540-
delayed_payment_basepoint: delayed_payment_basepoint,
541-
htlc_basepoint: htlc_basepoint,
542-
first_per_commitment_point: first_per_commitment_point,
542+
funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
543+
revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
544+
payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
545+
delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
546+
htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
547+
first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
543548
channel_flags: v[318],
544549
shutdown_scriptpubkey: shutdown_scriptpubkey
545550
})
@@ -551,10 +556,41 @@ impl MsgEncodable for OpenChannel {
551556
}
552557
}
553558

554-
555559
impl MsgDecodable for AcceptChannel {
556-
fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
557-
unimplemented!();
560+
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
561+
if v.len() < 32+4*8+4+2*2+6*33 {
562+
return Err(DecodeError::WrongLength);
563+
}
564+
let ctx = Secp256k1::without_caps();
565+
566+
let mut shutdown_scriptpubkey = None;
567+
if v.len() >= 272 {
568+
let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
569+
if v.len() < 272+len {
570+
return Err(DecodeError::WrongLength);
571+
}
572+
shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
573+
} else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
574+
return Err(DecodeError::WrongLength);
575+
}
576+
577+
Ok(Self {
578+
temporary_channel_id: deserialize(&v[0..32]).unwrap(),
579+
dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
580+
max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
581+
channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
582+
htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
583+
minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
584+
to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
585+
max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
586+
funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
587+
revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
588+
payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
589+
delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
590+
htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
591+
first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
592+
shutdown_scriptpubkey: shutdown_scriptpubkey
593+
})
558594
}
559595
}
560596
impl MsgEncodable for AcceptChannel {
@@ -564,8 +600,17 @@ impl MsgEncodable for AcceptChannel {
564600
}
565601

566602
impl MsgDecodable for FundingCreated {
567-
fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
568-
unimplemented!();
603+
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
604+
if v.len() < 32+32+2+64 {
605+
return Err(DecodeError::WrongLength);
606+
}
607+
let ctx = Secp256k1::without_caps();
608+
Ok(Self {
609+
temporary_channel_id: deserialize(&v[0..32]).unwrap(),
610+
funding_txid: deserialize(&v[32..64]).unwrap(),
611+
funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
612+
signature: secp_signature!(&ctx, &v[66..130]),
613+
})
569614
}
570615
}
571616
impl MsgEncodable for FundingCreated {
@@ -575,8 +620,15 @@ impl MsgEncodable for FundingCreated {
575620
}
576621

577622
impl MsgDecodable for FundingSigned {
578-
fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
579-
unimplemented!();
623+
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
624+
if v.len() < 32+64 {
625+
return Err(DecodeError::WrongLength);
626+
}
627+
let ctx = Secp256k1::without_caps();
628+
Ok(Self {
629+
channel_id: deserialize(&v[0..32]).unwrap(),
630+
signature: secp_signature!(&ctx, &v[32..96]),
631+
})
580632
}
581633
}
582634
impl MsgEncodable for FundingSigned {
@@ -586,8 +638,15 @@ impl MsgEncodable for FundingSigned {
586638
}
587639

588640
impl MsgDecodable for FundingLocked {
589-
fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
590-
unimplemented!();
641+
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
642+
if v.len() < 32+33 {
643+
return Err(DecodeError::WrongLength);
644+
}
645+
let ctx = Secp256k1::without_caps();
646+
Ok(Self {
647+
channel_id: deserialize(&v[0..32]).unwrap(),
648+
next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
649+
})
591650
}
592651
}
593652
impl MsgEncodable for FundingLocked {
@@ -839,7 +898,7 @@ impl MsgEncodable for ChannelUpdate {
839898

840899
impl MsgDecodable for OnionRealm0HopData {
841900
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
842-
if v.len() != 32 {
901+
if v.len() < 32 {
843902
return Err(DecodeError::WrongLength);
844903
}
845904
Ok(OnionRealm0HopData {
@@ -862,7 +921,7 @@ impl MsgEncodable for OnionRealm0HopData {
862921

863922
impl MsgDecodable for OnionHopData {
864923
fn decode(v: &[u8]) -> Result<Self, DecodeError> {
865-
if v.len() != 65 {
924+
if v.len() < 65 {
866925
return Err(DecodeError::WrongLength);
867926
}
868927
let realm = v[0];

0 commit comments

Comments
 (0)