Browse Source

lightningd: remove lightningd_state.

Some fields were redundant, some are simply moved into 'struct lightningd'.
All routines updated to hand 'struct lightningd *ld' now.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
ppa-0.6.1
Rusty Russell 8 years ago
committed by Christian Decker
parent
commit
153c622157
  1. 2
      lightningd/bitcoind.h
  2. 14
      lightningd/chaintopology.c
  3. 4
      lightningd/chaintopology.h
  4. 3
      lightningd/dev_ping.c
  5. 42
      lightningd/dns.c
  6. 22
      lightningd/dns.h
  7. 2
      lightningd/gossip/routing.h
  8. 14
      lightningd/gossip_control.c
  9. 8
      lightningd/hsm_control.c
  10. 26
      lightningd/invoice.c
  11. 4
      lightningd/invoice.h
  12. 47
      lightningd/jsonrpc.c
  13. 6
      lightningd/jsonrpc.h
  14. 72
      lightningd/lightningd.c
  15. 96
      lightningd/lightningd.h
  16. 1
      lightningd/log.h
  17. 9
      lightningd/new_connection.c
  18. 3
      lightningd/new_connection.h
  19. 140
      lightningd/options.c
  20. 6
      lightningd/options.h
  21. 23
      lightningd/pay.c
  22. 92
      lightningd/peer_control.c
  23. 22
      lightningd/peer_htlcs.c
  24. 2
      lightningd/subd.c
  25. 1
      lightningd/watch.h
  26. 32
      wallet/walletrpc.c

2
lightningd/bitcoind.h

@ -9,7 +9,7 @@
#include <stdbool.h> #include <stdbool.h>
struct sha256_double; struct sha256_double;
struct lightningd_state; struct lightningd;
struct ripemd160; struct ripemd160;
struct bitcoin_tx; struct bitcoin_tx;
struct peer; struct peer;

14
lightningd/chaintopology.c

@ -503,13 +503,13 @@ void json_dev_broadcast(struct command *cmd,
return; return;
} }
log_debug(cmd->dstate->base_log, "dev-broadcast: broadcast %s", log_debug(cmd->ld->log, "dev-broadcast: broadcast %s",
enable ? "enabled" : "disabled"); enable ? "enabled" : "disabled");
cmd->dstate->topology->dev_no_broadcast = !enable; cmd->ld->topology->dev_no_broadcast = !enable;
/* If enabling, flush and wait. */ /* If enabling, flush and wait. */
if (enable) if (enable)
rebroadcast_txs(cmd->dstate->topology, cmd); rebroadcast_txs(cmd->ld->topology, cmd);
else else
command_success(cmd, null_response(cmd)); command_success(cmd, null_response(cmd));
} }
@ -517,7 +517,7 @@ void json_dev_broadcast(struct command *cmd,
static void json_dev_blockheight(struct command *cmd, static void json_dev_blockheight(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct chain_topology *topo = cmd->dstate->topology; struct chain_topology *topo = cmd->ld->topology;
struct json_result *response; struct json_result *response;
response = new_json_result(cmd); response = new_json_result(cmd);
@ -557,22 +557,22 @@ struct chain_topology *new_topology(const tal_t *ctx, struct log *log)
topo->default_fee_rate = 40000; topo->default_fee_rate = 40000;
topo->override_fee_rate = 0; topo->override_fee_rate = 0;
topo->dev_no_broadcast = false; topo->dev_no_broadcast = false;
topo->bitcoind = new_bitcoind(topo, log);
return topo; return topo;
} }
void setup_topology(struct chain_topology *topo, struct bitcoind *bitcoind, void setup_topology(struct chain_topology *topo,
struct timers *timers, struct timers *timers,
struct timerel poll_time, u32 first_peer_block) struct timerel poll_time, u32 first_peer_block)
{ {
topo->startup = true; topo->startup = true;
topo->feerate = 0; topo->feerate = 0;
topo->timers = timers; topo->timers = timers;
topo->bitcoind = bitcoind;
topo->poll_time = poll_time; topo->poll_time = poll_time;
topo->first_blocknum = first_peer_block; topo->first_blocknum = first_peer_block;
bitcoind_getblockcount(bitcoind, get_init_blockhash, topo); bitcoind_getblockcount(topo->bitcoind, get_init_blockhash, topo);
tal_add_destructor(topo, destroy_outgoing_txs); tal_add_destructor(topo, destroy_outgoing_txs);

4
lightningd/chaintopology.h

@ -14,7 +14,7 @@
struct bitcoin_tx; struct bitcoin_tx;
struct bitcoind; struct bitcoind;
struct command; struct command;
struct lightningd_state; struct lightningd;
struct peer; struct peer;
struct sha256_double; struct sha256_double;
struct txwatch; struct txwatch;
@ -148,7 +148,7 @@ void broadcast_tx(struct chain_topology *topo,
const char *err)); const char *err));
struct chain_topology *new_topology(const tal_t *ctx, struct log *log); struct chain_topology *new_topology(const tal_t *ctx, struct log *log);
void setup_topology(struct chain_topology *topology, struct bitcoind *bitcoind, void setup_topology(struct chain_topology *topology,
struct timers *timers, struct timers *timers,
struct timerel poll_time, u32 first_peer_block); struct timerel poll_time, u32 first_peer_block);

3
lightningd/dev_ping.c

