@@ -358,6 +358,75 @@ impl TxMetadataStore {
358358 Err ( ( ) )
359359 }
360360 }
361+
362+ /// Sets the preimage for an outgoing lightning payment. If the payment already has a preimage,
363+ /// this is a no-op and returns Ok(()). If the payment_id does not exist in the store, or if the payment
364+ /// is not an outgoing lightning payment, returns Err(()).
365+ pub fn set_preimage ( & self , payment_id : PaymentId , preimage : [ u8 ; 32 ] ) -> Result < ( ) , ( ) > {
366+ let mut tx_metadata = self . tx_metadata . write ( ) . unwrap ( ) ;
367+ if let Some ( metadata) = tx_metadata. get_mut ( & payment_id) {
368+ match metadata. ty {
369+ TxType :: Payment { ty } => match ty {
370+ PaymentType :: OutgoingLightningBolt12 { payment_preimage } => {
371+ if payment_preimage. is_some ( ) {
372+ Ok ( ( ) )
373+ } else {
374+ metadata. ty = TxType :: Payment {
375+ ty : PaymentType :: OutgoingLightningBolt12 {
376+ payment_preimage : Some ( PaymentPreimage ( preimage) ) ,
377+ } ,
378+ } ;
379+
380+ self . store
381+ . write (
382+ STORE_PRIMARY_KEY ,
383+ STORE_SECONDARY_KEY ,
384+ & payment_id. to_string ( ) ,
385+ & metadata. encode ( ) ,
386+ )
387+ . expect ( "We do not allow writes to fail" ) ;
388+ Ok ( ( ) )
389+ }
390+ } ,
391+ PaymentType :: OutgoingLightningBolt11 { payment_preimage } => {
392+ if payment_preimage. is_some ( ) {
393+ Ok ( ( ) )
394+ } else {
395+ metadata. ty = TxType :: Payment {
396+ ty : PaymentType :: OutgoingLightningBolt11 {
397+ payment_preimage : Some ( PaymentPreimage ( preimage) ) ,
398+ } ,
399+ } ;
400+
401+ self . store
402+ . write (
403+ STORE_PRIMARY_KEY ,
404+ STORE_SECONDARY_KEY ,
405+ & payment_id. to_string ( ) ,
406+ & metadata. encode ( ) ,
407+ )
408+ . expect ( "We do not allow writes to fail" ) ;
409+ Ok ( ( ) )
410+ }
411+ } ,
412+ _ => {
413+ eprintln ! (
414+ "payment_id {payment_id} is not an outgoing lightning payment, cannot set preimage"
415+ ) ;
416+ Err ( ( ) )
417+ } ,
418+ } ,
419+ _ => {
420+ // if we're trying to set a preimage on a non-payment, just continue
421+ // this should only happen when we finish a rebalance payment
422+ Ok ( ( ) )
423+ } ,
424+ }
425+ } else {
426+ eprintln ! ( "doesn't exist in metadata store: {payment_id}" ) ;
427+ Err ( ( ) )
428+ }
429+ }
361430}
362431
363432const REBALANCE_ENABLED_KEY : & str = "rebalance_enabled" ;
0 commit comments