Merge remote-tracking branch 'origin/pr/46'

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
This commit is contained in:
Rusty Russell
2016-10-17 12:37:16 +10:30
14 changed files with 854 additions and 1271 deletions

View File

@@ -30,7 +30,6 @@ DAEMON_SRC := \
daemon/jsonrpc.c \
daemon/lightningd.c \
daemon/netaddr.c \
daemon/onion.c \
daemon/opt_time.c \
daemon/output_to_htlc.c \
daemon/packets.c \
@@ -38,6 +37,7 @@ DAEMON_SRC := \
daemon/peer.c \
daemon/routing.c \
daemon/secrets.c \
daemon/sphinx.c \
daemon/timeout.c \
daemon/wallet.c \
daemon/watch.c \
@@ -79,7 +79,6 @@ DAEMON_HEADERS := \
daemon/lightningd.h \
daemon/log.h \
daemon/netaddr.h \
daemon/onion.h \
daemon/opt_time.h \
daemon/output_to_htlc.h \
daemon/packets.h \
@@ -88,6 +87,7 @@ DAEMON_HEADERS := \
daemon/pseudorand.h \
daemon/routing.h \
daemon/secrets.h \
daemon/sphinx.h \
daemon/timeout.h \
daemon/wallet.h \
daemon/watch.h

View File

@@ -1,82 +0,0 @@
#include "log.h"
#include "onion.h"
#include "peer.h"
#include "protobuf_convert.h"
#include "routing.h"
#include <string.h>
/* FIXME: http://www.cypherpunks.ca/~iang/pubs/Sphinx_Oakland09.pdf */
/* Frees r */
static const u8 *to_onion(const tal_t *ctx, const Route *r)
{
u8 *onion = tal_arr(ctx, u8, route__get_packed_size(r));
route__pack(r, onion);
tal_free(r);
return onion;
}
/* Create an onion for this path. */
const u8 *onion_create(const tal_t *ctx,
secp256k1_context *secpctx,
const struct pubkey *ids,
const u64 *amounts,
size_t num_hops)
{
Route *r = tal(ctx, Route);
size_t i;
route__init(r);
r->n_steps = num_hops + 1;
r->steps = tal_arr(r, RouteStep *, r->n_steps);
for (i = 0; i < num_hops; i++) {
r->steps[i] = tal(r, RouteStep);
route_step__init(r->steps[i]);
r->steps[i]->next_case = ROUTE_STEP__NEXT_BITCOIN;
r->steps[i]->bitcoin = pubkey_to_proto(r, secpctx, &ids[i]);
r->steps[i]->amount = amounts[i];
}
/* Now the stop marker. */
r->steps[i] = tal(r, RouteStep);
route_step__init(r->steps[i]);
r->steps[i]->next_case = ROUTE_STEP__NEXT_END;
r->steps[i]->end = true;
r->steps[i]->amount = 0;
return to_onion(ctx, r);
}
/* Decode next step in the route, and fill out the onion to send onwards. */
RouteStep *onion_unwrap(struct peer *peer,
const void *data, size_t len, const u8 **next)
{
struct ProtobufCAllocator *prototal = make_prototal(peer);
Route *r;
RouteStep *step;
r = route__unpack(prototal, len, data);
if (!r || r->n_steps == 0) {
log_unusual(peer->log, "Failed to unwrap onion");
tal_free(prototal);
return NULL;
}
/* Remove first step. */
step = r->steps[0];
/* Make sure that step owns the rest */
steal_from_prototal(peer, prototal, step);
/* Re-pack with remaining steps. */
r->n_steps--;
memmove(r->steps, r->steps + 1, sizeof(*r->steps) * r->n_steps);
if (!r->n_steps) {
*next = NULL;
tal_free(r);
} else
*next = to_onion(peer, r);
return step;
}

View File

@@ -1,21 +0,0 @@
#ifndef LIGHTNING_DAEMON_ONION_H
#define LIGHTNING_DAEMON_ONION_H
#include "config.h"
#include "lightning.pb-c.h"
#include <ccan/short_types/short_types.h>
#include <secp256k1.h>
struct peer;
struct node_connection;
/* Decode next step in the route, and fill out the onion to send onwards. */
RouteStep *onion_unwrap(struct peer *peer,
const void *data, size_t len, const u8 **next);
/* Create an onion for sending msatoshi down path, paying fees. */
const u8 *onion_create(const tal_t *ctx,
secp256k1_context *secpctx,
const struct pubkey *ids,
const u64 *amounts,
size_t num_hops);
#endif /* LIGHTNING_DAEMON_ONION_H */

View File