@ -37,7 +37,6 @@ static bool ping_reply(struct subd *subd, const u8 *msg, const int *fds,
static void json_dev_ping(struct command *cmd, static void json_dev_ping(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct peer *peer; struct peer *peer;
u8 *msg; u8 *msg;
jsmntok_t *peeridtok, *lentok, *pongbytestok; jsmntok_t *peeridtok, *lentok, *pongbytestok;
@ -52,7 +51,7 @@ static void json_dev_ping(struct command *cmd,
return; return;
} }
peer = peer_from_json(ld, buffer, peeridtok); peer = peer_from_json(cmd->ld, buffer, peeridtok);
if (!peer) { if (!peer) {
command_fail(cmd, "Could not find peer with that peerid"); command_fail(cmd, "Could not find peer with that peerid");
return; return;

42
lightningd/dns.c

@ -16,11 +16,11 @@
#include <sys/wait.h> #include <sys/wait.h>
struct dns_async { struct dns_async {
struct lightningd_state *dstate; struct lightningd *ld;
struct io_plan *(*init)(struct io_conn *, struct lightningd_state *, struct io_plan *(*init)(struct io_conn *, struct lightningd *,
const struct netaddr *, const struct netaddr *,
void *); void *);
void (*fail)(struct lightningd_state *, void *arg); void (*fail)(struct lightningd *, void *arg);
const char *name; const char *name;
void *arg; void *arg;
int pid; int pid;
@ -77,7 +77,7 @@ static struct io_plan *connected(struct io_conn *conn, struct dns_async *d)
/* No longer need to try more connections via connect_failed. */ /* No longer need to try more connections via connect_failed. */
io_set_finish(conn, NULL, NULL); io_set_finish(conn, NULL, NULL);
plan = d->init(conn, d->dstate, &d->addresses[-1], d->arg); plan = d->init(conn, d->ld, &d->addresses[-1], d->arg);
tal_free(d); tal_free(d);
return plan; return plan;
@ -116,7 +116,7 @@ static void try_connect_one(struct dns_async *d)
/* Now we can warn if it's overlength */ /* Now we can warn if it's overlength */
if (a->addrlen > sizeof(a->saddr)) { if (a->addrlen > sizeof(a->saddr)) {
log_broken(d->dstate->base_log, log_broken(d->ld->log,
"DNS lookup gave overlength address for %s" "DNS lookup gave overlength address for %s"
" for family %u, len=%u", " for family %u, len=%u",
d->name, a->saddr.s.sa_family, a->addrlen); d->name, a->saddr.s.sa_family, a->addrlen);
@ -124,7 +124,7 @@ static void try_connect_one(struct dns_async *d)
/* Might not even be able to create eg. IPv6 sockets */ /* Might not even be able to create eg. IPv6 sockets */
fd = socket(a->saddr.s.sa_family, a->type, a->protocol); fd = socket(a->saddr.s.sa_family, a->type, a->protocol);
if (fd >= 0) { if (fd >= 0) {
io_new_conn(d->dstate, fd, init_conn, d); io_new_conn(d->ld, fd, init_conn, d);
return; return;
} }
} }
@ -135,7 +135,7 @@ static void try_connect_one(struct dns_async *d)
} }
/* We're out of things to try. Fail. */ /* We're out of things to try. Fail. */
d->fail(d->dstate, d->arg); d->fail(d->ld, d->arg);
tal_free(d); tal_free(d);
} }
@ -154,18 +154,18 @@ static struct io_plan *start_connecting(struct io_conn *conn,
return io_close(conn); return io_close(conn);
} }
struct dns_async *multiaddress_connect_(struct lightningd_state *dstate, struct dns_async *multiaddress_connect_(struct lightningd *ld,
const struct netaddr *addresses, const struct netaddr *addresses,
struct io_plan *(*init)(struct io_conn *, struct io_plan *(*init)(struct io_conn *,
struct lightningd_state *, struct lightningd *,
const struct netaddr *, const struct netaddr *,
void *arg), void *arg),
void (*fail)(struct lightningd_state *, void *arg), void (*fail)(struct lightningd *, void *arg),
void *arg) void *arg)
{ {
struct dns_async *d = tal(dstate, struct dns_async); struct dns_async *d = tal(ld, struct dns_async);
d->dstate = dstate; d->ld = ld;
d->init = init; d->init = init;
d->fail = fail; d->fail = fail;
d->arg = arg; d->arg = arg;
@ -194,24 +194,24 @@ static struct io_plan *init_dns_conn(struct io_conn *conn, struct dns_async *d)
static void dns_lookup_failed(struct io_conn *conn, struct dns_async *d) static void dns_lookup_failed(struct io_conn *conn, struct dns_async *d)
{ {
waitpid(d->pid, NULL, 0); waitpid(d->pid, NULL, 0);
d->fail(d->dstate, d->arg); d->fail(d->ld, d->arg);
tal_free(d); tal_free(d);
} }
struct dns_async *dns_resolve_and_connect_(struct lightningd_state *dstate, struct dns_async *dns_resolve_and_connect_(struct lightningd *ld,
const char *name, const char *port, const char *name, const char *port,
struct io_plan *(*init)(struct io_conn *, struct io_plan *(*init)(struct io_conn *,
struct lightningd_state *, struct lightningd *,
const struct netaddr *, const struct netaddr *,
void *arg), void *arg),
void (*fail)(struct lightningd_state *, void *arg), void (*fail)(struct lightningd *, void *arg),
void *arg) void *arg)
{ {
int pfds[2]; int pfds[2];
struct dns_async *d = tal(dstate, struct dns_async); struct dns_async *d = tal(ld, struct dns_async);
struct io_conn *conn; struct io_conn *conn;
d->dstate = dstate; d->ld = ld;
d->init = init; d->init = init;
d->fail = fail; d->fail = fail;
d->arg = arg; d->arg = arg;
@ -219,7 +219,7 @@ struct dns_async *dns_resolve_and_connect_(struct lightningd_state *dstate,
/* First fork child to get addresses. */ /* First fork child to get addresses. */
if (pipe(pfds) != 0) { if (pipe(pfds) != 0) {
log_unusual(dstate->base_log, log_unusual(ld->log,
"Creating pipes for dns lookup: %s", "Creating pipes for dns lookup: %s",
strerror(errno)); strerror(errno));
return NULL; return NULL;
@ -229,7 +229,7 @@ struct dns_async *dns_resolve_and_connect_(struct lightningd_state *dstate,
d->pid = fork(); d->pid = fork();
switch (d->pid) { switch (d->pid) {
case -1: case -1:
log_unusual(dstate->base_log, "forking for dns lookup: %s", log_unusual(ld->log, "forking for dns lookup: %s",
strerror(errno)); strerror(errno));
close(pfds[0]); close(pfds[0]);
close(pfds[1]); close(pfds[1]);
@ -241,7 +241,7 @@ struct dns_async *dns_resolve_and_connect_(struct lightningd_state *dstate,
} }
close(pfds[1]); close(pfds[1]);
conn = io_new_conn(dstate, pfds[0], init_dns_conn, d); conn = io_new_conn(ld, pfds[0], init_dns_conn, d);
io_set_finish(conn, dns_lookup_failed, d); io_set_finish(conn, dns_lookup_failed, d);
return d; return d;
} }

22
lightningd/dns.h

@ -6,7 +6,7 @@
#include <ccan/typesafe_cb/typesafe_cb.h> #include <ccan/typesafe_cb/typesafe_cb.h>
#include <stdbool.h> #include <stdbool.h>
struct lightningd_state; struct lightningd;
struct netaddr; struct netaddr;
#define dns_resolve_and_connect(dstate, name, port, initfn, failfn, arg) \ #define dns_resolve_and_connect(dstate, name, port, initfn, failfn, arg) \
@ -14,19 +14,19 @@ struct netaddr;
typesafe_cb_preargs(struct io_plan *, void *, \ typesafe_cb_preargs(struct io_plan *, void *, \
(initfn), (arg), \ (initfn), (arg), \
struct io_conn *, \ struct io_conn *, \
struct lightningd_state *, \ struct lightningd *, \
const struct netaddr *), \ const struct netaddr *), \
typesafe_cb_preargs(void, void *, (failfn), (arg), \ typesafe_cb_preargs(void, void *, (failfn), (arg), \
struct lightningd_state *), \ struct lightningd *), \
(arg)) (arg))
struct dns_async *dns_resolve_and_connect_(struct lightningd_state *dstate, struct dns_async *dns_resolve_and_connect_(struct lightningd *ld,
const char *name, const char *port, const char *name, const char *port,
struct io_plan *(*init)(struct io_conn *, struct io_plan *(*init)(struct io_conn *,
struct lightningd_state *, struct lightningd *,
const struct netaddr *, const struct netaddr *,
void *arg), void *arg),
void (*fail)(struct lightningd_state *, void *arg), void (*fail)(struct lightningd *, void *arg),
void *arg); void *arg);
/* Don't do lookup, just try to connect to these addresses. */ /* Don't do lookup, just try to connect to these addresses. */
@ -35,19 +35,19 @@ struct dns_async *dns_resolve_and_connect_(struct lightningd_state *dstate,
typesafe_cb_preargs(struct io_plan *, void *, \ typesafe_cb_preargs(struct io_plan *, void *, \
(initfn), (arg), \ (initfn), (arg), \
struct io_conn *, \ struct io_conn *, \
struct lightningd_state *, \ struct lightningd *, \
const struct netaddr *), \ const struct netaddr *), \
typesafe_cb_preargs(void, void *, (failfn), (arg), \ typesafe_cb_preargs(void, void *, (failfn), (arg), \
struct lightningd_state *), \ struct lightningd *), \
(arg)) (arg))
struct dns_async *multiaddress_connect_(struct lightningd_state *dstate, struct dns_async *multiaddress_connect_(struct lightningd *ld,
const struct netaddr *addresses, const struct netaddr *addresses,
struct io_plan *(*init)(struct io_conn *, struct io_plan *(*init)(struct io_conn *,
struct lightningd_state *, struct lightningd *,
const struct netaddr *, const struct netaddr *,
void *arg), void *arg),
void (*fail)(struct lightningd_state *, void *arg), void (*fail)(struct lightningd *, void *arg),
void *arg); void *arg);
#endif /* LIGHTNING_LIGHTNINGD_DNS_H */ #endif /* LIGHTNING_LIGHTNINGD_DNS_H */

2
lightningd/gossip/routing.h

@ -77,8 +77,6 @@ size_t node_map_hash_key(const secp256k1_pubkey *key);
bool node_map_node_eq(const struct node *n, const secp256k1_pubkey *key); bool node_map_node_eq(const struct node *n, const secp256k1_pubkey *key);
HTABLE_DEFINE_TYPE(struct node, node_map_keyof_node, node_map_hash_key, node_map_node_eq, node_map); HTABLE_DEFINE_TYPE(struct node, node_map_keyof_node, node_map_hash_key, node_map_node_eq, node_map);
struct lightningd_state;
struct routing_state { struct routing_state {
/* All known nodes. */ /* All known nodes. */
struct node_map *nodes; struct node_map *nodes;

14
lightningd/gossip_control.c

@ -151,7 +151,7 @@ void gossip_init(struct lightningd *ld)
err(1, "Could not subdaemon gossip"); err(1, "Could not subdaemon gossip");
init = towire_gossipctl_init(tmpctx, ld->broadcast_interval, init = towire_gossipctl_init(tmpctx, ld->broadcast_interval,
&ld->chainparams->genesis_blockhash); &get_chainparams(ld)->genesis_blockhash);
subd_send_msg(ld->gossip, init); subd_send_msg(ld->gossip, init);
tal_free(tmpctx); tal_free(tmpctx);
} }
@ -191,9 +191,8 @@ static bool json_getnodes_reply(struct subd *gossip, const u8 *reply,
static void json_getnodes(struct command *cmd, const char *buffer, static void json_getnodes(struct command *cmd, const char *buffer,
const jsmntok_t *params) const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
u8 *req = towire_gossip_getnodes_request(cmd); u8 *req = towire_gossip_getnodes_request(cmd);
subd_req(cmd, ld->gossip, req, -1, 0, json_getnodes_reply, cmd); subd_req(cmd, cmd->ld->gossip, req, -1, 0, json_getnodes_reply, cmd);
} }
static const struct json_command getnodes_command = { static const struct json_command getnodes_command = {
@ -239,7 +238,8 @@ static void json_getroute(struct command *cmd, const char *buffer, const jsmntok
jsmntok_t *idtok, *msatoshitok, *riskfactortok; jsmntok_t *idtok, *msatoshitok, *riskfactortok;
u64 msatoshi; u64 msatoshi;
double riskfactor; double riskfactor;
struct lightningd *ld = ld_from_dstate(cmd->dstate); struct lightningd *ld = cmd->ld;
if (!json_get_params(buffer, params, if (!json_get_params(buffer, params,
"id", &idtok, "id", &idtok,
"msatoshi", &msatoshitok, "msatoshi", &msatoshitok,
@ -268,7 +268,7 @@ static void json_getroute(struct command *cmd, const char *buffer, const jsmntok
buffer + riskfactortok->start); buffer + riskfactortok->start);
return; return;
} }
u8 *req = towire_gossip_getroute_request(cmd, &cmd->dstate->id, &id, msatoshi, riskfactor*1000); u8 *req = towire_gossip_getroute_request(cmd, &ld->id, &id, msatoshi, riskfactor*1000);
subd_req(ld->gossip, ld->gossip, req, -1, 0, json_getroute_reply, cmd); subd_req(ld->gossip, ld->gossip, req, -1, 0, json_getroute_reply, cmd);
} }
@ -322,9 +322,9 @@ static bool json_getchannels_reply(struct subd *gossip, const u8 *reply,
static void json_getchannels(struct command *cmd, const char *buffer, static void json_getchannels(struct command *cmd, const char *buffer,
const jsmntok_t *params) const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
u8 *req = towire_gossip_getchannels_request(cmd); u8 *req = towire_gossip_getchannels_request(cmd);
subd_req(ld->gossip, ld->gossip, req, -1, 0, json_getchannels_reply, cmd); subd_req(cmd->ld->gossip, cmd->ld->gossip,
req, -1, 0, json_getchannels_reply, cmd);
} }
static const struct json_command getchannels_command = { static const struct json_command getchannels_command = {

8
lightningd/hsm_control.c

@ -48,15 +48,13 @@ void hsm_init(struct lightningd *ld, bool newdir)
if (!wire_sync_write(ld->hsm_fd, towire_hsmctl_init(tmpctx, create))) if (!wire_sync_write(ld->hsm_fd, towire_hsmctl_init(tmpctx, create)))
err(1, "Writing init msg to hsm"); err(1, "Writing init msg to hsm");
ld->bip32_base = tal(ld, struct ext_key); ld->wallet->bip32_base = tal(ld->wallet, struct ext_key);
msg = hsm_sync_read(tmpctx, ld); msg = hsm_sync_read(tmpctx, ld);
if (!fromwire_hsmctl_init_reply(msg, NULL, if (!fromwire_hsmctl_init_reply(msg, NULL,
&ld->dstate.id, &ld->id,
&ld->peer_seed, &ld->peer_seed,
ld->bip32_base)) ld->wallet->bip32_base))
errx(1, "HSM did not give init reply"); errx(1, "HSM did not give init reply");
/* FIXME... */
ld->wallet->bip32_base = ld->bip32_base;
tal_free(tmpctx); tal_free(tmpctx);
} }

26
lightningd/invoice.c

@ -102,18 +102,18 @@ static void tell_waiter(struct command *cmd, const struct invoice *paid)
} }
/* UNIFICATION FIXME */ /* UNIFICATION FIXME */
void db_resolve_invoice(struct lightningd_state *dstate, void db_resolve_invoice(struct lightningd *ld,
const char *label, u64 paid_num); const char *label, u64 paid_num);
bool db_new_invoice(struct lightningd_state *dstate, bool db_new_invoice(struct lightningd *ld,
u64 msatoshi, u64 msatoshi,
const char *label, const char *label,
const struct preimage *r); const struct preimage *r);
bool db_remove_invoice(struct lightningd_state *dstate, const char *label); bool db_remove_invoice(struct lightningd *ld, const char *label);
void resolve_invoice(struct lightningd_state *dstate, struct invoice *invoice) void resolve_invoice(struct lightningd *ld, struct invoice *invoice)
{ {
struct invoice_waiter *w; struct invoice_waiter *w;
struct invoices *invs = dstate->invoices; struct invoices *invs = ld->invoices;
invoice->paid_num = ++invs->invoices_completed; invoice->paid_num = ++invs->invoices_completed;
list_del_from(&invs->unpaid, &invoice->list); list_del_from(&invs->unpaid, &invoice->list);
@ -125,7 +125,7 @@ void resolve_invoice(struct lightningd_state *dstate, struct invoice *invoice)
list)) != NULL) list)) != NULL)
tell_waiter(w->cmd, invoice); tell_waiter(w->cmd, invoice);
db_resolve_invoice(dstate, invoice->label, invoice->paid_num); db_resolve_invoice(ld, invoice->label, invoice->paid_num);
} }
static void json_invoice(struct command *cmd, static void json_invoice(struct command *cmd,
@ -134,7 +134,7 @@ static void json_invoice(struct command *cmd,
struct invoice *invoice; struct invoice *invoice;
jsmntok_t *msatoshi, *r, *label; jsmntok_t *msatoshi, *r, *label;
struct json_result *response = new_json_result(cmd); struct json_result *response = new_json_result(cmd);
struct invoices *invs = cmd->dstate->invoices; struct invoices *invs = cmd->ld->invoices;
if (!json_get_params(buffer, params, if (!json_get_params(buffer, params,
"amount", &msatoshi, "amount", &msatoshi,
@ -187,7 +187,7 @@ static void json_invoice(struct command *cmd,
} }
invoice->paid_num = 0; invoice->paid_num = 0;
if (!db_new_invoice(cmd->dstate, invoice->msatoshi, invoice->label, if (!db_new_invoice(cmd->ld, invoice->msatoshi, invoice->label,
&invoice->r)) { &invoice->r)) {
command_fail(cmd, "database error"); command_fail(cmd, "database error");
return; return;
@ -238,7 +238,7 @@ static void json_listinvoice(struct command *cmd,
{ {
jsmntok_t *label = NULL; jsmntok_t *label = NULL;
struct json_result *response = new_json_result(cmd); struct json_result *response = new_json_result(cmd);
struct invoices *invs = cmd->dstate->invoices; struct invoices *invs = cmd->ld->invoices;
if (!json_get_params(buffer, params, if (!json_get_params(buffer, params,
"?label", &label, "?label", &label,
@ -270,7 +270,7 @@ static void json_delinvoice(struct command *cmd,
jsmntok_t *labeltok; jsmntok_t *labeltok;
struct json_result *response = new_json_result(cmd); struct json_result *response = new_json_result(cmd);
const char *label; const char *label;
struct invoices *invs = cmd->dstate->invoices; struct invoices *invs = cmd->ld->invoices;
if (!json_get_params(buffer, params, if (!json_get_params(buffer, params,
"label", &labeltok, "label", &labeltok,
@ -286,7 +286,7 @@ static void json_delinvoice(struct command *cmd,
command_fail(cmd, "Unknown invoice"); command_fail(cmd, "Unknown invoice");
return; return;
} }
if (!db_remove_invoice(cmd->dstate, i->label)) { if (!db_remove_invoice(cmd->ld, i->label)) {
command_fail(cmd, "Database error"); command_fail(cmd, "Database error");
return; return;
} }
@ -316,7 +316,7 @@ static void json_waitanyinvoice(struct command *cmd,
jsmntok_t *labeltok; jsmntok_t *labeltok;
const char *label = NULL; const char *label = NULL;
struct invoice_waiter *w; struct invoice_waiter *w;
struct invoices *invs = cmd->dstate->invoices; struct invoices *invs = cmd->ld->invoices;
if (!json_get_params(buffer, params, if (!json_get_params(buffer, params,
"?label", &labeltok, "?label", &labeltok,
@ -372,7 +372,7 @@ static void json_waitinvoice(struct command *cmd,
jsmntok_t *labeltok; jsmntok_t *labeltok;
const char *label = NULL; const char *label = NULL;
struct invoice_waiter *w; struct invoice_waiter *w;
struct invoices *invs = cmd->dstate->invoices; struct invoices *invs = cmd->ld->invoices;
if (!json_get_params(buffer, params, "label", &labeltok, NULL)) { if (!json_get_params(buffer, params, "label", &labeltok, NULL)) {
command_fail(cmd, "Missing {label}"); command_fail(cmd, "Missing {label}");

4
lightningd/invoice.h

@ -7,7 +7,7 @@
#include <ccan/tal/tal.h> #include <ccan/tal/tal.h>
struct invoices; struct invoices;
struct lightningd_state; struct lightningd;
struct invoice { struct invoice {
struct list_node list; struct list_node list;
@ -27,7 +27,7 @@ void invoice_add(struct invoices *i,
const char *label, const char *label,
u64 complete); u64 complete);
void resolve_invoice(struct lightningd_state *dstate, struct invoice *invoice); void resolve_invoice(struct lightningd *ld, struct invoice *invoice);
struct invoice *find_unpaid(struct invoices *i, struct invoice *find_unpaid(struct invoices *i,
const struct sha256 *rhash); const struct sha256 *rhash);

47
lightningd/jsonrpc.c

@ -136,7 +136,7 @@ static void json_getlog(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct log_info info; struct log_info info;
struct log_book *lr = cmd->dstate->log_book; struct log_book *lr = cmd->ld->log_book;
jsmntok_t *level; jsmntok_t *level;
json_get_params(buffer, params, "?level", &level, NULL); json_get_params(buffer, params, "?level", &level, NULL);
@ -237,15 +237,14 @@ static void json_getinfo(struct command *cmd,
struct json_result *response = new_json_result(cmd); struct json_result *response = new_json_result(cmd);
json_object_start(response, NULL); json_object_start(response, NULL);
json_add_pubkey(response, "id", &cmd->dstate->id); json_add_pubkey(response, "id", &cmd->ld->id);
/* FIXME: Keep netaddrs and list them all. */ /* FIXME: Keep netaddrs and list them all. */
if (cmd->dstate->portnum) if (cmd->ld->portnum)
json_add_num(response, "port", cmd->dstate->portnum); json_add_num(response, "port", cmd->ld->portnum);
json_add_string(response, "network", json_add_string(response, "network",
ld_from_dstate(cmd->dstate)->chainparams->network_name); get_chainparams(cmd->ld)->network_name);
json_add_string(response, "version", version()); json_add_string(response, "version", version());
json_add_num(response, "blockheight", json_add_num(response, "blockheight", get_block_height(cmd->ld->topology));
get_block_height(cmd->dstate->topology));
json_object_end(response); json_object_end(response);
command_success(cmd, response); command_success(cmd, response);
} }
@ -377,7 +376,7 @@ void command_success(struct command *cmd, struct json_result *result)
struct json_connection *jcon = cmd->jcon; struct json_connection *jcon = cmd->jcon;
if (!jcon) { if (!jcon) {
log_unusual(cmd->dstate->base_log, log_unusual(cmd->ld->log,
"Command returned result after jcon close"); "Command returned result after jcon close");
tal_free(cmd); tal_free(cmd);
return; return;
@ -395,7 +394,7 @@ void command_fail(struct command *cmd, const char *fmt, ...)
va_list ap; va_list ap;
if (!jcon) { if (!jcon) {
log_unusual(cmd->dstate->base_log, log_unusual(cmd->ld->log,
"Command failed after jcon close"); "Command failed after jcon close");
tal_free(cmd); tal_free(cmd);
return; return;
@ -454,9 +453,9 @@ static void parse_request(struct json_connection *jcon, const jsmntok_t tok[])
/* This is a convenient tal parent for durarion of command /* This is a convenient tal parent for durarion of command
* (which may outlive the conn!). */ * (which may outlive the conn!). */
jcon->current = tal(jcon->dstate, struct command); jcon->current = tal(jcon->ld, struct command);
jcon->current->jcon = jcon; jcon->current->jcon = jcon;
jcon->current->dstate = jcon->dstate; jcon->current->ld = jcon->ld;
jcon->current->id = tal_strndup(jcon->current, jcon->current->id = tal_strndup(jcon->current,
json_tok_contents(jcon->buffer, id), json_tok_contents(jcon->buffer, id),
json_tok_len(id)); json_tok_len(id));
@ -499,7 +498,7 @@ static struct io_plan *write_json(struct io_conn *conn,
if (jcon->stop) { if (jcon->stop) {
log_unusual(jcon->log, "JSON-RPC shutdown"); log_unusual(jcon->log, "JSON-RPC shutdown");
/* Return us to toplevel lightningd.c */ /* Return us to toplevel lightningd.c */
io_break(jcon->dstate); io_break(jcon->ld);
return io_close(conn); return io_close(conn);
} }
@ -533,7 +532,7 @@ again:
toks = json_parse_input(jcon->buffer, jcon->used, &valid); toks = json_parse_input(jcon->buffer, jcon->used, &valid);
if (!toks) { if (!toks) {
if (!valid) { if (!valid) {
log_unusual(jcon->dstate->base_log, log_unusual(jcon->ld->log,
"Invalid token in json input: '%.*s'", "Invalid token in json input: '%.*s'",
(int)jcon->used, jcon->buffer); (int)jcon->used, jcon->buffer);
return io_close(conn); return io_close(conn);
@ -573,18 +572,18 @@ read_more:
} }
static struct io_plan *jcon_connected(struct io_conn *conn, static struct io_plan *jcon_connected(struct io_conn *conn,
struct lightningd_state *dstate) struct lightningd *ld)
{ {
struct json_connection *jcon; struct json_connection *jcon;
jcon = tal(dstate, struct json_connection); jcon = tal(ld, struct json_connection);
jcon->dstate = dstate; jcon->ld = ld;
jcon->used = 0; jcon->used = 0;
jcon->buffer = tal_arr(jcon, char, 64); jcon->buffer = tal_arr(jcon, char, 64);
jcon->stop = false; jcon->stop = false;
jcon->current = NULL; jcon->current = NULL;
jcon->log = new_log(jcon, dstate->log_book, "%sjcon fd %i:", jcon->log = new_log(jcon, ld->log_book, "%sjcon fd %i:",
log_prefix(dstate->base_log), io_conn_fd(conn)); log_prefix(ld->log), io_conn_fd(conn));
list_head_init(&jcon->output); list_head_init(&jcon->output);
io_set_finish(conn, finish_jcon, jcon); io_set_finish(conn, finish_jcon, jcon);
@ -597,13 +596,13 @@ static struct io_plan *jcon_connected(struct io_conn *conn,
} }
static struct io_plan *incoming_jcon_connected(struct io_conn *conn, static struct io_plan *incoming_jcon_connected(struct io_conn *conn,
struct lightningd_state *dstate) struct lightningd *ld)
{ {
log_info(dstate->base_log, "Connected json input"); log_info(ld->log, "Connected json input");
return jcon_connected(conn, dstate); return jcon_connected(conn, ld);
} }
void setup_jsonrpc(struct lightningd_state *dstate, const char *rpc_filename) void setup_jsonrpc(struct lightningd *ld, const char *rpc_filename)
{ {
struct sockaddr_un addr; struct sockaddr_un addr;
int fd, old_umask; int fd, old_umask;
@ -615,7 +614,7 @@ void setup_jsonrpc(struct lightningd_state *dstate, const char *rpc_filename)
fd = open(rpc_filename, O_RDWR); fd = open(rpc_filename, O_RDWR);
if (fd == -1) if (fd == -1)
err(1, "Opening %s", rpc_filename); err(1, "Opening %s", rpc_filename);
io_new_conn(dstate, fd, jcon_connected, dstate); io_new_conn(ld, fd, jcon_connected, ld);
return; return;
} }
@ -639,5 +638,5 @@ void setup_jsonrpc(struct lightningd_state *dstate, const char *rpc_filename)
if (listen(fd, 1) != 0) if (listen(fd, 1) != 0)
err(1, "Listening on '%s'", rpc_filename); err(1, "Listening on '%s'", rpc_filename);
io_new_listener(dstate, fd, incoming_jcon_connected, dstate); io_new_listener(ld, fd, incoming_jcon_connected, ld);
} }

6
lightningd/jsonrpc.h

@ -9,7 +9,7 @@
* You can allocate off this for temporary objects. */ * You can allocate off this for temporary objects. */
struct command { struct command {
/* The global state */ /* The global state */
struct lightningd_state *dstate; struct lightningd *ld;
/* The 'id' which we need to include in the response. */ /* The 'id' which we need to include in the response. */
const char *id; const char *id;
/* The connection, or NULL if it closed. */ /* The connection, or NULL if it closed. */
@ -18,7 +18,7 @@ struct command {
struct json_connection { struct json_connection {
/* The global state */ /* The global state */
struct lightningd_state *dstate; struct lightningd *ld;
/* Logging for this json connection. */ /* Logging for this json connection. */
struct log *log; struct log *log;
@ -70,7 +70,7 @@ void json_add_address(struct json_result *response, const char *fieldname,
/* For initialization */ /* For initialization */
void setup_jsonrpc(struct lightningd_state *dstate, const char *rpc_filename); void setup_jsonrpc(struct lightningd *ld, const char *rpc_filename);
AUTODATA_TYPE(json_command, struct json_command); AUTODATA_TYPE(json_command, struct json_command);
#endif /* LIGHTNING_LIGHTNINGD_JSONRPC_H */ #endif /* LIGHTNING_LIGHTNINGD_JSONRPC_H */

72
lightningd/lightningd.c

@ -4,6 +4,7 @@
#include "peer_control.h" #include "peer_control.h"
#include "subd.h" #include "subd.h"
#include <ccan/array_size/array_size.h> #include <ccan/array_size/array_size.h>
#include <ccan/cast/cast.h>
#include <ccan/crypto/hkdf_sha256/hkdf_sha256.h> #include <ccan/crypto/hkdf_sha256/hkdf_sha256.h>
#include <ccan/err/err.h> #include <ccan/err/err.h>
#include <ccan/io/fdpass/fdpass.h> #include <ccan/io/fdpass/fdpass.h>
@ -30,12 +31,6 @@ char *bitcoin_datadir;
#define FIXME_IMPLEMENT() errx(1, "FIXME: Implement %s", __func__) #define FIXME_IMPLEMENT() errx(1, "FIXME: Implement %s", __func__)
struct peer *find_peer(struct lightningd_state *dstate, const struct pubkey *id);
struct peer *find_peer(struct lightningd_state *dstate, const struct pubkey *id)
{
FIXME_IMPLEMENT();
}
struct peer *find_peer_by_unique_id(struct lightningd *ld, u64 unique_id) struct peer *find_peer_by_unique_id(struct lightningd *ld, u64 unique_id)
{ {
struct peer *peer; struct peer *peer;
@ -52,19 +47,19 @@ void notify_new_block(struct chain_topology *topo, u32 height)
/* FIXME */ /* FIXME */
} }
void db_resolve_invoice(struct lightningd_state *dstate, void db_resolve_invoice(struct lightningd *ld,
const char *label, u64 paid_num); const char *label, u64 paid_num);
void db_resolve_invoice(struct lightningd_state *dstate, void db_resolve_invoice(struct lightningd *ld,
const char *label, u64 paid_num) const char *label, u64 paid_num)
{ {
/* FIXME */ /* FIXME */
} }
bool db_new_invoice(struct lightningd_state *dstate, bool db_new_invoice(struct lightningd *ld,
u64 msatoshi, u64 msatoshi,
const char *label, const char *label,
const struct preimage *r); const struct preimage *r);
bool db_new_invoice(struct lightningd_state *dstate, bool db_new_invoice(struct lightningd *ld,
u64 msatoshi, u64 msatoshi,
const char *label, const char *label,
const struct preimage *r) const struct preimage *r)
@ -73,9 +68,8 @@ bool db_new_invoice(struct lightningd_state *dstate,
return true; return true;
} }
bool db_remove_invoice(struct lightningd_state *dstate, const char *label); bool db_remove_invoice(struct lightningd *ld, const char *label);
bool db_remove_invoice(struct lightningd_state *dstate, bool db_remove_invoice(struct lightningd *ld, const char *label)
const char *label)
{ {
/* FIXME */ /* FIXME */
return true; return true;
@ -91,29 +85,16 @@ static struct lightningd *new_lightningd(const tal_t *ctx)
htlc_in_map_init(&ld->htlcs_in); htlc_in_map_init(&ld->htlcs_in);
htlc_out_map_init(&ld->htlcs_out); htlc_out_map_init(&ld->htlcs_out);
ld->dev_disconnect_fd = -1; ld->dev_disconnect_fd = -1;
ld->dstate.log_book = new_log_book(&ld->dstate, 20*1024*1024,LOG_INFORM); ld->log_book = new_log_book(ld, 20*1024*1024, LOG_INFORM);
ld->log = ld->dstate.base_log = new_log(&ld->dstate, ld->log = new_log(ld, ld->log_book, "lightningd(%u):", (int)getpid());
ld->dstate.log_book,
"lightningd(%u):", list_head_init(&ld->pay_commands);
(int)getpid()); ld->portnum = DEFAULT_PORT;
timers_init(&ld->timers, time_mono());
list_head_init(&ld->dstate.peers); ld->topology = new_topology(ld, ld->log);
list_head_init(&ld->dstate.pay_commands);
ld->dstate.portnum = DEFAULT_PORT;
ld->dstate.testnet = true;
timers_init(&ld->dstate.timers, time_mono());
list_head_init(&ld->dstate.wallet);
list_head_init(&ld->dstate.addresses);
ld->dstate.dev_never_routefail = false;
ld->dstate.reexec = NULL;
ld->dstate.external_ip = NULL;
ld->dstate.announce = NULL;
ld->topology = ld->dstate.topology = new_topology(ld, ld->log);
ld->bitcoind = ld->dstate.bitcoind = new_bitcoind(ld, ld->log);
ld->chainparams = chainparams_for_network("testnet");
/* FIXME: Move into invoice daemon. */ /* FIXME: Move into invoice daemon. */
ld->dstate.invoices = invoices_init(&ld->dstate); ld->invoices = invoices_init(ld);
return ld; return ld;
} }
@ -140,7 +121,7 @@ static void test_daemons(const struct lightningd *ld)
pid_t pid = pipecmd(&outfd, NULL, &outfd, pid_t pid = pipecmd(&outfd, NULL, &outfd,
dpath, "--version", NULL); dpath, "--version", NULL);
log_debug(ld->dstate.base_log, "testing %s", dpath); log_debug(ld->log, "testing %s", dpath);
if (pid == -1) if (pid == -1)
err(1, "Could not run %s", dpath); err(1, "Could not run %s", dpath);
verstring = grab_fd(ctx, outfd); verstring = grab_fd(ctx, outfd);
@ -191,6 +172,12 @@ static void shutdown_subdaemons(struct lightningd *ld)
subd_shutdown(p->owner, 0); subd_shutdown(p->owner, 0);
} }
struct chainparams *get_chainparams(const struct lightningd *ld)
{
return cast_const(struct chainparams *,
ld->topology->bitcoind->chainparams);
}
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
struct lightningd *ld = new_lightningd(NULL); struct lightningd *ld = new_lightningd(NULL);
@ -204,7 +191,7 @@ int main(int argc, char *argv[])
/* Figure out where we are first. */ /* Figure out where we are first. */
ld->daemon_dir = find_my_path(ld, argv[0]); ld->daemon_dir = find_my_path(ld, argv[0]);
register_opts(&ld->dstate); register_opts(ld);
opt_register_arg("--dev-debugger=<subdaemon>", opt_subd_debug, NULL, opt_register_arg("--dev-debugger=<subdaemon>", opt_subd_debug, NULL,
ld, "Wait for gdb attach at start of <subdaemon>"); ld, "Wait for gdb attach at start of <subdaemon>");
@ -220,7 +207,7 @@ int main(int argc, char *argv[])
ld->broadcast_interval = 30000; ld->broadcast_interval = 30000;
/* Handle options and config; move to .lightningd */ /* Handle options and config; move to .lightningd */
newdir = handle_opts(&ld->dstate, argc, argv); newdir = handle_opts(ld, argc, argv);
/* Activate crash log now we're in the right place. */ /* Activate crash log now we're in the right place. */
crashlog_activate(ld->log); crashlog_activate(ld->log);
@ -244,8 +231,9 @@ int main(int argc, char *argv[])
gossip_init(ld); gossip_init(ld);
/* Initialize block topology. */ /* Initialize block topology. */
setup_topology(ld->topology, ld->bitcoind, &ld->dstate.timers, setup_topology(ld->topology,
ld->dstate.config.poll_time, &ld->timers,
ld->config.poll_time,
/* FIXME: Load from peers. */ /* FIXME: Load from peers. */
0); 0);
@ -262,7 +250,7 @@ int main(int argc, char *argv[])
} }
/* Create RPC socket (if any) */ /* Create RPC socket (if any) */
setup_jsonrpc(&ld->dstate, ld->dstate.rpc_filename); setup_jsonrpc(ld, ld->rpc_filename);
/* Ready for connections from peers. */ /* Ready for connections from peers. */
setup_listeners(ld); setup_listeners(ld);
@ -274,14 +262,14 @@ int main(int argc, char *argv[])
for (;;) { for (;;) {
struct timer *expired; struct timer *expired;
void *v = io_loop(&ld->dstate.timers, &expired); void *v = io_loop(&ld->timers, &expired);
/* We use io_break(dstate) to shut down. */ /* We use io_break(dstate) to shut down. */
if (v == ld) if (v == ld)
break; break;
if (expired) if (expired)
timer_expired(&ld->dstate, expired); timer_expired(ld, expired);
} }
shutdown_subdaemons(ld); shutdown_subdaemons(ld);

96
lightningd/lightningd.h

@ -72,85 +72,29 @@ struct config {
struct ipaddr ipaddr; struct ipaddr ipaddr;
}; };
/* Here's where the global variables hide! */ struct lightningd {
struct lightningd_state { /* The directory to find all the subdaemons. */
/* Where all our logging goes. */ const char *daemon_dir;
struct log_book *log_book;
struct log *base_log;
FILE *logf;
/* Our config dir, and rpc file */ /* Our config dir, and rpc file */
char *config_dir; char *config_dir;
char *rpc_filename; char *rpc_filename;
/* Port we're listening on */
u16 portnum;
/* We're on testnet. */
bool testnet;
/* Configuration settings. */ /* Configuration settings. */
struct config config; struct config config;
/* The database where we keep our stuff. */ /* Log for general stuff. */
struct db *db; struct log_book *log_book;
struct log *log;
/* Any pending timers. */
struct timers timers;
/* Cached block topology. */
struct chain_topology *topology;
/* Our peers. */
struct list_head peers;
/* Addresses to contact peers. */
struct list_head addresses;
/* Any outstanding "pay" commands. */
struct list_head pay_commands;
/* Our private key */
struct privkey *privkey;
/* This is us. */ /* This is us. */
struct pubkey id; struct pubkey id;
/* Our tame bitcoind. */ /* Any pending timers. */
struct bitcoind *bitcoind; struct timers timers;
/* Wallet addresses we maintain. */
struct list_head wallet;
/* Maintained by invoices.c */
struct invoices *invoices;
/* Routing information */
struct routing_state *rstate;
/* For testing: don't fail if we can't route. */
bool dev_never_routefail;
/* Re-exec hack for testing. */
char **reexec;
/* IP/hostname to be announced for incoming connections */
char *external_ip;
/* Announce timer. */
struct oneshot *announce;
};
/* FIXME: This is two structures, during the migration from old setup to new */
struct lightningd {
/* Must be first, since things assume we can tal() off it */
struct lightningd_state dstate;
/* The directory to find all the subdaemons. */
const char *daemon_dir;
/* Log for general stuff. */ /* Port we're listening on */
struct log *log; u16 portnum;
/* Bearer of all my secrets. */ /* Bearer of all my secrets. */
int hsm_fd; int hsm_fd;
@ -165,12 +109,6 @@ struct lightningd {
/* Used to give a unique seed to every peer. */ /* Used to give a unique seed to every peer. */
u64 peer_counter; u64 peer_counter;
/* Public base for bip32 keys, and max we've ever used. */
struct ext_key *bip32_base;
/* Our bitcoind context. */
struct bitcoind *bitcoind;
/* Our chain topology. */ /* Our chain topology. */
struct chain_topology *topology; struct chain_topology *topology;
@ -188,7 +126,11 @@ struct lightningd {
struct wallet *wallet; struct wallet *wallet;
const struct chainparams *chainparams; /* Maintained by invoices.c */
struct invoices *invoices;
/* Any outstanding "pay" commands. */
struct list_head pay_commands;
}; };
/** /**
@ -209,10 +151,6 @@ void derive_peer_seed(struct lightningd *ld, struct privkey *peer_seed,
const struct pubkey *peer_id, const u64 channel_id); const struct pubkey *peer_id, const u64 channel_id);
struct peer *find_peer_by_unique_id(struct lightningd *ld, u64 unique_id); struct peer *find_peer_by_unique_id(struct lightningd *ld, u64 unique_id);
/* FIXME */
static inline struct lightningd * struct chainparams *get_chainparams(const struct lightningd *ld);
ld_from_dstate(const struct lightningd_state *dstate)
{
return container_of(dstate, struct lightningd, dstate);
}
#endif /* LIGHTNING_LIGHTNINGD_LIGHTNINGD_H */ #endif /* LIGHTNING_LIGHTNINGD_LIGHTNINGD_H */

1
lightningd/log.h

@ -7,7 +7,6 @@
#include <stdarg.h> #include <stdarg.h>
struct timerel; struct timerel;
struct lightningd_state;
enum log_level { enum log_level {
/* Logging all IO. */ /* Logging all IO. */

9
lightningd/new_connection.c

@ -235,10 +235,9 @@ static struct io_plan *hsm_then_handshake(struct io_conn *conn,
tal_steal(handshaked, c); tal_steal(handshaked, c);
if (c->known_id) { if (c->known_id) {
msg = towire_handshake_initiator(tmpctx, &ld->dstate.id, msg = towire_handshake_initiator(tmpctx, &ld->id, c->known_id);
c->known_id);
} else { } else {
msg = towire_handshake_responder(tmpctx, &ld->dstate.id); msg = towire_handshake_responder(tmpctx, &ld->id);
} }
/* Now hand peer request to the handshake daemon: hands it /* Now hand peer request to the handshake daemon: hands it
@ -257,12 +256,12 @@ error:
} }
struct io_plan *connection_out(struct io_conn *conn, struct io_plan *connection_out(struct io_conn *conn,
struct lightningd_state *dstate, struct lightningd *ld,
const struct netaddr *netaddr, const struct netaddr *netaddr,
struct connection *c) struct connection *c)
{ {
c->netaddr = *netaddr; c->netaddr = *netaddr;
return hsm_then_handshake(conn, ld_from_dstate(dstate), c); return hsm_then_handshake(conn, ld, c);
} }
struct io_plan *connection_in(struct io_conn *conn, struct lightningd *ld) struct io_plan *connection_in(struct io_conn *conn, struct lightningd *ld)

3
lightningd/new_connection.h

@ -6,7 +6,6 @@
struct command; struct command;
struct io_conn; struct io_conn;
struct lightningd; struct lightningd;
struct lightningd_state;
struct netaddr; struct netaddr;
struct pubkey; struct pubkey;
@ -16,7 +15,7 @@ struct connection *new_connection(const tal_t *ctx,
const struct pubkey *known_id); const struct pubkey *known_id);
struct io_plan *connection_out(struct io_conn *conn, struct io_plan *connection_out(struct io_conn *conn,
struct lightningd_state *dstate, struct lightningd *dstate,
const struct netaddr *netaddr, const struct netaddr *netaddr,
struct connection *c); struct connection *c);

140
lightningd/options.c

@ -153,11 +153,9 @@ static void opt_show_u16(char buf[OPT_SHOW_LEN], const u16 *u)
static char *opt_set_network(const char *arg, struct lightningd *ld) static char *opt_set_network(const char *arg, struct lightningd *ld)
{ {
ld->chainparams = chainparams_for_network(arg); ld->topology->bitcoind->chainparams = chainparams_for_network(arg);
if (!ld->chainparams) if (!ld->topology->bitcoind->chainparams)
return tal_fmt(NULL, "Unknown network name '%s'", arg); return tal_fmt(NULL, "Unknown network name '%s'", arg);
ld->dstate.testnet = ld->chainparams->testnet;
ld->bitcoind->chainparams = ld->chainparams;
return NULL; return NULL;
} }
@ -170,87 +168,84 @@ static void opt_show_network(char buf[OPT_SHOW_LEN],
} }
*/ */
static void config_register_opts(struct lightningd_state *dstate) static void config_register_opts(struct lightningd *ld)
{ {
opt_register_arg("--locktime-blocks", opt_set_u32, opt_show_u32, opt_register_arg("--locktime-blocks", opt_set_u32, opt_show_u32,
&dstate->config.locktime_blocks, &ld->config.locktime_blocks,
"Blocks before peer can unilaterally spend funds"); "Blocks before peer can unilaterally spend funds");
opt_register_arg("--max-locktime-blocks", opt_set_u32, opt_show_u32, opt_register_arg("--max-locktime-blocks", opt_set_u32, opt_show_u32,
&dstate->config.locktime_max, &ld->config.locktime_max,
"Maximum seconds peer can lock up our funds"); "Maximum seconds peer can lock up our funds");
opt_register_arg("--anchor-onchain", opt_set_u32, opt_show_u32, opt_register_arg("--anchor-onchain", opt_set_u32, opt_show_u32,
&dstate->config.anchor_onchain_wait, &ld->config.anchor_onchain_wait,
"Blocks before we give up on pending anchor transaction"); "Blocks before we give up on pending anchor transaction");
opt_register_arg("--anchor-confirms", opt_set_u32, opt_show_u32, opt_register_arg("--anchor-confirms", opt_set_u32, opt_show_u32,
&dstate->config.anchor_confirms, &ld->config.anchor_confirms,
"Confirmations required for anchor transaction"); "Confirmations required for anchor transaction");
opt_register_arg("--max-anchor-confirms", opt_set_u32, opt_show_u32, opt_register_arg("--max-anchor-confirms", opt_set_u32, opt_show_u32,
&dstate->config.anchor_confirms_max, &ld->config.anchor_confirms_max,
"Maximum confirmations other side can wait for anchor transaction"); "Maximum confirmations other side can wait for anchor transaction");
opt_register_arg("--forever-confirms", opt_set_u32, opt_show_u32, opt_register_arg("--forever-confirms", opt_set_u32, opt_show_u32,
&dstate->config.forever_confirms, &ld->config.forever_confirms,
"Confirmations after which we consider a reorg impossible"); "Confirmations after which we consider a reorg impossible");
opt_register_arg("--commit-fee-min=<percent>", opt_set_u32, opt_show_u32, opt_register_arg("--commit-fee-min=<percent>", opt_set_u32, opt_show_u32,
&dstate->config.commitment_fee_min_percent, &ld->config.commitment_fee_min_percent,
"Minimum percentage of fee to accept for commitment"); "Minimum percentage of fee to accept for commitment");
opt_register_arg("--commit-fee-max=<percent>", opt_set_u32, opt_show_u32, opt_register_arg("--commit-fee-max=<percent>", opt_set_u32, opt_show_u32,
&dstate->config.commitment_fee_max_percent, &ld->config.commitment_fee_max_percent,
"Maximum percentage of fee to accept for commitment (0 for unlimited)"); "Maximum percentage of fee to accept for commitment (0 for unlimited)");
opt_register_arg("--commit-fee=<percent>", opt_set_u32, opt_show_u32, opt_register_arg("--commit-fee=<percent>", opt_set_u32, opt_show_u32,
&dstate->config.commitment_fee_percent, &ld->config.commitment_fee_percent,
"Percentage of fee to request for their commitment"); "Percentage of fee to request for their commitment");
opt_register_arg("--override-fee-rate", opt_set_u64, opt_show_u64, opt_register_arg("--override-fee-rate", opt_set_u64, opt_show_u64,
&dstate->topology->override_fee_rate, &ld->topology->override_fee_rate,
"Force a specific rate in satoshis per kb regardless of estimated fees"); "Force a specific rate in satoshis per kb regardless of estimated fees");
opt_register_arg("--default-fee-rate", opt_set_u64, opt_show_u64, opt_register_arg("--default-fee-rate", opt_set_u64, opt_show_u64,
&dstate->topology->default_fee_rate, &ld->topology->default_fee_rate,
"Satoshis per kb if can't estimate fees"); "Satoshis per kb if can't estimate fees");
opt_register_arg("--min-htlc-expiry", opt_set_u32, opt_show_u32, opt_register_arg("--min-htlc-expiry", opt_set_u32, opt_show_u32,
&dstate->config.min_htlc_expiry, &ld->config.min_htlc_expiry,
"Minimum number of blocks to accept an HTLC before expiry"); "Minimum number of blocks to accept an HTLC before expiry");
opt_register_arg("--max-htlc-expiry", opt_set_u32, opt_show_u32, opt_register_arg("--max-htlc-expiry", opt_set_u32, opt_show_u32,
&dstate->config.max_htlc_expiry, &ld->config.max_htlc_expiry,
"Maximum number of blocks to accept an HTLC before expiry"); "Maximum number of blocks to accept an HTLC before expiry");
opt_register_arg("--deadline-blocks", opt_set_u32, opt_show_u32, opt_register_arg("--deadline-blocks", opt_set_u32, opt_show_u32,
&dstate->config.deadline_blocks, &ld->config.deadline_blocks,
"Number of blocks before HTLC timeout before we drop connection"); "Number of blocks before HTLC timeout before we drop connection");
opt_register_arg("--bitcoind-poll", opt_set_time, opt_show_time, opt_register_arg("--bitcoind-poll", opt_set_time, opt_show_time,
&dstate->config.poll_time, &ld->config.poll_time,
"Time between polling for new transactions"); "Time between polling for new transactions");
opt_register_arg("--commit-time", opt_set_time, opt_show_time, opt_register_arg("--commit-time", opt_set_time, opt_show_time,
&dstate->config.commit_time, &ld->config.commit_time,
"Time after changes before sending out COMMIT"); "Time after changes before sending out COMMIT");
opt_register_arg("--fee-base", opt_set_u32, opt_show_u32, opt_register_arg("--fee-base", opt_set_u32, opt_show_u32,
&dstate->config.fee_base, &ld->config.fee_base,
"Millisatoshi minimum to charge for HTLC"); "Millisatoshi minimum to charge for HTLC");
opt_register_arg("--fee-per-satoshi", opt_set_s32, opt_show_s32, opt_register_arg("--fee-per-satoshi", opt_set_s32, opt_show_s32,
&dstate->config.fee_per_satoshi, &ld->config.fee_per_satoshi,
"Microsatoshi fee for every satoshi in HTLC"); "Microsatoshi fee for every satoshi in HTLC");
opt_register_noarg("--disable-irc", opt_set_invbool, opt_register_noarg("--disable-irc", opt_set_invbool,
&dstate->config.use_irc, &ld->config.use_irc,
"Disable IRC peer discovery for routing"); "Disable IRC peer discovery for routing");
opt_register_noarg("--ignore-dbversion", opt_set_bool, opt_register_noarg("--ignore-dbversion", opt_set_bool,
&dstate->config.db_version_ignore, &ld->config.db_version_ignore,
"Continue despite invalid database version (DANGEROUS!)"); "Continue despite invalid database version (DANGEROUS!)");
opt_register_arg("--ipaddr", opt_set_ipaddr, NULL, opt_register_arg("--ipaddr", opt_set_ipaddr, NULL,
&dstate->config.ipaddr, &ld->config.ipaddr,
"Set the IP address (v4 or v6) to announce to the network for incoming connections"); "Set the IP address (v4 or v6) to announce to the network for incoming connections");
/* FIXME: Register opt_show_network with the option */ /* FIXME: Register opt_show_network with the option */
opt_register_arg("--network", opt_set_network, NULL, opt_register_early_arg("--network", opt_set_network, NULL, ld,
ld_from_dstate(dstate),
"Select the network parameters (bitcoin, testnet, " "Select the network parameters (bitcoin, testnet, "
"regtest, or litecoin)"); "regtest, or litecoin)");
} }
static void dev_register_opts(struct lightningd_state *dstate) static void dev_register_opts(struct lightningd *ld)
{ {
opt_register_noarg("--dev-no-routefail", opt_set_bool,
&dstate->dev_never_routefail, opt_hidden);
opt_register_noarg("--dev-no-broadcast", opt_set_bool, opt_register_noarg("--dev-no-broadcast", opt_set_bool,
&dstate->topology->dev_no_broadcast, opt_hidden); &ld->topology->dev_no_broadcast, opt_hidden);
} }
static const struct config testnet_config = { static const struct config testnet_config = {
@ -380,22 +375,22 @@ static const struct config mainnet_config = {
.ipaddr.type = 0, .ipaddr.type = 0,
}; };
static void check_config(struct lightningd_state *dstate) static void check_config(struct lightningd *ld)
{ {
/* We do this by ensuring it's less than the minimum we would accept. */ /* We do this by ensuring it's less than the minimum we would accept. */
if (dstate->config.commitment_fee_max_percent != 0 if (ld->config.commitment_fee_max_percent != 0
&& dstate->config.commitment_fee_max_percent && ld->config.commitment_fee_max_percent
< dstate->config.commitment_fee_min_percent) < ld->config.commitment_fee_min_percent)
fatal("Commitment fee invalid min-max %u-%u", fatal("Commitment fee invalid min-max %u-%u",
dstate->config.commitment_fee_min_percent, ld->config.commitment_fee_min_percent,
dstate->config.commitment_fee_max_percent); ld->config.commitment_fee_max_percent);
if (dstate->config.forever_confirms < 100 && !dstate->testnet) if (ld->config.forever_confirms < 100 && !get_chainparams(ld)->testnet)
log_unusual(dstate->base_log, log_unusual(ld->log,
"Warning: forever-confirms of %u is less than 100!", "Warning: forever-confirms of %u is less than 100!",
dstate->config.forever_confirms); ld->config.forever_confirms);
if (dstate->config.anchor_confirms == 0) if (ld->config.anchor_confirms == 0)
fatal("anchor-confirms must be greater than zero"); fatal("anchor-confirms must be greater than zero");
/* FIXME-OLD #2: /* FIXME-OLD #2:
@ -403,18 +398,18 @@ static void check_config(struct lightningd_state *dstate)
* a node MUST estimate the deadline for successful redemption * a node MUST estimate the deadline for successful redemption
* for each HTLC it offers. A node MUST NOT offer a HTLC * for each HTLC it offers. A node MUST NOT offer a HTLC
* after this deadline */ * after this deadline */
if (dstate->config.deadline_blocks >= dstate->config.min_htlc_expiry) if (ld->config.deadline_blocks >= ld->config.min_htlc_expiry)
fatal("Deadline %u can't be more than minimum expiry %u", fatal("Deadline %u can't be more than minimum expiry %u",
dstate->config.deadline_blocks, ld->config.deadline_blocks,
dstate->config.min_htlc_expiry); ld->config.min_htlc_expiry);
} }
static void setup_default_config(struct lightningd_state *dstate) static void setup_default_config(struct lightningd *ld)
{ {
if (dstate->testnet) if (get_chainparams(ld)->testnet)
dstate->config = testnet_config; ld->config = testnet_config;
else else
dstate->config = mainnet_config; ld->config = mainnet_config;
} }
@ -444,27 +439,27 @@ static void config_log_stderr_exit(const char *fmt, ...)
} }
/* We turn the config file into cmdline arguments. */ /* We turn the config file into cmdline arguments. */
static void opt_parse_from_config(struct lightningd_state *dstate) static void opt_parse_from_config(struct lightningd *ld)
{ {
char *contents, **lines; char *contents, **lines;
char **argv; char **argv;
int i, argc; int i, argc;
contents = grab_file(dstate, "config"); contents = grab_file(ld, "config");
/* Doesn't have to exist. */ /* Doesn't have to exist. */
if (!contents) { if (!contents) {
if (errno != ENOENT) if (errno != ENOENT)
fatal("Opening and reading config: %s", fatal("Opening and reading config: %s",
strerror(errno)); strerror(errno));
/* Now we can set up defaults, since no config file. */ /* Now we can set up defaults, since no config file. */
setup_default_config(dstate); setup_default_config(ld);
return; return;
} }
lines = tal_strsplit(contents, contents, "\r\n", STR_NO_EMPTY); lines = tal_strsplit(contents, contents, "\r\n", STR_NO_EMPTY);
/* We have to keep argv around, since opt will point into it */ /* We have to keep argv around, since opt will point into it */
argv = tal_arr(dstate, char *, argc = 1); argv = tal_arr(ld, char *, argc = 1);
argv[0] = "lightning config file"; argv[0] = "lightning config file";
for (i = 0; i < tal_count(lines) - 1; i++) { for (i = 0; i < tal_count(lines) - 1; i++) {
@ -480,13 +475,13 @@ static void opt_parse_from_config(struct lightningd_state *dstate)
opt_early_parse(argc, argv, config_log_stderr_exit); opt_early_parse(argc, argv, config_log_stderr_exit);
/* Now we can set up defaults, depending on whether testnet or not */ /* Now we can set up defaults, depending on whether testnet or not */
setup_default_config(dstate); setup_default_config(ld);
opt_parse(&argc, argv, config_log_stderr_exit); opt_parse(&argc, argv, config_log_stderr_exit);
tal_free(contents); tal_free(contents);
} }
void register_opts(struct lightningd_state *dstate) void register_opts(struct lightningd *ld)
{ {
opt_set_alloc(opt_allocfn, tal_reallocfn, tal_freefn); opt_set_alloc(opt_allocfn, tal_reallocfn, tal_freefn);
@ -494,21 +489,20 @@ void register_opts(struct lightningd_state *dstate)
"\n" "\n"
"A bitcoin lightning daemon.", "A bitcoin lightning daemon.",
"Print this message."); "Print this message.");
opt_register_arg("--port", opt_set_u16, opt_show_u16, &dstate->portnum, opt_register_arg("--port", opt_set_u16, opt_show_u16, &ld->portnum,
"Port to bind to (0 means don't listen)"); "Port to bind to (0 means don't listen)");
opt_register_arg("--bitcoin-datadir", opt_set_charp, NULL, opt_register_arg("--bitcoin-datadir", opt_set_charp, NULL,
&dstate->bitcoind->datadir, &ld->topology->bitcoind->datadir,
"-datadir arg for bitcoin-cli"); "-datadir arg for bitcoin-cli");
opt_register_logging(dstate->base_log); opt_register_logging(ld->log);
opt_register_version(); opt_register_version();
configdir_register_opts(dstate, configdir_register_opts(ld, &ld->config_dir, &ld->rpc_filename);
&dstate->config_dir, &dstate->rpc_filename); config_register_opts(ld);
config_register_opts(dstate); dev_register_opts(ld);
dev_register_opts(dstate);
} }
bool handle_opts(struct lightningd_state *dstate, int argc, char *argv[]) bool handle_opts(struct lightningd *ld, int argc, char *argv[])
{ {
bool newdir = false; bool newdir = false;
@ -516,27 +510,27 @@ bool handle_opts(struct lightningd_state *dstate, int argc, char *argv[])
opt_early_parse(argc, argv, opt_log_stderr_exit); opt_early_parse(argc, argv, opt_log_stderr_exit);
/* Move to config dir, to save ourselves the hassle of path manip. */ /* Move to config dir, to save ourselves the hassle of path manip. */
if (chdir(dstate->config_dir) != 0) { if (chdir(ld->config_dir) != 0) {
log_unusual(dstate->base_log, "Creating lightningd dir %s" log_unusual(ld->log, "Creating lightningd dir %s"
" (because chdir gave %s)", " (because chdir gave %s)",
dstate->config_dir, strerror(errno)); ld->config_dir, strerror(errno));
if (mkdir(dstate->config_dir, 0700) != 0) if (mkdir(ld->config_dir, 0700) != 0)
fatal("Could not make directory %s: %s", fatal("Could not make directory %s: %s",
dstate->config_dir, strerror(errno)); ld->config_dir, strerror(errno));
if (chdir(dstate->config_dir) != 0) if (chdir(ld->config_dir) != 0)
fatal("Could not change directory %s: %s", fatal("Could not change directory %s: %s",
dstate->config_dir, strerror(errno)); ld->config_dir, strerror(errno));
newdir = true; newdir = true;
} }
/* Now look for config file */ /* Now look for config file */
opt_parse_from_config(dstate); opt_parse_from_config(ld);
dstate->config.ipaddr.port = dstate->portnum; ld->config.ipaddr.port = ld->portnum;
opt_parse(&argc, argv, opt_log_stderr_exit); opt_parse(&argc, argv, opt_log_stderr_exit);
if (argc != 1) if (argc != 1)
errx(1, "no arguments accepted"); errx(1, "no arguments accepted");
check_config(dstate); check_config(ld);
return newdir; return newdir;
} }

6
lightningd/options.h

@ -3,14 +3,14 @@
#include "config.h" #include "config.h"
#include <ccan/tal/tal.h> #include <ccan/tal/tal.h>
struct lightningd_state; struct lightningd;
/* You can register additional options *after* this if you want. */ /* You can register additional options *after* this if you want. */
void register_opts(struct lightningd_state *dstate); void register_opts(struct lightningd *ld);
/* After this, we're in the .lightning dir, config file parsed. /* After this, we're in the .lightning dir, config file parsed.
* If we just created the dir, returns true. * If we just created the dir, returns true.
*/ */
bool handle_opts(struct lightningd_state *dstate, int argc, char *argv[]); bool handle_opts(struct lightningd *ld, int argc, char *argv[]);
#endif /* LIGHTNING_LIGHTNINGD_OPTIONS_H */ #endif /* LIGHTNING_LIGHTNINGD_OPTIONS_H */

23
lightningd/pay.c

@ -131,7 +131,7 @@ static struct pay_command *find_pay_command(struct lightningd *ld,
{ {
struct pay_command *pc; struct pay_command *pc;
list_for_each(&ld->dstate.pay_commands, pc, list) { list_for_each(&ld->pay_commands, pc, list) {
if (structeq(rhash, &pc->rhash)) if (structeq(rhash, &pc->rhash))
return pc; return pc;
} }
@ -146,7 +146,6 @@ static void pay_command_destroyed(struct pay_command *pc)
static void json_sendpay(struct command *cmd, static void json_sendpay(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct pubkey *ids; struct pubkey *ids;
jsmntok_t *routetok, *rhashtok; jsmntok_t *routetok, *rhashtok;
const jsmntok_t *t, *end; const jsmntok_t *t, *end;
@ -189,7 +188,7 @@ static void json_sendpay(struct command *cmd,
} }
/* Expiry for HTLCs is absolute. And add one to give some margin. */ /* Expiry for HTLCs is absolute. And add one to give some margin. */
base_expiry = get_block_height(cmd->dstate->topology) + 1; base_expiry = get_block_height(cmd->ld->topology) + 1;
end = json_next(routetok); end = json_next(routetok);
n_hops = 0; n_hops = 0;
@ -267,17 +266,17 @@ static void json_sendpay(struct command *cmd,
hop_data[n_hops-1].outgoing_cltv = base_expiry + delay; hop_data[n_hops-1].outgoing_cltv = base_expiry + delay;
memset(&hop_data[n_hops-1].channel_id, 0, sizeof(struct short_channel_id)); memset(&hop_data[n_hops-1].channel_id, 0, sizeof(struct short_channel_id));
pc = find_pay_command(ld, &rhash); pc = find_pay_command(cmd->ld, &rhash);
if (pc) { if (pc) {
log_debug(ld->log, "json_sendpay: found previous"); log_debug(cmd->ld->log, "json_sendpay: found previous");
if (pc->out) { if (pc->out) {
log_add(ld->log, "... still in progress"); log_add(cmd->ld->log, "... still in progress");
command_fail(cmd, "still in progress"); command_fail(cmd, "still in progress");
return; return;
} }
if (pc->rval) { if (pc->rval) {
size_t old_nhops = tal_count(pc->ids); size_t old_nhops = tal_count(pc->ids);
log_add(ld->log, "... succeeded"); log_add(cmd->ld->log, "... succeeded");
/* Must match successful payment parameters. */ /* Must match successful payment parameters. */
if (pc->msatoshi != lastamount) { if (pc->msatoshi != lastamount) {
command_fail(cmd, command_fail(cmd,
@ -298,10 +297,10 @@ static void json_sendpay(struct command *cmd,
return; return;
} }
/* FIXME: We can free failed ones... */ /* FIXME: We can free failed ones... */
log_add(ld->log, "... retrying"); log_add(cmd->ld->log, "... retrying");
} }
peer = peer_by_id(ld, &ids[0]); peer = peer_by_id(cmd->ld, &ids[0]);
if (!peer) { if (!peer) {
command_fail(cmd, "no connection to first peer found"); command_fail(cmd, "no connection to first peer found");
return; return;
@ -317,8 +316,8 @@ static void json_sendpay(struct command *cmd,
if (pc) if (pc)
pc->ids = tal_free(pc->ids); pc->ids = tal_free(pc->ids);
else { else {
pc = tal(ld, struct pay_command); pc = tal(cmd->ld, struct pay_command);
list_add_tail(&cmd->dstate->pay_commands, &pc->list); list_add_tail(&cmd->ld->pay_commands, &pc->list);
tal_add_destructor(pc, pay_command_destroyed); tal_add_destructor(pc, pay_command_destroyed);
} }
pc->cmd = cmd; pc->cmd = cmd;
@ -328,7 +327,7 @@ static void json_sendpay(struct command *cmd,
pc->msatoshi = lastamount; pc->msatoshi = lastamount;
pc->path_secrets = tal_steal(pc, path_secrets); pc->path_secrets = tal_steal(pc, path_secrets);
log_info(ld->log, "Sending %"PRIu64" over %zu hops to deliver %"PRIu64, log_info(cmd->ld->log, "Sending %"PRIu64" over %zu hops to deliver %"PRIu64,
amount, n_hops, lastamount); amount, n_hops, lastamount);
/* Wait until we get response. */ /* Wait until we get response. */

92
lightningd/peer_control.c

@ -62,11 +62,10 @@ void peer_debug(struct peer *peer, const char *fmt, ...)
/* Mutual recursion, sets timer. */ /* Mutual recursion, sets timer. */
static void peer_reconnect(struct peer *peer); static void peer_reconnect(struct peer *peer);
static void reconnect_failed(struct lightningd_state *dstate, static void reconnect_failed(struct lightningd *ld,
struct connection *c) struct connection *c)
{ {
/* Figure out what peer, set reconnect timer. */ /* Figure out what peer, set reconnect timer. */
struct lightningd *ld = ld_from_dstate(dstate);
struct peer *peer = peer_by_id(ld, connection_known_id(c)); struct peer *peer = peer_by_id(ld, connection_known_id(c));
log_debug(peer->log, "reconnect_failed"); log_debug(peer->log, "reconnect_failed");
@ -94,14 +93,14 @@ static void try_reconnect(struct peer *peer)
/* FIXME: Combine known address with gossip addresses and possibly /* FIXME: Combine known address with gossip addresses and possibly
* DNS seed addresses. */ * DNS seed addresses. */
addrs = tal_dup_arr(c, struct netaddr, &peer->netaddr, 1, 0); addrs = tal_dup_arr(c, struct netaddr, &peer->netaddr, 1, 0);
multiaddress_connect(&peer->ld->dstate, addrs, multiaddress_connect(peer->ld, addrs,
connection_out, reconnect_failed, c); connection_out, reconnect_failed, c);
} }
static void peer_reconnect(struct peer *peer) static void peer_reconnect(struct peer *peer)
{ {
new_reltimer(&peer->ld->dstate.timers, new_reltimer(&peer->ld->timers,
peer, peer->ld->dstate.config.poll_time, peer, peer->ld->config.poll_time,
try_reconnect, peer); try_reconnect, peer);
} }
@ -574,7 +573,7 @@ void populate_peer(struct lightningd *ld, struct peer *peer)
/* Max 128k per peer. */ /* Max 128k per peer. */
peer->log_book = new_log_book(peer, 128*1024, peer->log_book = new_log_book(peer, 128*1024,
get_log_level(ld->dstate.log_book)); get_log_level(ld->log_book));
peer->log = new_log(peer, peer->log_book, "peer %s:", idname); peer->log = new_log(peer, peer->log_book, "peer %s:", idname);
set_log_outfn(peer->log_book, copy_to_parent_log, peer); set_log_outfn(peer->log_book, copy_to_parent_log, peer);
tal_free(idname); tal_free(idname);
@ -735,7 +734,7 @@ void setup_listeners(struct lightningd *ld)
socklen_t len; socklen_t len;
int fd1, fd2; int fd1, fd2;
if (!ld->dstate.portnum) { if (!ld->portnum) {
log_debug(ld->log, "Zero portnum, not listening for incoming"); log_debug(ld->log, "Zero portnum, not listening for incoming");
return; return;
} }
@ -743,12 +742,12 @@ void setup_listeners(struct lightningd *ld)
memset(&addr, 0, sizeof(addr)); memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY; addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(ld->dstate.portnum); addr.sin_port = htons(ld->portnum);
memset(&addr6, 0, sizeof(addr6)); memset(&addr6, 0, sizeof(addr6));
addr6.sin6_family = AF_INET6; addr6.sin6_family = AF_INET6;
addr6.sin6_addr = in6addr_any; addr6.sin6_addr = in6addr_any;
addr6.sin6_port = htons(ld->dstate.portnum); addr6.sin6_port = htons(ld->portnum);
/* IPv6, since on Linux that (usually) binds to IPv4 too. */ /* IPv6, since on Linux that (usually) binds to IPv4 too. */
fd1 = make_listen_fd(ld, AF_INET6, &addr6, sizeof(addr6)); fd1 = make_listen_fd(ld, AF_INET6, &addr6, sizeof(addr6));
@ -763,9 +762,9 @@ void setup_listeners(struct lightningd *ld)
fd1 = -1; fd1 = -1;
} else { } else {
addr.sin_port = in6.sin6_port; addr.sin_port = in6.sin6_port;
assert(ld->dstate.portnum == ntohs(addr.sin_port)); assert(ld->portnum == ntohs(addr.sin_port));
log_debug(ld->log, "Creating IPv6 listener on port %u", log_debug(ld->log, "Creating IPv6 listener on port %u",
ld->dstate.portnum); ld->portnum);
io_new_listener(ld, fd1, connection_in, ld); io_new_listener(ld, fd1, connection_in, ld);
} }
} }
@ -780,19 +779,19 @@ void setup_listeners(struct lightningd *ld)
close_noerr(fd2); close_noerr(fd2);
fd2 = -1; fd2 = -1;
} else { } else {
assert(ld->dstate.portnum == ntohs(addr.sin_port)); assert(ld->portnum == ntohs(addr.sin_port));
log_debug(ld->log, "Creating IPv4 listener on port %u", log_debug(ld->log, "Creating IPv4 listener on port %u",
ld->dstate.portnum); ld->portnum);
io_new_listener(ld, fd2, connection_in, ld); io_new_listener(ld, fd2, connection_in, ld);
} }
} }
if (fd1 < 0 && fd2 < 0) if (fd1 < 0 && fd2 < 0)
fatal("Could not bind to a network address on port %u", fatal("Could not bind to a network address on port %u",
ld->dstate.portnum); ld->portnum);
} }
static void connect_failed(struct lightningd_state *dstate, static void connect_failed(struct lightningd *ld,
struct connection *c) struct connection *c)
{ {
tal_free(c); tal_free(c);
@ -801,7 +800,6 @@ static void connect_failed(struct lightningd_state *dstate,
static void json_connect(struct command *cmd, static void json_connect(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct connection *c; struct connection *c;
jsmntok_t *host, *porttok, *idtok; jsmntok_t *host, *porttok, *idtok;
const tal_t *tmpctx = tal_tmpctx(cmd); const tal_t *tmpctx = tal_tmpctx(cmd);
@ -825,13 +823,13 @@ static void json_connect(struct command *cmd,
return; return;
} }
c = new_connection(cmd, ld, cmd, &id); c = new_connection(cmd, cmd->ld, cmd, &id);
name = tal_strndup(tmpctx, name = tal_strndup(tmpctx,
buffer + host->start, host->end - host->start); buffer + host->start, host->end - host->start);
port = tal_strndup(tmpctx, port = tal_strndup(tmpctx,
buffer + porttok->start, buffer + porttok->start,
porttok->end - porttok->start); porttok->end - porttok->start);
if (!dns_resolve_and_connect(cmd->dstate, name, port, if (!dns_resolve_and_connect(cmd->ld, name, port,
connection_out, connect_failed, c)) { connection_out, connect_failed, c)) {
command_fail(cmd, "DNS failed"); command_fail(cmd, "DNS failed");
return; return;
@ -851,7 +849,6 @@ AUTODATA(json_command, &connect_command);
static void json_dev_fail(struct command *cmd, static void json_dev_fail(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
jsmntok_t *peertok; jsmntok_t *peertok;
struct peer *peer; struct peer *peer;
@ -862,7 +859,7 @@ static void json_dev_fail(struct command *cmd,
return; return;
} }
peer = peer_from_json(ld, buffer, peertok); peer = peer_from_json(cmd->ld, buffer, peertok);
if (!peer) { if (!peer) {
command_fail(cmd, "Could not find peer with that id"); command_fail(cmd, "Could not find peer with that id");
return; return;
@ -903,7 +900,6 @@ static void log_to_json(unsigned int skipped,
static void json_getpeers(struct command *cmd, static void json_getpeers(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct peer *p; struct peer *p;
struct json_result *response = new_json_result(cmd); struct json_result *response = new_json_result(cmd);
jsmntok_t *leveltok; jsmntok_t *leveltok;
@ -928,7 +924,7 @@ static void json_getpeers(struct command *cmd,
json_object_start(response, NULL); json_object_start(response, NULL);
json_array_start(response, "peers"); json_array_start(response, "peers");
list_for_each(&ld->peers, p, list) { list_for_each(&cmd->ld->peers, p, list) {
json_object_start(response, NULL); json_object_start(response, NULL);
json_add_u64(response, "unique_id", p->unique_id); json_add_u64(response, "unique_id", p->unique_id);
json_add_string(response, "state", peer_state_name(p->state)); json_add_string(response, "state", peer_state_name(p->state));
@ -1207,7 +1203,7 @@ static u8 *p2wpkh_for_keyidx(const tal_t *ctx, struct lightningd *ld, u64 keyidx
{ {
struct pubkey shutdownkey; struct pubkey shutdownkey;
if (!bip32_pubkey(ld->bip32_base, &shutdownkey, keyidx)) if (!bip32_pubkey(ld->wallet->bip32_base, &shutdownkey, keyidx))
return NULL; return NULL;
return scriptpubkey_p2wpkh(ctx, &shutdownkey); return scriptpubkey_p2wpkh(ctx, &shutdownkey);
@ -1259,7 +1255,7 @@ static enum watch_result funding_spent(struct peer *peer,
return DELETE_WATCH; return DELETE_WATCH;
} }
if (!bip32_pubkey(peer->ld->bip32_base, &ourkey, keyindex)) { if (!bip32_pubkey(peer->ld->wallet->bip32_base, &ourkey, keyindex)) {
peer_internal_error(peer, peer_internal_error(peer,
"Can't get shutdown key %"PRIu64, "Can't get shutdown key %"PRIu64,
keyindex); keyindex);
@ -1392,7 +1388,7 @@ static void opening_got_hsm_funding_sig(struct funding_channel *fc,
for (i = 0; i < tal_count(tx->input); i++) { for (i = 0; i < tal_count(tx->input); i++) {
struct pubkey key; struct pubkey key;
if (!bip32_pubkey(fc->peer->ld->bip32_base, if (!bip32_pubkey(fc->peer->ld->wallet->bip32_base,
&key, fc->utxomap[i]->keyindex)) &key, fc->utxomap[i]->keyindex))
fatal("Cannot generate BIP32 key for UTXO %u", fatal("Cannot generate BIP32 key for UTXO %u",
fc->utxomap[i]->keyindex); fc->utxomap[i]->keyindex);
@ -1441,13 +1437,13 @@ static u8 *create_node_announcement(const tal_t *ctx, struct lightningd *ld,
sig = tal(ctx, secp256k1_ecdsa_signature); sig = tal(ctx, secp256k1_ecdsa_signature);
memset(sig, 0, sizeof(*sig)); memset(sig, 0, sizeof(*sig));
} }
if (ld->dstate.config.ipaddr.type != ADDR_TYPE_PADDING) { if (ld->config.ipaddr.type != ADDR_TYPE_PADDING) {
towire_ipaddr(&addresses, &ld->dstate.config.ipaddr); towire_ipaddr(&addresses, &ld->config.ipaddr);
} }
memset(alias, 0, sizeof(alias)); memset(alias, 0, sizeof(alias));
announcement = announcement =
towire_node_announcement(ctx, sig, features, timestamp, towire_node_announcement(ctx, sig, features, timestamp,
&ld->dstate.id, rgb, alias, addresses); &ld->id, rgb, alias, addresses);
return announcement; return announcement;
} }
@ -1938,7 +1934,7 @@ static bool peer_start_channeld(struct peer *peer,
const tal_t *tmpctx = tal_tmpctx(peer); const tal_t *tmpctx = tal_tmpctx(peer);
u8 *msg, *initmsg; u8 *msg, *initmsg;
int hsmfd; int hsmfd;
const struct config *cfg = &peer->ld->dstate.config; const struct config *cfg = &peer->ld->config;
struct added_htlc *htlcs; struct added_htlc *htlcs;
enum htlc_state *htlc_states; enum htlc_state *htlc_states;
struct fulfilled_htlc *fulfilled_htlcs; struct fulfilled_htlc *fulfilled_htlcs;
@ -2010,7 +2006,8 @@ static bool peer_start_channeld(struct peer *peer,
num_revocations = revocations_received(&peer->their_shachain.chain); num_revocations = revocations_received(&peer->their_shachain.chain);
initmsg = towire_channel_init(tmpctx, initmsg = towire_channel_init(tmpctx,
&peer->ld->chainparams->genesis_blockhash, &get_chainparams(peer->ld)
->genesis_blockhash,
peer->funding_txid, peer->funding_txid,
peer->funding_outnum, peer->funding_outnum,
peer->funding_satoshi, peer->funding_satoshi,
@ -2030,7 +2027,7 @@ static bool peer_start_channeld(struct peer *peer,
cfg->fee_per_satoshi, cfg->fee_per_satoshi,
*peer->our_msatoshi, *peer->our_msatoshi,
peer->seed, peer->seed,
&peer->ld->dstate.id, &peer->ld->id,
&peer->id, &peer->id,
time_to_msec(cfg->commit_time), time_to_msec(cfg->commit_time),
cfg->deadline_blocks, cfg->deadline_blocks,
@ -2115,7 +2112,7 @@ static bool opening_funder_finished(struct subd *opening, const u8 *resp,
/* Generate the funding tx. */ /* Generate the funding tx. */
if (fc->change if (fc->change
&& !bip32_pubkey(fc->peer->ld->bip32_base, && !bip32_pubkey(fc->peer->ld->wallet->bip32_base,
&changekey, fc->change_keyindex)) &changekey, fc->change_keyindex))
fatal("Error deriving change key %u", fc->change_keyindex); fatal("Error deriving change key %u", fc->change_keyindex);
@ -2126,7 +2123,7 @@ static bool opening_funder_finished(struct subd *opening, const u8 *resp,
&local_fundingkey, &local_fundingkey,
&channel_info->remote_fundingkey, &channel_info->remote_fundingkey,
fc->change, &changekey, fc->change, &changekey,
fc->peer->ld->bip32_base); fc->peer->ld->wallet->bip32_base);
fc->peer->funding_txid = tal(fc->peer, struct sha256_double); fc->peer->funding_txid = tal(fc->peer, struct sha256_double);
bitcoin_txid(fc->funding_tx, fc->peer->funding_txid); bitcoin_txid(fc->funding_tx, fc->peer->funding_txid);
@ -2253,8 +2250,8 @@ static void channel_config(struct lightningd *ld,
u64 *min_effective_htlc_capacity_msat) u64 *min_effective_htlc_capacity_msat)
{ {
/* FIXME: depend on feerate. */ /* FIXME: depend on feerate. */
*max_to_self_delay = ld->dstate.config.locktime_max; *max_to_self_delay = ld->config.locktime_max;
*max_minimum_depth = ld->dstate.config.anchor_confirms_max; *max_minimum_depth = ld->config.anchor_confirms_max;
/* This is 1c at $1000/BTC */ /* This is 1c at $1000/BTC */
*min_effective_htlc_capacity_msat = 1000000; *min_effective_htlc_capacity_msat = 1000000;
@ -2276,7 +2273,7 @@ static void channel_config(struct lightningd *ld,
* the sender can irreversibly spend a commitment transaction * the sender can irreversibly spend a commitment transaction
* output in case of misbehavior by the receiver. * output in case of misbehavior by the receiver.
*/ */
ours->to_self_delay = ld->dstate.config.locktime_blocks; ours->to_self_delay = ld->config.locktime_blocks;
/* BOLT #2: /* BOLT #2:
* *
@ -2332,7 +2329,7 @@ void peer_fundee_open(struct peer *peer, const u8 *from_peer,
* considers reasonable to avoid double-spending of the funding * considers reasonable to avoid double-spending of the funding
* transaction. * transaction.
*/ */
peer->minimum_depth = ld->dstate.config.anchor_confirms; peer->minimum_depth = ld->config.anchor_confirms;
channel_config(ld, &peer->our_config, channel_config(ld, &peer->our_config,
&max_to_self_delay, &max_minimum_depth, &max_to_self_delay, &max_minimum_depth,
@ -2348,7 +2345,7 @@ void peer_fundee_open(struct peer *peer, const u8 *from_peer,
peer->seed = tal(peer, struct privkey); peer->seed = tal(peer, struct privkey);
derive_peer_seed(ld, peer->seed, &peer->id, peer->channel->id); derive_peer_seed(ld, peer->seed, &peer->id, peer->channel->id);
msg = towire_opening_init(peer, ld->chainparams->index, msg = towire_opening_init(peer, get_chainparams(ld)->index,
&peer->our_config, &peer->our_config,
max_to_self_delay, max_to_self_delay,
min_effective_htlc_capacity_msat, min_effective_htlc_capacity_msat,
@ -2426,7 +2423,8 @@ static bool gossip_peer_released(struct subd *gossip,
fc->peer->channel_flags = OUR_CHANNEL_FLAGS; fc->peer->channel_flags = OUR_CHANNEL_FLAGS;
msg = towire_opening_init(fc, ld->chainparams->index, msg = towire_opening_init(fc,
get_chainparams(ld)->index,
&fc->peer->our_config, &fc->peer->our_config,
max_to_self_delay, max_to_self_delay,
min_effective_htlc_capacity_msat, min_effective_htlc_capacity_msat,
@ -2442,7 +2440,7 @@ static bool gossip_peer_released(struct subd *gossip,
15000, max_minimum_depth, 15000, max_minimum_depth,
fc->change, fc->change_keyindex, fc->change, fc->change_keyindex,
fc->peer->channel_flags, fc->peer->channel_flags,
utxos, fc->peer->ld->bip32_base); utxos, fc->peer->ld->wallet->bip32_base);
subd_req(fc, opening, take(msg), -1, 2, opening_funder_finished, fc); subd_req(fc, opening, take(msg), -1, 2, opening_funder_finished, fc);
return true; return true;
} }
@ -2450,7 +2448,6 @@ static bool gossip_peer_released(struct subd *gossip,
static void json_fund_channel(struct command *cmd, static void json_fund_channel(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
jsmntok_t *peertok, *satoshitok; jsmntok_t *peertok, *satoshitok;
struct funding_channel *fc = tal(cmd, struct funding_channel); struct funding_channel *fc = tal(cmd, struct funding_channel);
u8 *msg; u8 *msg;
@ -2464,12 +2461,12 @@ static void json_fund_channel(struct command *cmd,
} }
fc->cmd = cmd; fc->cmd = cmd;
fc->peer = peer_from_json(ld, buffer, peertok); fc->peer = peer_from_json(cmd->ld, buffer, peertok);
if (!fc->peer) { if (!fc->peer) {
command_fail(cmd, "Could not find peer with that peerid"); command_fail(cmd, "Could not find peer with that peerid");
return; return;
} }
if (fc->peer->owner != ld->gossip) { if (fc->peer->owner != cmd->ld->gossip) {
command_fail(cmd, "Peer not ready for connection"); command_fail(cmd, "Peer not ready for connection");
return; return;
} }
@ -2484,8 +2481,8 @@ static void json_fund_channel(struct command *cmd,
/* Try to do this now, so we know if insufficient funds. */ /* Try to do this now, so we know if insufficient funds. */
/* FIXME: Feerate & dustlimit */ /* FIXME: Feerate & dustlimit */
fc->utxomap = build_utxos(fc, ld, fc->peer->funding_satoshi, 15000, 600, fc->utxomap = build_utxos(fc, cmd->ld, fc->peer->funding_satoshi,
&fc->change, &fc->change_keyindex); 15000, 600, &fc->change, &fc->change_keyindex);
if (!fc->utxomap) { if (!fc->utxomap) {
command_fail(cmd, "Cannot afford funding transaction"); command_fail(cmd, "Cannot afford funding transaction");
return; return;
@ -2496,7 +2493,7 @@ static void json_fund_channel(struct command *cmd,
/* Tie this fc lifetime (and hence utxo release) to the peer */ /* Tie this fc lifetime (and hence utxo release) to the peer */
tal_steal(fc->peer, fc); tal_steal(fc->peer, fc);
tal_add_destructor(fc, fail_fundchannel_command); tal_add_destructor(fc, fail_fundchannel_command);
subd_req(fc, ld->gossip, msg, -1, 2, gossip_peer_released, fc); subd_req(fc, cmd->ld->gossip, msg, -1, 2, gossip_peer_released, fc);
} }
static const struct json_command fund_channel_command = { static const struct json_command fund_channel_command = {
@ -2510,7 +2507,6 @@ AUTODATA(json_command, &fund_channel_command);
static void json_close(struct command *cmd, static void json_close(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
jsmntok_t *peertok; jsmntok_t *peertok;
struct peer *peer; struct peer *peer;
@ -2521,7 +2517,7 @@ static void json_close(struct command *cmd,
return; return;
} }
peer = peer_from_json(ld, buffer, peertok); peer = peer_from_json(cmd->ld, buffer, peertok);
if (!peer) { if (!peer) {
command_fail(cmd, "Could not find peer with that id"); command_fail(cmd, "Could not find peer with that id");
return; return;

22
lightningd/peer_htlcs.c

@ -329,7 +329,7 @@ static void handle_localpay(struct htlc_in *hin,
goto fail; goto fail;
} }
invoice = find_unpaid(ld->dstate.invoices, payment_hash); invoice = find_unpaid(ld->invoices, payment_hash);
if (!invoice) { if (!invoice) {
failcode = WIRE_UNKNOWN_PAYMENT_HASH; failcode = WIRE_UNKNOWN_PAYMENT_HASH;
goto fail; goto fail;
@ -357,13 +357,13 @@ static void handle_localpay(struct htlc_in *hin,
* *
* If the `cltv_expiry` is too low, the final node MUST fail the HTLC: * If the `cltv_expiry` is too low, the final node MUST fail the HTLC:
*/ */
if (get_block_height(ld->topology) + ld->dstate.config.deadline_blocks if (get_block_height(ld->topology) + ld->config.deadline_blocks
>= cltv_expiry) { >= cltv_expiry) {
log_debug(hin->key.peer->log, log_debug(hin->key.peer->log,
"Expiry cltv %u too close to current %u + deadline %u", "Expiry cltv %u too close to current %u + deadline %u",
cltv_expiry, cltv_expiry,
get_block_height(ld->topology), get_block_height(ld->topology),
ld->dstate.config.deadline_blocks); ld->config.deadline_blocks);
failcode = WIRE_FINAL_EXPIRY_TOO_SOON; failcode = WIRE_FINAL_EXPIRY_TOO_SOON;
goto fail; goto fail;
} }
@ -371,7 +371,7 @@ static void handle_localpay(struct htlc_in *hin,
log_info(ld->log, "Resolving invoice '%s' with HTLC %"PRIu64, log_info(ld->log, "Resolving invoice '%s' with HTLC %"PRIu64,
invoice->label, hin->key.id); invoice->label, hin->key.id);
fulfill_htlc(hin, &invoice->r); fulfill_htlc(hin, &invoice->r);
resolve_invoice(&ld->dstate, invoice); resolve_invoice(ld, invoice);
return; return;
fail: fail:
@ -495,19 +495,19 @@ static void forward_htlc(struct htlc_in *hin,
* fee_base_msat + amount_msat * fee_proportional_millionths / 1000000 * fee_base_msat + amount_msat * fee_proportional_millionths / 1000000
*/ */
if (mul_overflows_u64(amt_to_forward, if (mul_overflows_u64(amt_to_forward,
ld->dstate.config.fee_per_satoshi)) { ld->config.fee_per_satoshi)) {
failcode = WIRE_FEE_INSUFFICIENT; failcode = WIRE_FEE_INSUFFICIENT;
goto fail; goto fail;
} }
fee = ld->dstate.config.fee_base fee = ld->config.fee_base
+ amt_to_forward * ld->dstate.config.fee_per_satoshi / 1000000; + amt_to_forward * ld->config.fee_per_satoshi / 1000000;
if (!check_amount(hin, amt_to_forward, hin->msatoshi, fee)) { if (!check_amount(hin, amt_to_forward, hin->msatoshi, fee)) {
failcode = WIRE_FEE_INSUFFICIENT; failcode = WIRE_FEE_INSUFFICIENT;
goto fail; goto fail;
} }
if (!check_ctlv(hin, cltv_expiry, outgoing_cltv_value, if (!check_ctlv(hin, cltv_expiry, outgoing_cltv_value,
ld->dstate.config.deadline_blocks)) { ld->config.deadline_blocks)) {
failcode = WIRE_INCORRECT_CLTV_EXPIRY; failcode = WIRE_INCORRECT_CLTV_EXPIRY;
goto fail; goto fail;
} }
@ -522,12 +522,12 @@ static void forward_htlc(struct htlc_in *hin,
* * [`len`:`channel_update`] * * [`len`:`channel_update`]
*/ */
if (get_block_height(next->ld->topology) if (get_block_height(next->ld->topology)
+ next->ld->dstate.config.deadline_blocks >= outgoing_cltv_value) { + next->ld->config.deadline_blocks >= outgoing_cltv_value) {
log_debug(hin->key.peer->log, log_debug(hin->key.peer->log,
"Expiry cltv %u too close to current %u + deadline %u", "Expiry cltv %u too close to current %u + deadline %u",
outgoing_cltv_value, outgoing_cltv_value,
get_block_height(next->ld->topology), get_block_height(next->ld->topology),
next->ld->dstate.config.deadline_blocks); next->ld->config.deadline_blocks);
failcode = WIRE_EXPIRY_TOO_SOON; failcode = WIRE_EXPIRY_TOO_SOON;
goto fail; goto fail;
} }
@ -576,7 +576,7 @@ static bool channel_resolve_reply(struct subd *gossip, const u8 *msg,
} }
/* Get the other peer matching the id that is not us */ /* Get the other peer matching the id that is not us */
if (pubkey_cmp(&nodes[0], &gossip->ld->dstate.id) == 0) { if (pubkey_cmp(&nodes[0], &gossip->ld->id) == 0) {
peer_id = &nodes[1]; peer_id = &nodes[1];
} else { } else {
peer_id = &nodes[0]; peer_id = &nodes[0];

2
lightningd/subd.c

@ -429,7 +429,7 @@ struct subd *new_subd(const tal_t *ctx,
return tal_free(sd); return tal_free(sd);
} }
sd->ld = ld; sd->ld = ld;
sd->log = new_log(sd, ld->dstate.log_book, "%s(%u):", name, sd->pid); sd->log = new_log(sd, ld->log_book, "%s(%u):", name, sd->pid);
sd->name = name; sd->name = name;
sd->finished = finished; sd->finished = finished;
sd->msgname = msgname; sd->msgname = msgname;

1
lightningd/watch.h

@ -10,7 +10,6 @@
struct bitcoin_tx; struct bitcoin_tx;
struct block; struct block;
struct lightningd_state;
enum watch_result { enum watch_result {
DELETE_WATCH = -1, DELETE_WATCH = -1,

32
wallet/walletrpc.c

@ -74,7 +74,7 @@ static void wallet_withdrawal_broadcast(struct bitcoind *bitcoind,
struct withdrawal *withdraw) struct withdrawal *withdraw)
{ {
struct command *cmd = withdraw->cmd; struct command *cmd = withdraw->cmd;
struct lightningd *ld = ld_from_dstate(withdraw->cmd->dstate); struct lightningd *ld = withdraw->cmd->ld;
struct bitcoin_tx *tx; struct bitcoin_tx *tx;
u64 change_satoshi = 0; u64 change_satoshi = 0;
@ -112,7 +112,6 @@ static void wallet_withdrawal_broadcast(struct bitcoind *bitcoind,
static void json_withdraw(struct command *cmd, static void json_withdraw(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
jsmntok_t *desttok, *sattok; jsmntok_t *desttok, *sattok;
struct withdrawal *withdraw; struct withdrawal *withdraw;
bool testnet; bool testnet;
@ -149,7 +148,8 @@ static void json_withdraw(struct command *cmd,
} }
/* Select the coins */ /* Select the coins */
withdraw->utxos = wallet_select_coins(cmd, ld->wallet, withdraw->amount, withdraw->utxos = wallet_select_coins(cmd, cmd->ld->wallet,
withdraw->amount,
feerate_per_kw, &fee_estimate, feerate_per_kw, &fee_estimate,
&withdraw->changesatoshi); &withdraw->changesatoshi);
if (!withdraw->utxos) { if (!withdraw->utxos) {
@ -161,7 +161,7 @@ static void json_withdraw(struct command *cmd,
if (withdraw->changesatoshi <= 546) if (withdraw->changesatoshi <= 546)
withdraw->changesatoshi = 0; withdraw->changesatoshi = 0;
withdraw->change_key_index = wallet_get_newindex(ld); withdraw->change_key_index = wallet_get_newindex(cmd->ld);
utxos = from_utxoptr_arr(withdraw, withdraw->utxos); utxos = from_utxoptr_arr(withdraw, withdraw->utxos);
u8 *msg = towire_hsmctl_sign_withdrawal(cmd, u8 *msg = towire_hsmctl_sign_withdrawal(cmd,
@ -172,17 +172,18 @@ static void json_withdraw(struct command *cmd,
utxos); utxos);
tal_free(utxos); tal_free(utxos);
if (!wire_sync_write(ld->hsm_fd, take(msg))) if (!wire_sync_write(cmd->ld->hsm_fd, take(msg)))
fatal("Could not write sign_withdrawal to HSM: %s", fatal("Could not write sign_withdrawal to HSM: %s",
strerror(errno)); strerror(errno));
msg = hsm_sync_read(cmd, ld); msg = hsm_sync_read(cmd, cmd->ld);
if (!fromwire_hsmctl_sign_withdrawal_reply(withdraw, msg, NULL, &sigs)) if (!fromwire_hsmctl_sign_withdrawal_reply(withdraw, msg, NULL, &sigs))
fatal("HSM gave bad sign_withdrawal_reply %s", fatal("HSM gave bad sign_withdrawal_reply %s",
tal_hex(withdraw, msg)); tal_hex(withdraw, msg));
if (bip32_key_from_parent(ld->bip32_base, withdraw->change_key_index, if (bip32_key_from_parent(cmd->ld->wallet->bip32_base,
withdraw->change_key_index,
BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) { BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) {
command_fail(cmd, "Changekey generation failure"); command_fail(cmd, "Changekey generation failure");
return; return;
@ -191,7 +192,7 @@ static void json_withdraw(struct command *cmd,
pubkey_from_der(ext.pub_key, sizeof(ext.pub_key), &changekey); pubkey_from_der(ext.pub_key, sizeof(ext.pub_key), &changekey);
tx = withdraw_tx(withdraw, withdraw->utxos, &withdraw->destination, tx = withdraw_tx(withdraw, withdraw->utxos, &withdraw->destination,
withdraw->amount, &changekey, withdraw->changesatoshi, withdraw->amount, &changekey, withdraw->changesatoshi,
ld->bip32_base); cmd->ld->wallet->bip32_base);
if (tal_count(sigs) != tal_count(tx->input)) if (tal_count(sigs) != tal_count(tx->input))
fatal("HSM gave %zu sigs, needed %zu", fatal("HSM gave %zu sigs, needed %zu",
@ -201,7 +202,7 @@ static void json_withdraw(struct command *cmd,
for (size_t i = 0; i < tal_count(tx->input); i++) { for (size_t i = 0; i < tal_count(tx->input); i++) {
struct pubkey key; struct pubkey key;
if (!bip32_pubkey(ld->bip32_base, if (!bip32_pubkey(cmd->ld->wallet->bip32_base,
&key, withdraw->utxos[i]->keyindex)) &key, withdraw->utxos[i]->keyindex))
fatal("Cannot generate BIP32 key for UTXO %u", fatal("Cannot generate BIP32 key for UTXO %u",
withdraw->utxos[i]->keyindex); withdraw->utxos[i]->keyindex);
@ -213,7 +214,7 @@ static void json_withdraw(struct command *cmd,
/* Now broadcast the transaction */ /* Now broadcast the transaction */
withdraw->hextx = tal_hex(withdraw, linearize_tx(cmd, tx)); withdraw->hextx = tal_hex(withdraw, linearize_tx(cmd, tx));
bitcoind_sendrawtx(ld->topology->bitcoind, withdraw->hextx, bitcoind_sendrawtx(cmd->ld->topology->bitcoind, withdraw->hextx,
wallet_withdrawal_broadcast, withdraw); wallet_withdrawal_broadcast, withdraw);
} }
@ -229,7 +230,6 @@ static void json_newaddr(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct json_result *response = new_json_result(cmd); struct json_result *response = new_json_result(cmd);
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct ext_key ext; struct ext_key ext;
struct sha256 h; struct sha256 h;
struct ripemd160 p2sh; struct ripemd160 p2sh;
@ -237,13 +237,13 @@ static void json_newaddr(struct command *cmd,
u8 *redeemscript; u8 *redeemscript;
s64 keyidx; s64 keyidx;
keyidx = wallet_get_newindex(ld); keyidx = wallet_get_newindex(cmd->ld);
if (keyidx < 0) { if (keyidx < 0) {
command_fail(cmd, "Keys exhausted "); command_fail(cmd, "Keys exhausted ");
return; return;
} }
if (bip32_key_from_parent(ld->bip32_base, keyidx, if (bip32_key_from_parent(cmd->ld->wallet->bip32_base, keyidx,
BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) { BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) {
command_fail(cmd, "Keys generation failure"); command_fail(cmd, "Keys generation failure");
return; return;
@ -261,7 +261,8 @@ static void json_newaddr(struct command *cmd,
json_object_start(response, NULL); json_object_start(response, NULL);
json_add_string(response, "address", json_add_string(response, "address",
p2sh_to_base58(cmd, cmd->dstate->testnet, &p2sh)); p2sh_to_base58(cmd, get_chainparams(cmd->ld)->testnet,
&p2sh));
json_object_end(response); json_object_end(response);
command_success(cmd, response); command_success(cmd, response);
} }
@ -277,7 +278,6 @@ AUTODATA(json_command, &newaddr_command);
static void json_addfunds(struct command *cmd, static void json_addfunds(struct command *cmd,
const char *buffer, const jsmntok_t *params) const char *buffer, const jsmntok_t *params)
{ {
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct json_result *response = new_json_result(cmd); struct json_result *response = new_json_result(cmd);
jsmntok_t *txtok; jsmntok_t *txtok;
struct bitcoin_tx *tx; struct bitcoin_tx *tx;
@ -301,7 +301,7 @@ static void json_addfunds(struct command *cmd,
/* Find an output we know how to spend. */ /* Find an output we know how to spend. */
num_utxos = num_utxos =
wallet_extract_owned_outputs(ld->wallet, tx, &total_satoshi); wallet_extract_owned_outputs(cmd->ld->wallet, tx, &total_satoshi);
if (num_utxos < 0) { if (num_utxos < 0) {
command_fail(cmd, "Could not add outputs to wallet"); command_fail(cmd, "Could not add outputs to wallet");
return; return;

Loading…
Cancel
Save