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