@@ -430,15 +430,6 @@ const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_P
430
430
#[ allow( dead_code) ]
431
431
const CHECK_CLTV_EXPIRY_SANITY_2 : u32 = CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2 * CLTV_CLAIM_BUFFER ;
432
432
433
- macro_rules! secp_call {
434
- ( $res: expr, $err: expr ) => {
435
- match $res {
436
- Ok ( key) => key,
437
- Err ( _) => return Err ( $err) ,
438
- }
439
- } ;
440
- }
441
-
442
433
/// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
443
434
pub struct ChannelDetails {
444
435
/// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
@@ -475,6 +466,32 @@ pub struct ChannelDetails {
475
466
pub is_live : bool ,
476
467
}
477
468
469
+ /// If a payment fails to send, it can be in one of several states. This enum is returned as the
470
+ /// Err() type describing which state the payment is in, see the description of individual enum
471
+ /// states for more.
472
+ #[ derive( Debug ) ]
473
+ pub enum PaymentSendFailure {
474
+ /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
475
+ /// send the payment at all. No channel state has been changed or messages sent to peers, and
476
+ /// once you've changed the parameter at error, you can freely retry the payment in full.
477
+ ParameterError ( APIError ) ,
478
+ /// All paths which were attempted failed to send, with no channel state change taking place.
479
+ /// You can freely retry the payment in full (though you probably want to do so over different
480
+ /// paths than the ones selected).
481
+ AllFailedRetrySafe ( Vec < APIError > ) ,
482
+ /// Some paths which were attempted failed to send, though possibly not all. At least some
483
+ /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
484
+ /// in over-/re-payment.
485
+ ///
486
+ /// The results here are ordered the same as the paths in the route object which was passed to
487
+ /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
488
+ /// retried.
489
+ ///
490
+ /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
491
+ /// as they will result in over-/re-payment.
492
+ PartialFailure ( Vec < Result < ( ) , APIError > > ) ,
493
+ }
494
+
478
495
macro_rules! handle_error {
479
496
( $self: ident, $internal: expr, $their_node_id: expr, $locked_channel_state: expr) => {
480
497
match $internal {
@@ -1169,109 +1186,154 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
1169
1186
/// payment_preimage tracking (which you should already be doing as they represent "proof of
1170
1187
/// payment") and prevent double-sends yourself.
1171
1188
///
1172
- /// May generate a SendHTLCs message event on success, which should be relayed.
1189
+ /// May generate SendHTLCs message(s) event on success, which should be relayed.
1190
+ ///
1191
+ /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1192
+ /// each entry matching the corresponding-index entry in the route paths.
1173
1193
///
1174
- /// Raises APIError::RoutError when invalid route or forward parameter
1175
- /// (cltv_delta, fee, node public key) is specified.
1176
- /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1177
- /// (including due to previous monitor update failure or new permanent monitor update failure).
1178
- /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1179
- /// relevant updates.
1194
+ /// In general, a path may raise:
1195
+ /// * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1196
+ /// node public key) is specified.
1197
+ /// * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1198
+ /// (including due to previous monitor update failure or new permanent monitor update
1199
+ /// failure).
1200
+ /// * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1201
+ /// relevant updates.
1180
1202
///
1181
- /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1182
- /// and you may wish to retry via a different route immediately.
1183
- /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1184
- /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1185
- /// the payment via a different route unless you intend to pay twice!
1203
+ /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1204
+ /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1205
+ /// different route unless you intend to pay twice!
1186
1206
///
1187
1207
/// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1188
1208
/// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1189
1209
/// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1190
1210
/// must not contain multiple paths as otherwise the multipath data cannot be sent.
1191
1211
/// If a payment_secret *is* provided, we assume that the invoice had the basic_mpp feature bit
1192
1212
/// set (either as required or as available).
1193
- pub fn send_payment ( & self , route : Route , payment_hash : PaymentHash , payment_secret : Option < & [ u8 ; 32 ] > ) -> Result < ( ) , APIError > {
1194
- if route. paths . len ( ) < 1 || route . paths . len ( ) > 1 {
1195
- return Err ( APIError :: RouteError { err : "We currently don't support MPP, and we need at least one path" } ) ;
1213
+ pub fn send_payment ( & self , route : Route , payment_hash : PaymentHash , payment_secret : Option < & [ u8 ; 32 ] > ) -> Result < ( ) , PaymentSendFailure > {
1214
+ if route. paths . len ( ) < 1 {
1215
+ return Err ( PaymentSendFailure :: ParameterError ( APIError :: RouteError { err : "There must be at least one path to send over" } ) ) ;
1196
1216
}
1197
- if route. paths [ 0 ] . len ( ) < 1 || route . paths [ 0 ] . len ( ) > 20 {
1198
- return Err ( APIError :: RouteError { err : "Path didn't go anywhere/had bogus size" } ) ;
1217
+ if route. paths . len ( ) > 10 {
1218
+ return Err ( PaymentSendFailure :: ParameterError ( APIError :: RouteError { err : "Sending over more than 10 paths is not currently supported" } ) ) ;
1199
1219
}
1220
+ let mut total_value = 0 ;
1200
1221
let our_node_id = self . get_our_node_id ( ) ;
1201
- for ( idx, hop) in route. paths [ 0 ] . iter ( ) . enumerate ( ) {
1202
- if idx != route. paths [ 0 ] . len ( ) - 1 && hop. pubkey == our_node_id {
1203
- return Err ( APIError :: RouteError { err : "Path went through us but wasn't a simple rebalance loop to us" } ) ;
1222
+ for path in route. paths . iter ( ) {
1223
+ if path. len ( ) < 1 || path. len ( ) > 20 {
1224
+ return Err ( PaymentSendFailure :: ParameterError ( APIError :: RouteError { err : "Path didn't go anywhere/had bogus size" } ) ) ;
1225
+ }
1226
+ for ( idx, hop) in path. iter ( ) . enumerate ( ) {
1227
+ if idx != path. len ( ) - 1 && hop. pubkey == our_node_id {
1228
+ return Err ( PaymentSendFailure :: ParameterError ( APIError :: RouteError { err : "Path went through us but wasn't a simple rebalance loop to us" } ) ) ;
1229
+ }
1204
1230
}
1231
+ total_value += path. last ( ) . unwrap ( ) . fee_msat ;
1205
1232
}
1206
-
1207
- let ( session_priv, prng_seed) = self . keys_manager . get_onion_rand ( ) ;
1208
-
1209
1233
let cur_height = self . latest_block_height . load ( Ordering :: Acquire ) as u32 + 1 ;
1234
+ let mut results = Vec :: new ( ) ;
1235
+ ' path_loop: for path in route. paths . iter ( ) {
1236
+ macro_rules! check_res_push {
1237
+ ( $res: expr) => { match $res {
1238
+ Ok ( r) => r,
1239
+ Err ( e) => {
1240
+ results. push( Err ( e) ) ;
1241
+ continue ' path_loop;
1242
+ } ,
1243
+ }
1244
+ }
1245
+ }
1210
1246
1211
- let onion_keys = secp_call ! ( onion_utils:: construct_onion_keys( & self . secp_ctx, & route. paths[ 0 ] , & session_priv) ,
1212
- APIError :: RouteError { err: "Pubkey along hop was maliciously selected" } ) ;
1213
- let ( onion_payloads, htlc_msat, htlc_cltv) = onion_utils:: build_onion_payloads ( & route. paths [ 0 ] , payment_secret, cur_height) ?;
1214
- if onion_utils:: route_size_insane ( & onion_payloads) {
1215
- return Err ( APIError :: RouteError { err : "Route size too large considering onion data" } ) ;
1216
- }
1217
- let onion_packet = onion_utils:: construct_onion_packet ( onion_payloads, onion_keys, prng_seed, & payment_hash) ;
1247
+ log_trace ! ( self , "Attempting to send payment for path with next hop {}" , path. first( ) . unwrap( ) . short_channel_id) ;
1248
+ let ( session_priv, prng_seed) = self . keys_manager . get_onion_rand ( ) ;
1218
1249
1219
- let _ = self . total_consistency_lock . read ( ) . unwrap ( ) ;
1250
+ let onion_keys = check_res_push ! ( onion_utils:: construct_onion_keys( & self . secp_ctx, & path, & session_priv)
1251
+ . map_err( |_| APIError :: RouteError { err: "Pubkey along hop was maliciously selected" } ) ) ;
1252
+ let ( onion_payloads, htlc_msat, htlc_cltv) = check_res_push ! ( onion_utils:: build_onion_payloads( & path, total_value, payment_secret, cur_height) ) ;
1253
+ if onion_utils:: route_size_insane ( & onion_payloads) {
1254
+ check_res_push ! ( Err ( APIError :: RouteError { err: "Route size too large considering onion data" } ) ) ;
1255
+ }
1256
+ let onion_packet = onion_utils:: construct_onion_packet ( onion_payloads, onion_keys, prng_seed, & payment_hash) ;
1220
1257
1221
- let mut channel_lock = self . channel_state . lock ( ) . unwrap ( ) ;
1222
- let err: Result < ( ) , _ > = loop {
1258
+ let _ = self . total_consistency_lock . read ( ) . unwrap ( ) ;
1223
1259
1224
- let id = match channel_lock. short_to_id . get ( & route. paths [ 0 ] . first ( ) . unwrap ( ) . short_channel_id ) {
1225
- None => return Err ( APIError :: ChannelUnavailable { err : "No channel available with first hop!" } ) ,
1226
- Some ( id) => id. clone ( ) ,
1227
- } ;
1260
+ let mut channel_lock = self . channel_state . lock ( ) . unwrap ( ) ;
1261
+ let err: Result < ( ) , _ > = loop {
1262
+ let id = match channel_lock. short_to_id . get ( & path. first ( ) . unwrap ( ) . short_channel_id ) {
1263
+ None => check_res_push ! ( Err ( APIError :: ChannelUnavailable { err: "No channel available with first hop!" } ) ) ,
1264
+ Some ( id) => id. clone ( ) ,
1265
+ } ;
1228
1266
1229
- let channel_state = & mut * channel_lock;
1230
- if let hash_map:: Entry :: Occupied ( mut chan) = channel_state. by_id . entry ( id) {
1231
- match {
1232
- if chan. get ( ) . get_their_node_id ( ) != route. paths [ 0 ] . first ( ) . unwrap ( ) . pubkey {
1233
- return Err ( APIError :: RouteError { err : "Node ID mismatch on first hop!" } ) ;
1234
- }
1235
- if !chan. get ( ) . is_live ( ) {
1236
- return Err ( APIError :: ChannelUnavailable { err : "Peer for first hop currently disconnected/pending monitor update!" } ) ;
1237
- }
1238
- break_chan_entry ! ( self , chan. get_mut( ) . send_htlc_and_commit( htlc_msat, payment_hash. clone( ) , htlc_cltv, HTLCSource :: OutboundRoute {
1239
- path: route. paths[ 0 ] . clone( ) ,
1240
- session_priv: session_priv. clone( ) ,
1241
- first_hop_htlc_msat: htlc_msat,
1242
- } , onion_packet) , channel_state, chan)
1243
- } {
1244
- Some ( ( update_add, commitment_signed, chan_monitor) ) => {
1245
- if let Err ( e) = self . monitor . add_update_monitor ( chan_monitor. get_funding_txo ( ) . unwrap ( ) , chan_monitor) {
1246
- maybe_break_monitor_err ! ( self , e, channel_state, chan, RAACommitmentOrder :: CommitmentFirst , false , true ) ;
1247
- // Note that MonitorUpdateFailed here indicates (per function docs)
1248
- // that we will resent the commitment update once we unfree monitor
1249
- // updating, so we have to take special care that we don't return
1250
- // something else in case we will resend later!
1251
- return Err ( APIError :: MonitorUpdateFailed ) ;
1267
+ let channel_state = & mut * channel_lock;
1268
+ if let hash_map:: Entry :: Occupied ( mut chan) = channel_state. by_id . entry ( id) {
1269
+ match {
1270
+ if chan. get ( ) . get_their_node_id ( ) != path. first ( ) . unwrap ( ) . pubkey {
1271
+ check_res_push ! ( Err ( APIError :: RouteError { err: "Node ID mismatch on first hop!" } ) ) ;
1252
1272
}
1273
+ if !chan. get ( ) . is_live ( ) {
1274
+ check_res_push ! ( Err ( APIError :: ChannelUnavailable { err: "Peer for first hop currently disconnected/pending monitor update!" } ) ) ;
1275
+ }
1276
+ break_chan_entry ! ( self , chan. get_mut( ) . send_htlc_and_commit( htlc_msat, payment_hash. clone( ) , htlc_cltv, HTLCSource :: OutboundRoute {
1277
+ path: path. clone( ) ,
1278
+ session_priv: session_priv. clone( ) ,
1279
+ first_hop_htlc_msat: htlc_msat,
1280
+ } , onion_packet) , channel_state, chan)
1281
+ } {
1282
+ Some ( ( update_add, commitment_signed, chan_monitor) ) => {
1283
+ if let Err ( e) = self . monitor . add_update_monitor ( chan_monitor. get_funding_txo ( ) . unwrap ( ) , chan_monitor) {
1284
+ maybe_break_monitor_err ! ( self , e, channel_state, chan, RAACommitmentOrder :: CommitmentFirst , false , true ) ;
1285
+ // Note that MonitorUpdateFailed here indicates (per function docs)
1286
+ // that we will resent the commitment update once we unfree monitor
1287
+ // updating, so we have to take special care that we don't return
1288
+ // something else in case we will resend later!
1289
+ check_res_push ! ( Err ( APIError :: MonitorUpdateFailed ) ) ;
1290
+ }
1253
1291
1254
- channel_state. pending_msg_events . push ( events:: MessageSendEvent :: UpdateHTLCs {
1255
- node_id : route. paths [ 0 ] . first ( ) . unwrap ( ) . pubkey ,
1256
- updates : msgs:: CommitmentUpdate {
1257
- update_add_htlcs : vec ! [ update_add] ,
1258
- update_fulfill_htlcs : Vec :: new ( ) ,
1259
- update_fail_htlcs : Vec :: new ( ) ,
1260
- update_fail_malformed_htlcs : Vec :: new ( ) ,
1261
- update_fee : None ,
1262
- commitment_signed,
1263
- } ,
1264
- } ) ;
1265
- } ,
1266
- None => { } ,
1267
- }
1268
- } else { unreachable ! ( ) ; }
1269
- return Ok ( ( ) ) ;
1270
- } ;
1292
+ channel_state. pending_msg_events . push ( events:: MessageSendEvent :: UpdateHTLCs {
1293
+ node_id : path. first ( ) . unwrap ( ) . pubkey ,
1294
+ updates : msgs:: CommitmentUpdate {
1295
+ update_add_htlcs : vec ! [ update_add] ,
1296
+ update_fulfill_htlcs : Vec :: new ( ) ,
1297
+ update_fail_htlcs : Vec :: new ( ) ,
1298
+ update_fail_malformed_htlcs : Vec :: new ( ) ,
1299
+ update_fee : None ,
1300
+ commitment_signed,
1301
+ } ,
1302
+ } ) ;
1303
+ } ,
1304
+ None => { } ,
1305
+ }
1306
+ } else { unreachable ! ( ) ; }
1307
+ results. push ( Ok ( ( ) ) ) ;
1308
+ continue ' path_loop;
1309
+ } ;
1271
1310
1272
- match handle_error ! ( self , err, route. paths[ 0 ] . first( ) . unwrap( ) . pubkey, channel_lock) {
1273
- Ok ( _) => unreachable ! ( ) ,
1274
- Err ( e) => { Err ( APIError :: ChannelUnavailable { err : e. err } ) }
1311
+ match handle_error ! ( self , err, path. first( ) . unwrap( ) . pubkey, channel_lock) {
1312
+ Ok ( _) => unreachable ! ( ) ,
1313
+ Err ( e) => {
1314
+ check_res_push ! ( Err ( APIError :: ChannelUnavailable { err: e. err } ) ) ;
1315
+ } ,
1316
+ }
1317
+ }
1318
+ let mut has_ok = false ;
1319
+ let mut has_err = false ;
1320
+ for res in results. iter ( ) {
1321
+ if res. is_ok ( ) { has_ok = true ; }
1322
+ if res. is_err ( ) { has_err = true ; }
1323
+ if let & Err ( APIError :: MonitorUpdateFailed ) = res {
1324
+ // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1325
+ // PartialFailure.
1326
+ has_err = true ;
1327
+ has_ok = true ;
1328
+ break ;
1329
+ }
1330
+ }
1331
+ if has_err && has_ok {
1332
+ Err ( PaymentSendFailure :: PartialFailure ( results) )
1333
+ } else if has_err {
1334
+ Err ( PaymentSendFailure :: AllFailedRetrySafe ( results. drain ( ..) . map ( |r| r. unwrap_err ( ) ) . collect ( ) ) )
1335
+ } else {
1336
+ Ok ( ( ) )
1275
1337
}
1276
1338
}
1277
1339
0 commit comments