MCPcopy Create free account
hub / github.com/ElementsProject/lightning / cryptomsg_encrypt_msg

Function cryptomsg_encrypt_msg

common/cryptomsg.c:151–236  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

149}
150
151u8 *cryptomsg_encrypt_msg(const tal_t *ctx,
152 struct crypto_state *cs,
153 const u8 *msg TAKES)
154{
155 unsigned char npub[crypto_aead_chacha20poly1305_ietf_NPUBBYTES];
156 unsigned long long clen, mlen = tal_count(msg);
157 be16 l;
158 int ret;
159 u8 *out;
160
161 out = tal_arr(ctx, u8, sizeof(l) + 16 + mlen + 16);
162
163 /* BOLT #8:
164 *
165 * In order to encrypt and send a Lightning message (`m`) to the
166 * network stream, given a sending key (`sk`) and a nonce (`sn`), the
167 * following steps are completed:
168 *
169 * 1. Let `l = len(m)`.
170 * * where `len` obtains the length in bytes of the Lightning
171 * message
172 *
173 * 2. Serialize `l` into 2 bytes encoded as a big-endian integer.
174 */
175 l = cpu_to_be16(mlen);
176
177 /* BOLT #8:
178 *
179 * 3. Encrypt `l` (using `ChaChaPoly-1305`, `sn`, and `sk`), to obtain
180 * `lc` (18 bytes)
181 * * The nonce `sn` is encoded as a 96-bit little-endian number. As
182 * the decoded nonce is 64 bits, the 96-bit nonce is encoded as:
183 * 32 bits of leading 0s followed by a 64-bit value.
184 * * The nonce `sn` MUST be incremented after this step.
185 * * A zero-length byte slice is to be passed as the AD (associated
186 data).
187 */
188 le64_nonce(npub, cs->sn++);
189 ret = crypto_aead_chacha20poly1305_ietf_encrypt(out, &clen,
190 (unsigned char *)
191 memcheck(&l, sizeof(l)),
192 sizeof(l),
193 NULL, 0,
194 NULL, npub,
195 cs->sk.data);
196 assert(ret == 0);
197 assert(clen == sizeof(l) + 16);
198#ifdef SUPERVERBOSE
199 status_debug("# encrypt l: cleartext=0x%s, AD=NULL, sn=0x%s, sk=0x%s => 0x%s",
200 tal_hexstr(trc, &l, sizeof(l)),
201 tal_hexstr(trc, npub, sizeof(npub)),
202 tal_hexstr(trc, &cs->sk, sizeof(cs->sk)),
203 tal_hexstr(trc, out, clen));
204#endif
205
206 /* BOLT #8:
207 *
208 * 4. Finally, encrypt the message itself (`m`) using the same

Callers 6

encrypt_and_sendFunction · 0.85
peer_connectedFunction · 0.85
peer_init_receivedFunction · 0.85
peer_exchange_initmsgFunction · 0.85
mainFunction · 0.85
sync_crypto_writeFunction · 0.85

Calls 6

cpu_to_be16Function · 0.85
tal_hexstrFunction · 0.85
maybe_rotate_keyFunction · 0.85
takenFunction · 0.85
tal_freeFunction · 0.85
le64_nonceFunction · 0.70

Tested by 1

mainFunction · 0.68