@@ -19,7 +19,8 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
19
19
use crate :: ln:: msgs;
20
20
use crate :: ln:: msgs:: MAX_VALUE_MSAT ;
21
21
use crate :: crypto:: chacha20:: ChaCha20 ;
22
- use crate :: crypto:: utils:: hkdf_extract_expand_5x;
22
+ use crate :: crypto:: chacha20poly1305rfc:: ChaCha20Poly1305RFC ;
23
+ use crate :: crypto:: utils:: { hkdf_extract_expand_5x, hkdf_extract_expand_twice} ;
23
24
use crate :: util:: errors:: APIError ;
24
25
use crate :: util:: logger:: Logger ;
25
26
@@ -52,6 +53,8 @@ pub struct ExpandedKey {
52
53
offers_base_key : [ u8 ; 32 ] ,
53
54
/// The key used to encrypt message metadata for BOLT 12 Offers.
54
55
offers_encryption_key : [ u8 ; 32 ] ,
56
+ /// The key used to encrypt our peer storage that would be sent to our peers.
57
+ our_peerstorage_encryption_key : [ u8 ; 32 ] ,
55
58
}
56
59
57
60
impl ExpandedKey {
@@ -66,12 +69,14 @@ impl ExpandedKey {
66
69
offers_base_key,
67
70
offers_encryption_key,
68
71
) = hkdf_extract_expand_5x ( b"LDK Inbound Payment Key Expansion" , & key_material. 0 ) ;
72
+ let ( our_peerstorage_encryption_key, _) = hkdf_extract_expand_twice ( b"Peer Storage Encryption Key" , & key_material. 0 ) ;
69
73
Self {
70
74
metadata_key,
71
75
ldk_pmt_hash_key,
72
76
user_pmt_hash_key,
73
77
offers_base_key,
74
78
offers_encryption_key,
79
+ our_peerstorage_encryption_key
75
80
}
76
81
}
77
82
@@ -93,6 +98,29 @@ impl ExpandedKey {
93
98
ChaCha20 :: encrypt_single_block_in_place ( & self . offers_encryption_key , & nonce. 0 , & mut bytes) ;
94
99
bytes
95
100
}
101
+
102
+ /// Encrypt given plaintext using [`ExpandedKey::our_peerstorage_encryption_key`].
103
+ pub ( crate ) fn encrypt_our_peer_storage ( & self , res : & mut [ u8 ] , n : u64 , h : & [ u8 ] , plaintext : & [ u8 ] ) {
104
+ let mut nonce = [ 0 ; 12 ] ;
105
+ nonce[ 4 ..] . copy_from_slice ( & n. to_le_bytes ( ) [ ..] ) ;
106
+
107
+ let mut chacha = ChaCha20Poly1305RFC :: new ( & self . our_peerstorage_encryption_key , & nonce, h) ;
108
+ let mut tag = [ 0 ; 16 ] ;
109
+ chacha. encrypt ( plaintext, & mut res[ 0 ..plaintext. len ( ) ] , & mut tag) ;
110
+ res[ plaintext. len ( ) ..] . copy_from_slice ( & tag) ;
111
+ }
112
+
113
+ /// Decrypt given cyphertext using [`ExpandedKey::our_peerstorage_encryption_key`].
114
+ pub ( crate ) fn decrypt_our_peer_storage ( & self , res : & mut [ u8 ] , n : u64 , h : & [ u8 ] , cyphertext : & [ u8 ] ) -> Result < ( ) , ( ) > {
115
+ let mut nonce = [ 0 ; 12 ] ;
116
+ nonce[ 4 ..] . copy_from_slice ( & n. to_le_bytes ( ) [ ..] ) ;
117
+
118
+ let mut chacha = ChaCha20Poly1305RFC :: new ( & self . our_peerstorage_encryption_key , & nonce, h) ;
119
+ if chacha. variable_time_decrypt ( & cyphertext[ 0 ..cyphertext. len ( ) - 16 ] , res, & cyphertext[ cyphertext. len ( ) - 16 ..] ) . is_err ( ) {
120
+ return Err ( ( ) ) ;
121
+ }
122
+ Ok ( ( ) )
123
+ }
96
124
}
97
125
98
126
/// A 128-bit number used only once.
0 commit comments