@@ -4,13 +4,14 @@
#include "jsonrpc.h"
#include "lightningd.h"
#include "log.h"
#include "onion.h"
#include "pay.h"
#include "peer.h"
#include "routing.h"
#include "sphinx.h"
#include <ccan/str/hex/hex.h>
#include <ccan/structeq/structeq.h>
#include <inttypes.h>
#include <sodium/randombytes.h>
/* Outstanding "pay" commands. */
struct pay_command {
@@ -293,7 +294,6 @@ static void json_sendpay(struct command *cmd,
const char *buffer, const jsmntok_t *params)
{
struct pubkey *ids;
u64 *amounts;
jsmntok_t *routetok, *rhashtok;
const jsmntok_t *t, *end;
unsigned int delay;
@@ -303,8 +303,12 @@ static void json_sendpay(struct command *cmd,
struct pay_command *pc;
bool replacing = false;
const u8 *onion;
u8 sessionkey[32];
enum fail_error error_code;
const char *err;
struct hoppayload *hoppayloads;
u64 amount, lastamount;
struct onionpacket *packet;
if (!json_get_params(buffer, params,
"route", &routetok,
@@ -332,8 +336,8 @@ static void json_sendpay(struct command *cmd,
end = json_next(routetok);
n_hops = 0;
amounts = tal_arr(cmd, u64, n_hops);
ids = tal_arr(cmd, struct pubkey, n_hops);
hoppayloads = tal_arr(cmd, struct hoppayload, 0);
for (t = routetok + 1; t < end; t = json_next(t)) {
const jsmntok_t *amttok, *idtok, *delaytok;
@@ -353,12 +357,26 @@ static void json_sendpay(struct command *cmd,
return;
}
tal_resize(&amounts, n_hops+1);
if (!json_tok_u64(buffer, amttok, &amounts[n_hops])) {
command_fail(cmd, "route %zu invalid msatoshi", n_hops);
return;
if (n_hops == 0) {
/* What we will send */
if (!json_tok_u64(buffer, amttok, &amount)) {
command_fail(cmd, "route %zu invalid msatoshi", n_hops);
return;
}
lastamount = amount;
} else{
/* What that hop will forward */
tal_resize(&hoppayloads, n_hops);
memset(&hoppayloads[n_hops-1], 0, sizeof(struct hoppayload));
if (!json_tok_u64(buffer, amttok, &hoppayloads[n_hops-1].amount)) {
command_fail(cmd, "route %zu invalid msatoshi", n_hops);
return;
}
lastamount = hoppayloads[n_hops-1].amount;
}
tal_resize(&ids, n_hops+1);
memset(&ids[n_hops], 0, sizeof(ids[n_hops]));
if (!pubkey_from_hexstr(cmd->dstate->secpctx,
buffer + idtok->start,
idtok->end - idtok->start,
@@ -374,6 +392,10 @@ static void json_sendpay(struct command *cmd,
n_hops++;
}
/* Add payload for final hop */
tal_resize(&hoppayloads, n_hops);
memset(&hoppayloads[n_hops-1], 0, sizeof(struct hoppayload));
if (n_hops == 0) {
command_fail(cmd, "Empty route");
return;
@@ -392,7 +414,7 @@ static void json_sendpay(struct command *cmd,
size_t old_nhops = tal_count(pc->ids);
log_add(cmd->dstate->base_log, "... succeeded");
/* Must match successful payment parameters. */
if (pc->msatoshi != amounts[n_hops-1]) {
if (pc->msatoshi != lastamount) {
command_fail(cmd,
"already succeeded with amount %"
PRIu64, pc->msatoshi);
@@ -420,9 +442,13 @@ static void json_sendpay(struct command *cmd,
return;
}
randombytes_buf(&sessionkey, sizeof(sessionkey));
/* Onion will carry us from first peer onwards. */
onion = onion_create(cmd, cmd->dstate->secpctx, ids+1, amounts+1,
n_hops-1);
packet = create_onionpacket(
cmd, cmd->dstate->secpctx, ids, hoppayloads,
sessionkey, (u8*)"", 0);
onion = serialize_onionpacket(cmd, cmd->dstate->secpctx, packet);
if (pc)
pc->ids = tal_free(pc->ids);
@@ -432,10 +458,10 @@ static void json_sendpay(struct command *cmd,
pc->rhash = rhash;
pc->rval = NULL;
pc->ids = tal_steal(pc, ids);
pc->msatoshi = amounts[n_hops-1];
pc->msatoshi = lastamount;
/* Expiry for HTLCs is absolute. And add one to give some margin. */
err = command_htlc_add(peer, amounts[0],
err = command_htlc_add(peer, amount,
delay + get_block_height(cmd->dstate) + 1,
&rhash, NULL,
onion, &error_code, &pc->htlc);

View File

@@ -13,7 +13,6 @@
#include "log.h"
#include "names.h"
#include "netaddr.h"
#include "onion.h"
#include "output_to_htlc.h"
#include "packets.h"
#include "pay.h"
@@ -24,6 +23,7 @@
#include "remove_dust.h"
#include "routing.h"
#include "secrets.h"
#include "sphinx.h"
#include "state.h"
#include "timeout.h"
#include "utils.h"
@@ -46,6 +46,7 @@
#include <inttypes.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sodium/randombytes.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
@@ -199,6 +200,19 @@ struct peer *find_peer(struct lightningd_state *dstate, const struct pubkey *id)
return NULL;
}
struct peer *find_peer_by_pkhash(struct lightningd_state *dstate, const u8 *pkhash)
{
struct peer *peer;
u8 addr[20];
list_for_each(&dstate->peers, peer, list) {
pubkey_hash160(dstate->secpctx, addr, peer->id);
if (memcmp(addr, pkhash, sizeof(addr)) == 0)
return peer;
}
return NULL;
}
void debug_dump_peers(struct lightningd_state *dstate)
{
struct peer *peer;
@@ -438,11 +452,10 @@ static void set_htlc_fail(struct peer *peer,
static void route_htlc_onwards(struct peer *peer,
struct htlc *htlc,
u64 msatoshi,
const BitcoinPubkey *pb_id,
const u8 *pb_id,
const u8 *rest_of_route,
const struct peer *only_dest)
{
struct pubkey id;
struct peer *next;
struct htlc *newhtlc;
enum fail_error error_code;
@@ -454,19 +467,10 @@ static void route_htlc_onwards(struct peer *peer,
log_add(peer->log, " (id %"PRIu64")", htlc->id);
}
if (!proto_to_pubkey(peer->dstate->secpctx, pb_id, &id)) {
log_unusual(peer->log,
"Malformed pubkey for HTLC %"PRIu64, htlc->id);
command_htlc_set_fail(peer, htlc, BAD_REQUEST_400,
"Malformed pubkey");
return;
}
next = find_peer(peer->dstate, &id);
next = find_peer_by_pkhash(peer->dstate, pb_id);
if (!next || !next->nc) {
log_unusual(peer->log, "Can't route HTLC %"PRIu64": no %speer ",
htlc->id, next ? "ready " : "");
log_add_struct(peer->log, "%s", struct pubkey, &id);
if (!peer->dstate->dev_never_routefail)
command_htlc_set_fail(peer, htlc, NOT_FOUND_404,
"Unknown peer");
@@ -505,9 +509,10 @@ static void route_htlc_onwards(struct peer *peer,
static void their_htlc_added(struct peer *peer, struct htlc *htlc,
struct peer *only_dest)
{
RouteStep *step;
const u8 *rest_of_route;
struct invoice *invoice;
struct privkey pk;
struct onionpacket *packet;
struct route_step *step = NULL;
if (abs_locktime_is_seconds(&htlc->expiry)) {
log_unusual(peer->log, "HTLC %"PRIu64" is in seconds", htlc->id);
@@ -536,8 +541,13 @@ static void their_htlc_added(struct peer *peer, struct htlc *htlc,
return;
}
step = onion_unwrap(peer, htlc->routing, tal_count(htlc->routing),
&rest_of_route);
//FIXME: dirty trick to retrieve unexported state
memcpy(&pk, peer->dstate->secret, sizeof(pk));
packet = parse_onionpacket(peer, peer->dstate->secpctx,
htlc->routing, tal_count(htlc->routing));
if (packet)
step = process_onionpacket(peer, peer->dstate->secpctx, packet, &pk);
if (!step) {
log_unusual(peer->log, "Bad onion, failing HTLC %"PRIu64,
htlc->id);
@@ -546,8 +556,8 @@ static void their_htlc_added(struct peer *peer, struct htlc *htlc,
return;
}
switch (step->next_case) {
case ROUTE_STEP__NEXT_END:
switch (step->nextcase) {
case ONION_END:
if (only_dest)
return;
invoice = find_unpaid(peer->dstate, &htlc->rhash);
@@ -584,19 +594,20 @@ static void their_htlc_added(struct peer *peer, struct htlc *htlc,
command_htlc_fulfill(peer, htlc);
goto free_rest;
case ROUTE_STEP__NEXT_BITCOIN:
route_htlc_onwards(peer, htlc, step->amount, step->bitcoin,
rest_of_route, only_dest);
case ONION_FORWARD:
printf("FORWARDING %lu\n", step->hoppayload->amount);
route_htlc_onwards(peer, htlc, step->hoppayload->amount, step->next->nexthop,
serialize_onionpacket(step, peer->dstate->secpctx, step->next), only_dest);
goto free_rest;
default:
log_info(peer->log, "Unknown step type %u", step->next_case);
log_info(peer->log, "Unknown step type %u", step->nextcase);
command_htlc_set_fail(peer, htlc, VERSION_NOT_SUPPORTED_505,
"unknown step type");
goto free_rest;
}
free_rest:
tal_free(rest_of_route);
tal_free(step);
}
static void our_htlc_failed(struct peer *peer, struct htlc *htlc)
@@ -4420,6 +4431,11 @@ static void json_newhtlc(struct command *cmd,
struct htlc *htlc;
const char *err;
enum fail_error error_code;
struct hoppayload *hoppayloads;
u8 sessionkey[32];
struct onionpacket *packet;
u8 *onion;
struct pubkey *path = tal_arrz(cmd, struct pubkey, 1);
if (!json_get_params(buffer, params,
"peerid", &peeridtok,
@@ -4469,10 +4485,20 @@ static void json_newhtlc(struct command *cmd,
return;
}
tal_arr(cmd, struct pubkey, 1);
hoppayloads = tal_arrz(cmd, struct hoppayload, 1);
memcpy(&path[0], peer->id, sizeof(struct pubkey));
randombytes_buf(&sessionkey, sizeof(sessionkey));
packet = create_onionpacket(
cmd,
cmd->dstate->secpctx,
path,
hoppayloads, sessionkey, (u8*)"", 0);
onion = serialize_onionpacket(cmd, cmd->dstate->secpctx, packet);
log_debug(peer->log, "JSON command to add new HTLC");
err = command_htlc_add(peer, msatoshi, expiry, &rhash, NULL,
onion_create(cmd, cmd->dstate->secpctx,
NULL, NULL, 0),
onion,
&error_code, &htlc);
if (err) {
command_fail(cmd, "could not add htlc: %u:%s", error_code, err);

View File

@@ -240,6 +240,7 @@ struct peer_address {
void setup_listeners(struct lightningd_state *dstate, unsigned int portnum);
struct peer *find_peer(struct lightningd_state *dstate, const struct pubkey *id);
struct peer *find_peer_by_pkhash(struct lightningd_state *dstate, const u8 *pkhash);
struct peer *new_peer(struct lightningd_state *dstate,
struct log *log,

526
daemon/sphinx.c Normal file
View File

@@ -0,0 +1,526 @@
#include "sphinx.h"
#include <assert.h>
#include <ccan/crypto/ripemd160/ripemd160.h>
#include <ccan/crypto/sha256/sha256.h>
#include <ccan/mem/mem.h>
#include <err.h>
#include <sodium/crypto_auth_hmacsha256.h>
#include <sodium/crypto_stream_chacha20.h>
#define BLINDING_FACTOR_SIZE 32
#define SHARED_SECRET_SIZE 32
#define NUM_STREAM_BYTES (2 * NUM_MAX_HOPS + 2) * SECURITY_PARAMETER
#define KEY_LEN 32
struct hop_params {
u8 secret[SHARED_SECRET_SIZE];
u8 blind[BLINDING_FACTOR_SIZE];
secp256k1_pubkey ephemeralkey;
};
struct keyset {
u8 pi[KEY_LEN];
u8 mu[KEY_LEN];
u8 rho[KEY_LEN];
u8 gamma[KEY_LEN];
};
/* Small helper to append data to a buffer and update the position
* into the buffer
*/
static void write_buffer(u8 *dst, const void *src, const size_t len, int *pos)
{
memcpy(dst + *pos, src, len);
*pos += len;
}
/* Read len bytes from the source at position pos into dst and update
* the position pos accordingly.
*/
static void read_buffer(void *dst, const u8 *src, const size_t len, int *pos)
{
memcpy(dst, src + *pos, len);
*pos += len;
}
u8 *serialize_onionpacket(
const tal_t *ctx,
const secp256k1_context *secpctx,
const struct onionpacket *m)
{
u8 *dst = tal_arr(ctx, u8, TOTAL_PACKET_SIZE);
u8 der[33];
size_t outputlen = 33;
int p = 0;
secp256k1_ec_pubkey_serialize(secpctx,
der,
&outputlen,
&m->ephemeralkey,
SECP256K1_EC_COMPRESSED);
write_buffer(dst, &m->version, 1, &p);
write_buffer(dst, der, outputlen, &p);
write_buffer(dst, m->mac, sizeof(m->mac), &p);
write_buffer(dst, m->routinginfo, ROUTING_INFO_SIZE, &p);
write_buffer(dst, m->hoppayloads, TOTAL_HOP_PAYLOAD_SIZE, &p);
write_buffer(dst, m->payload, MESSAGE_SIZE, &p);
return dst;
}
struct onionpacket *parse_onionpacket(
const tal_t *ctx,
const secp256k1_context *secpctx,
const void *src,
const size_t srclen
)
{
struct onionpacket *m;
int p = 0;
u8 rawEphemeralkey[33];
if (srclen != TOTAL_PACKET_SIZE)
return NULL;
m = talz(ctx, struct onionpacket);
read_buffer(&m->version, src, 1, &p);
if (m->version != 0x01) {
// FIXME add logging
return NULL;
}
read_buffer(rawEphemeralkey, src, 33, &p);
if (secp256k1_ec_pubkey_parse(secpctx, &m->ephemeralkey, rawEphemeralkey, 33) != 1)
return NULL;
read_buffer(&m->mac, src, 20, &p);
read_buffer(&m->routinginfo, src, ROUTING_INFO_SIZE, &p);
read_buffer(&m->hoppayloads, src, TOTAL_HOP_PAYLOAD_SIZE, &p);
read_buffer(m->payload, src, MESSAGE_SIZE, &p);
return m;
}
static struct hoppayload *parse_hoppayload(const tal_t *ctx, u8 *src)
{
int p = 0;
struct hoppayload *result = talz(ctx, struct hoppayload);
read_buffer(&result->realm, src, sizeof(&result->realm), &p);
read_buffer(&result->amount, src, sizeof(&result->amount), &p);
read_buffer(&result->remainder, src, sizeof(&result->remainder), &p);
return result;
}
static void serialize_hoppayload(u8 *dst, struct hoppayload *hp)
{
int p = 0;
write_buffer(dst, &hp->realm, sizeof(&hp->realm), &p);
write_buffer(dst, &hp->amount, sizeof(&hp->amount), &p);
write_buffer(dst, &hp->remainder, sizeof(&hp->remainder), &p);
}
static void xorbytes(uint8_t *d, const uint8_t *a, const uint8_t *b, size_t len)
{
size_t i = 0;
for (i = 0; i < len; i++)
d[i] = a[i] ^ b[i];
}
/*
* Encrypt a message `m` of length `mlen` with key `key` and store the
* ciphertext in `c`. `c` must be pre-allocated to at least `mlen` bytes.
*/
static void stream_encrypt(void *c, const void *m, const size_t mlen, const u8 *key)
{
u8 nonce[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
memcheck(c, mlen);
crypto_stream_chacha20_xor(c, m, mlen, nonce, key);
}
/*
* Decrypt a ciphertext `c` of length `clen` with key `key` and store the
* cleartext in `m`. `m` must be pre-allocated to at least `clen` bytes.
*/
static void stream_decrypt(void *m, const void *c, const size_t clen, const u8 *key)
{
stream_encrypt(m, c, clen, key);
}
/*
* Generate a pseudo-random byte stream of length `dstlen` from key `k` and
* store it in `dst`. `dst must be at least `dstlen` bytes long.
*/
static void generate_cipher_stream(void *dst, const u8 *k, size_t dstlen)
{
u8 nonce[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
crypto_stream_chacha20(dst, dstlen, nonce, k);
}
static bool compute_hmac(
void *dst,
const void *src,
size_t len,
const void *key,
size_t keylen)
{
crypto_auth_hmacsha256_state state;
crypto_auth_hmacsha256_init(&state, key, keylen);
crypto_auth_hmacsha256_update(&state, memcheck(src, len), len);
crypto_auth_hmacsha256_final(&state, dst);
return true;
}
static void compute_packet_hmac(struct onionpacket *packet, u8 *mukey, u8 *hmac)
{
u8 mactemp[ROUTING_INFO_SIZE + TOTAL_HOP_PAYLOAD_SIZE + MESSAGE_SIZE];
memcpy(mactemp, packet->routinginfo, ROUTING_INFO_SIZE);
memcpy(mactemp + ROUTING_INFO_SIZE, packet->hoppayloads, TOTAL_HOP_PAYLOAD_SIZE);
memcpy(mactemp + ROUTING_INFO_SIZE + TOTAL_HOP_PAYLOAD_SIZE, packet->payload, sizeof(packet->payload));
compute_hmac(hmac, mactemp, sizeof(mactemp), mukey, KEY_LEN);
}
static bool generate_key(void *k, const char *t, u8 tlen, const u8 *s)
{
return compute_hmac(k, s, KEY_LEN, t, tlen);
}
static bool generate_header_padding(
void *dst, size_t dstlen,
const size_t hopsize,
const char *keytype,
size_t keytypelen,
const u8 numhops,
struct hop_params *params
)
{
int i;
u8 cipher_stream[(NUM_MAX_HOPS + 1) * hopsize];
u8 key[KEY_LEN];
memset(dst, 0, dstlen);
for (i = 1; i < numhops; i++) {
if (!generate_key(&key, keytype, keytypelen, params[i - 1].secret))
return false;
generate_cipher_stream(cipher_stream, key, sizeof(cipher_stream));
int pos = ((NUM_MAX_HOPS - i) + 1) * hopsize;
xorbytes(dst, dst, cipher_stream + pos, sizeof(cipher_stream) - pos);
}
return true;
}
static void compute_blinding_factor(secp256k1_context *secpctx,
secp256k1_pubkey *key,
u8 sharedsecret[SHARED_SECRET_SIZE],
u8 res[BLINDING_FACTOR_SIZE])
{
struct sha256_ctx ctx;
u8 der[33];
size_t outputlen = 33;
struct sha256 temp;
secp256k1_ec_pubkey_serialize(secpctx, der, &outputlen, key,
SECP256K1_EC_COMPRESSED);
sha256_init(&ctx);
sha256_update(&ctx, der, sizeof(der));
sha256_update(&ctx, sharedsecret, SHARED_SECRET_SIZE);
sha256_done(&ctx, &temp);
memcpy(res, &temp, 32);
}
static bool blind_group_element(
secp256k1_context *secpctx,
secp256k1_pubkey *blindedelement,
secp256k1_pubkey *pubkey,
u8 blind[BLINDING_FACTOR_SIZE])
{
/* tweak_mul is inplace so copy first. */
if (pubkey != blindedelement)
memcpy(blindedelement, pubkey, sizeof(secp256k1_pubkey));
if (secp256k1_ec_pubkey_tweak_mul(secpctx, blindedelement, blind) != 1)
return false;
return true;
}
static bool create_shared_secret(
secp256k1_context *secpctx,
u8 *secret,
const secp256k1_pubkey *pubkey,
const u8 *sessionkey)
{
/* Need to copy since tweak is in-place */
secp256k1_pubkey pkcopy;
u8 ecres[33];
memcpy(&pkcopy, pubkey, sizeof(pkcopy));
if (secp256k1_ec_pubkey_tweak_mul(secpctx, &pkcopy, sessionkey) != 1)
return false;
/* Serialize and strip first byte, this gives us the X coordinate */
size_t outputlen = 33;
secp256k1_ec_pubkey_serialize(secpctx, ecres, &outputlen,
&pkcopy, SECP256K1_EC_COMPRESSED);
struct sha256 h;
sha256(&h, ecres + 1, sizeof(ecres) - 1);
memcpy(secret, &h, sizeof(h));
return true;
}
void pubkey_hash160(
const secp256k1_context *secpctx,
u8 *dst,
const struct pubkey *pubkey)
{
struct ripemd160 r;
struct sha256 h;
u8 der[33];
size_t outputlen = 33;
secp256k1_ec_pubkey_serialize(secpctx,
der,
&outputlen,
&pubkey->pubkey,
SECP256K1_EC_COMPRESSED);
sha256(&h, der, sizeof(der));
ripemd160(&r, h.u.u8, sizeof(h));
memcpy(dst, r.u.u8, sizeof(r));
}
static void generate_key_set(u8 secret[SHARED_SECRET_SIZE], struct keyset *keys)
{
generate_key(keys->rho, "rho", 3, secret);
generate_key(keys->pi, "pi", 2, secret);
generate_key(keys->mu, "mu", 2, secret);
generate_key(keys->gamma, "gamma", 5, secret);
}
static struct hop_params *generate_hop_params(
const tal_t *ctx,
secp256k1_context *secpctx,
const u8 *sessionkey,
struct pubkey path[])
{
int i, j, num_hops = tal_count(path);
secp256k1_pubkey temp;
u8 blind[BLINDING_FACTOR_SIZE];
struct hop_params *params = tal_arr(ctx, struct hop_params, num_hops);
/* Initialize the first hop with the raw information */
if (secp256k1_ec_pubkey_create(
secpctx, &params[0].ephemeralkey, sessionkey) != 1)
return NULL;
if (!create_shared_secret(
secpctx, params[0].secret, &path[0].pubkey, sessionkey))
return NULL;
compute_blinding_factor(
secpctx, &params[0].ephemeralkey, params[0].secret,
params[0].blind);
/* Recursively compute all following ephemeral public keys,
* secrets and blinding factors
*/
for (i = 1; i < num_hops; i++) {
if (!blind_group_element(
secpctx, &params[i].ephemeralkey,
&params[i - 1].ephemeralkey,
params[i - 1].blind))
return NULL;
/* Blind this hop's point with all previous blinding factors
* Order is indifferent, multiplication is commutative.
*/
memcpy(&blind, sessionkey, 32);
memcpy(&temp, &path[i], sizeof(temp));
if (!blind_group_element(secpctx, &temp, &temp, blind))
return NULL;
for (j = 0; j < i; j++)
if (!blind_group_element(
secpctx,
&temp,
&temp,
params[j].blind))
return NULL;
/* Now hash temp and store it. This requires us to
* DER-serialize first and then skip the sign byte.
*/
u8 der[33];
size_t outputlen = 33;
secp256k1_ec_pubkey_serialize(
secpctx, der, &outputlen, &temp,
SECP256K1_EC_COMPRESSED);
struct sha256 h;
sha256(&h, der + 1, sizeof(der) - 1);
memcpy(&params[i].secret, &h, sizeof(h));
compute_blinding_factor(
secpctx, &params[i].ephemeralkey,
params[i].secret, params[i].blind);
}
return params;
}
struct onionpacket *create_onionpacket(
const tal_t *ctx,
secp256k1_context *secpctx,
struct pubkey *path,
struct hoppayload hoppayloads[],
const u8 *sessionkey,
const u8 *message,
const size_t messagelen
)
{
struct onionpacket *packet = talz(ctx, struct onionpacket);
int i, num_hops = tal_count(path);
u8 filler[2 * (num_hops - 1) * SECURITY_PARAMETER];
u8 hopfiller[(num_hops - 1) * HOP_PAYLOAD_SIZE];
struct keyset keys;
u8 nextaddr[20], nexthmac[SECURITY_PARAMETER];
u8 stream[ROUTING_INFO_SIZE], hopstream[TOTAL_HOP_PAYLOAD_SIZE];
struct hop_params *params = generate_hop_params(ctx, secpctx, sessionkey, path);
u8 binhoppayloads[tal_count(path)][HOP_PAYLOAD_SIZE];
for (i = 0; i < num_hops; i++)
serialize_hoppayload(binhoppayloads[i], &hoppayloads[i]);
if (MESSAGE_SIZE > messagelen) {
memset(&packet->hoppayloads, 0, TOTAL_HOP_PAYLOAD_SIZE);
memset(&packet->payload, 0xFF, MESSAGE_SIZE);
memcpy(&packet->payload, message, messagelen);
packet->payload[messagelen] = 0x7f;
}
if (!params)
return NULL;
packet->version = 1;
memset(nextaddr, 0, 20);
memset(nexthmac, 0, 20);
memset(packet->routinginfo, 0, ROUTING_INFO_SIZE);
generate_header_padding(filler, sizeof(filler), 2 * SECURITY_PARAMETER,
"rho", 3, num_hops, params);
generate_header_padding(hopfiller, sizeof(hopfiller), HOP_PAYLOAD_SIZE,
"gamma", 5, num_hops, params);
for (i = num_hops - 1; i >= 0; i--) {
generate_key_set(params[i].secret, &keys);
generate_cipher_stream(stream, keys.rho, ROUTING_INFO_SIZE);
/* Rightshift mix-header by 2*SECURITY_PARAMETER */
memmove(packet->routinginfo + 2 * SECURITY_PARAMETER, packet->routinginfo,
ROUTING_INFO_SIZE - 2 * SECURITY_PARAMETER);
memcpy(packet->routinginfo, nextaddr, SECURITY_PARAMETER);
memcpy(packet->routinginfo + SECURITY_PARAMETER, nexthmac, SECURITY_PARAMETER);
xorbytes(packet->routinginfo, packet->routinginfo, stream, ROUTING_INFO_SIZE);
/* Rightshift hop-payloads and obfuscate */
memmove(packet->hoppayloads + HOP_PAYLOAD_SIZE, packet->hoppayloads,
TOTAL_HOP_PAYLOAD_SIZE - HOP_PAYLOAD_SIZE);
memcpy(packet->hoppayloads, binhoppayloads[i], HOP_PAYLOAD_SIZE);
generate_cipher_stream(hopstream, keys.gamma, TOTAL_HOP_PAYLOAD_SIZE);
xorbytes(packet->hoppayloads, packet->hoppayloads, hopstream,
TOTAL_HOP_PAYLOAD_SIZE);
if (i == num_hops - 1) {
size_t len = (NUM_MAX_HOPS - num_hops + 1) * 2 * SECURITY_PARAMETER;
memcpy(packet->routinginfo + len, filler, sizeof(filler));
len = (NUM_MAX_HOPS - num_hops + 1) * HOP_PAYLOAD_SIZE;
memcpy(packet->hoppayloads + len, hopfiller, sizeof(hopfiller));
}
/* Obfuscate end-to-end payload */
stream_encrypt(packet->payload, packet->payload, sizeof(packet->payload), keys.pi);
compute_packet_hmac(packet, keys.mu, nexthmac);
pubkey_hash160(secpctx, nextaddr, &path[i]);
}
memcpy(packet->mac, nexthmac, sizeof(nexthmac));
memcpy(&packet->ephemeralkey, &params[0].ephemeralkey, sizeof(secp256k1_pubkey));
return packet;
}
/*
* Given a onionpacket msg extract the information for the current
* node and unwrap the remainder so that the node can forward it.
*/
struct route_step *process_onionpacket(
const tal_t *ctx,
secp256k1_context *secpctx,
struct onionpacket *msg,
struct privkey *hop_privkey
)
{
struct route_step *step = talz(ctx, struct route_step);
u8 secret[SHARED_SECRET_SIZE];
u8 hmac[20];
struct keyset keys;
u8 paddedhoppayloads[TOTAL_HOP_PAYLOAD_SIZE + HOP_PAYLOAD_SIZE];
u8 hopstream[TOTAL_HOP_PAYLOAD_SIZE + HOP_PAYLOAD_SIZE];
u8 blind[BLINDING_FACTOR_SIZE];
u8 stream[NUM_STREAM_BYTES];
u8 paddedheader[ROUTING_INFO_SIZE + 2 * SECURITY_PARAMETER];
step->next = talz(ctx, struct onionpacket);
step->next->version = msg->version;
create_shared_secret(secpctx, secret, &msg->ephemeralkey, hop_privkey->secret);
generate_key_set(secret, &keys);
compute_packet_hmac(msg, keys.mu, hmac);
if (memcmp(msg->mac, hmac, sizeof(hmac)) != 0) {
warnx("Computed MAC does not match expected MAC, the message was modified.");
return NULL;
}
//FIXME:store seen secrets to avoid replay attacks
generate_cipher_stream(stream, keys.rho, sizeof(stream));
memset(paddedheader, 0, sizeof(paddedheader));
memcpy(paddedheader, msg->routinginfo, ROUTING_INFO_SIZE);
xorbytes(paddedheader, paddedheader, stream, sizeof(stream));
/* Extract the per-hop payload */
generate_cipher_stream(hopstream, keys.gamma, sizeof(hopstream));
memset(paddedhoppayloads, 0, sizeof(paddedhoppayloads));
memcpy(paddedhoppayloads, msg->hoppayloads, TOTAL_HOP_PAYLOAD_SIZE);
xorbytes(paddedhoppayloads, paddedhoppayloads, hopstream, sizeof(hopstream));
step->hoppayload = parse_hoppayload(step, paddedhoppayloads);
memcpy(&step->next->hoppayloads, paddedhoppayloads + HOP_PAYLOAD_SIZE,
TOTAL_HOP_PAYLOAD_SIZE);
compute_blinding_factor(secpctx, &msg->ephemeralkey, secret, blind);
if (!blind_group_element(secpctx, &step->next->ephemeralkey, &msg->ephemeralkey, blind))
return NULL;
memcpy(&step->next->nexthop, paddedheader, SECURITY_PARAMETER);
memcpy(&step->next->mac,
paddedheader + SECURITY_PARAMETER,
SECURITY_PARAMETER);
stream_decrypt(step->next->payload, msg->payload, sizeof(msg->payload), keys.pi);
memcpy(&step->next->routinginfo, paddedheader + 2 * SECURITY_PARAMETER, ROUTING_INFO_SIZE);
if (memeqzero(step->next->mac, sizeof(&step->next->mac))) {
step->nextcase = ONION_END;
} else {
step->nextcase = ONION_FORWARD;
}
return step;
}

126
daemon/sphinx.h Normal file
View File

@@ -0,0 +1,126 @@
#ifndef LIGHTNING_DAEMON_SPHINX_H
#define LIGHTNING_DAEMON_SPHINX_H
#include "config.h"
#include "bitcoin/privkey.h"
#include "bitcoin/pubkey.h"
#include <ccan/short_types/short_types.h>
#include <ccan/tal/tal.h>
#include <secp256k1.h>
#include <sodium/randombytes.h>
#define SECURITY_PARAMETER 20
#define NUM_MAX_HOPS 20
#define HOP_PAYLOAD_SIZE 20
#define TOTAL_HOP_PAYLOAD_SIZE NUM_MAX_HOPS * HOP_PAYLOAD_SIZE
#define MESSAGE_SIZE 0
#define ROUTING_INFO_SIZE 2 * NUM_MAX_HOPS * SECURITY_PARAMETER
#define TOTAL_PACKET_SIZE 1 + 33 + SECURITY_PARAMETER + ROUTING_INFO_SIZE + \
TOTAL_HOP_PAYLOAD_SIZE + MESSAGE_SIZE
struct onionpacket {
/* Cleartext information */
u8 version;
u8 nexthop[20];
u8 mac[20];
secp256k1_pubkey ephemeralkey;
/* Encrypted information */
u8 routinginfo[ROUTING_INFO_SIZE];
u8 hoppayloads[TOTAL_HOP_PAYLOAD_SIZE];
u8 payload[MESSAGE_SIZE];
};
enum route_next_case {
ONION_END = 0,
ONION_FORWARD = 1,
};
struct hoppayload {
u8 realm;
u64 amount;
u8 remainder[11];
};
struct route_step {
enum route_next_case nextcase;
struct onionpacket *next;
u8 *payload;
struct hoppayload *hoppayload;
};
/**
* create_onionpacket - Create a new onionpacket that can be routed
* over a path of intermediate nodes.
*
* @ctx: tal context to allocate from
* @secpctx: the secp256k1_context for EC operations
* @path: public keys of nodes along the path.
* @hoppayloads: payloads destined for individual hosts (limited to
* HOP_PAYLOAD_SIZE bytes)
* @num_hops: path length in nodes
* @sessionkey: 20 byte random session key to derive secrets from
* @message: end-to-end payload destined for the final recipient
* @messagelen: length of @message
*/
struct onionpacket *create_onionpacket(
const tal_t * ctx,
secp256k1_context * secpctx,
struct pubkey path[],
struct hoppayload hoppayloads[],
const u8 * sessionkey,
const u8 * message,
const size_t messagelen
);
/**
* process_onionpacket - process an incoming packet by stripping one
* onion layer and return the packet for the next hop.
*
* @ctx: tal context to allocate from
* @secpctx: the secp256k1_context for EC operations
* @packet: incoming packet being processed
* @hop_privkey: the processing node's private key to decrypt the packet
* @hoppayload: the per-hop payload destined for the processing node.
*/
struct route_step *process_onionpacket(
const tal_t * ctx,
secp256k1_context * secpctx,
struct onionpacket *packet,
struct privkey *hop_privkey
);
/**
* serialize_onionpacket - Serialize an onionpacket to a buffer.
*
* @ctx: tal context to allocate from
* @secpctx: the secp256k1_context for EC operations
* @packet: the packet to serialize
*/
u8 *serialize_onionpacket(
const tal_t *ctx,
const secp256k1_context *secpctx,
const struct onionpacket *packet);
/**
* parese_onionpacket - Parse an onionpacket from a buffer.
*
* @ctx: tal context to allocate from
* @secpctx: the secp256k1_context for EC operations
* @src: buffer to read the packet from
* @srclen: length of the @src
*/
struct onionpacket *parse_onionpacket(
const tal_t *ctx,
const secp256k1_context *secpctx,
const void *src,
const size_t srclen
);
void pubkey_hash160(
const secp256k1_context *secpctx,
u8 *dst,
const struct pubkey *pubkey);
#endif /* LIGHTNING_DAEMON_SPHINX_H */