1 #include "bitcoin/block.h"
2 #include "bitcoin/feerate.h"
3 #include "bitcoin/script.h"
4 #include "bitcoin/tx.h"
5 #include "bitcoind.h"
6 #include "chaintopology.h"
7 #include "channel.h"
8 #include "jsonrpc.h"
9 #include "lightningd.h"
10 #include "log.h"
11 #include "watch.h"
12 #include <ccan/array_size/array_size.h>
13 #include <ccan/io/io.h>
14 #include <ccan/tal/str/str.h>
15 #include <common/htlc_tx.h>
16 #include <common/json_command.h>
17 #include <common/memleak.h>
18 #include <common/param.h>
19 #include <common/timeout.h>
20 #include <common/type_to_string.h>
21 #include <lightningd/coin_mvts.h>
22 #include <lightningd/gossip_control.h>
23 #include <lightningd/io_loop_with_timers.h>
24 #include <lightningd/json.h>
25 #include <math.h>
26 #include <wallet/txfilter.h>
27 
28 /* Mutual recursion via timer. */
29 static void try_extend_tip(struct chain_topology *topo);
30 
31 /* init_topo sets topo->root, start_fee_estimate clears
32  * feerate_uninitialized (even if unsuccessful) */
maybe_completed_init(struct chain_topology * topo)33 static void maybe_completed_init(struct chain_topology *topo)
34 {
35 	if (topo->feerate_uninitialized)
36 		return;
37 	if (!topo->root)
38 		return;
39 	io_break(topo);
40 }
41 
next_topology_timer(struct chain_topology * topo)42 static void next_topology_timer(struct chain_topology *topo)
43 {
44 	assert(!topo->extend_timer);
45 	topo->extend_timer = new_reltimer(topo->ld->timers, topo,
46 					  time_from_sec(topo->poll_seconds),
47 					  try_extend_tip, topo);
48 }
49 
we_broadcast(const struct chain_topology * topo,const struct bitcoin_txid * txid)50 static bool we_broadcast(const struct chain_topology *topo,
51 			 const struct bitcoin_txid *txid)
52 {
53 	const struct outgoing_tx *otx;
54 
55 	list_for_each(&topo->outgoing_txs, otx, list) {
56 		if (bitcoin_txid_eq(&otx->txid, txid))
57 			return true;
58 	}
59 	return false;
60 }
61 
filter_block_txs(struct chain_topology * topo,struct block * b)62 static void filter_block_txs(struct chain_topology *topo, struct block *b)
63 {
64 	size_t i;
65 	struct amount_sat owned;
66 
67 	/* Now we see if any of those txs are interesting. */
68 	for (i = 0; i < tal_count(b->full_txs); i++) {
69 		const struct bitcoin_tx *tx = b->full_txs[i];
70 		struct bitcoin_txid txid;
71 		size_t j;
72 
73 		/* Tell them if it spends a txo we care about. */
74 		for (j = 0; j < tx->wtx->num_inputs; j++) {
75 			struct bitcoin_outpoint out;
76 			struct txowatch *txo;
77 			bitcoin_tx_input_get_txid(tx, j, &out.txid);
78 			out.n = tx->wtx->inputs[j].index;
79 
80 			txo = txowatch_hash_get(&topo->txowatches, &out);
81 			if (txo) {
82 				wallet_transaction_add(topo->ld->wallet,
83 						       tx->wtx, b->height, i);
84 				txowatch_fire(txo, tx, j, b);
85 			}
86 		}
87 
88 		owned = AMOUNT_SAT(0);
89 		txid = b->txids[i];
90 		if (txfilter_match(topo->bitcoind->ld->owned_txfilter, tx)) {
91 			wallet_extract_owned_outputs(topo->bitcoind->ld->wallet,
92 						     tx->wtx, &b->height, &owned);
93 			wallet_transaction_add(topo->ld->wallet, tx->wtx,
94 					       b->height, i);
95 		}
96 
97 		/* We did spends first, in case that tells us to watch tx. */
98 		if (watching_txid(topo, &txid) || we_broadcast(topo, &txid)) {
99 			wallet_transaction_add(topo->ld->wallet,
100 					       tx->wtx, b->height, i);
101 		}
102 
103 		txwatch_inform(topo, &txid, tx);
104 	}
105 	b->full_txs = tal_free(b->full_txs);
106 	b->txids = tal_free(b->txids);
107 }
108 
get_tx_depth(const struct chain_topology * topo,const struct bitcoin_txid * txid)109 size_t get_tx_depth(const struct chain_topology *topo,
110 		    const struct bitcoin_txid *txid)
111 {
112 	u32 blockheight = wallet_transaction_height(topo->ld->wallet, txid);
113 
114 	if (blockheight == 0)
115 		return 0;
116 	return topo->tip->height - blockheight + 1;
117 }
118 
119 struct txs_to_broadcast {
120 	/* We just sent txs[cursor] */
121 	size_t cursor;
122 	/* These are hex encoded already, for bitcoind_sendrawtx */
123 	const char **txs;
124 
125 	/* Command to complete when we're done, if and only if dev-broadcast triggered */
126 	struct command *cmd;
127 };
128 
129 /* We just sent the last entry in txs[].  Shrink and send the next last. */
broadcast_remainder(struct bitcoind * bitcoind,bool success,const char * msg,struct txs_to_broadcast * txs)130 static void broadcast_remainder(struct bitcoind *bitcoind,
131 				bool success, const char *msg,
132 				struct txs_to_broadcast *txs)
133 {
134 	if (!success)
135 		log_debug(bitcoind->log,
136 			  "Expected error broadcasting tx %s: %s",
137 			  txs->txs[txs->cursor], msg);
138 
139 	txs->cursor++;
140 	if (txs->cursor == tal_count(txs->txs)) {
141 		if (txs->cmd)
142 			was_pending(command_success(txs->cmd,
143 						    json_stream_success(txs->cmd)));
144 		tal_free(txs);
145 		return;
146 	}
147 
148 	/* Broadcast next one. */
149 	bitcoind_sendrawtx(bitcoind, txs->txs[txs->cursor],
150 			   broadcast_remainder, txs);
151 }
152 
153 /* FIXME: This is dumb.  We can group txs and avoid bothering bitcoind
154  * if any one tx is in the main chain. */
rebroadcast_txs(struct chain_topology * topo,struct command * cmd)155 static void rebroadcast_txs(struct chain_topology *topo, struct command *cmd)
156 {
157 	/* Copy txs now (peers may go away, and they own txs). */
158 	struct txs_to_broadcast *txs;
159 	struct outgoing_tx *otx;
160 
161 	txs = tal(topo, struct txs_to_broadcast);
162 	txs->cmd = cmd;
163 
164 	/* Put any txs we want to broadcast in ->txs. */
165 	txs->txs = tal_arr(txs, const char *, 0);
166 	list_for_each(&topo->outgoing_txs, otx, list) {
167 		if (wallet_transaction_height(topo->ld->wallet, &otx->txid))
168 			continue;
169 
170 		tal_arr_expand(&txs->txs, tal_strdup(txs, otx->hextx));
171 	}
172 
173 	/* Let this do the dirty work. */
174 	txs->cursor = (size_t)-1;
175 	broadcast_remainder(topo->bitcoind, true, "", txs);
176 }
177 
destroy_outgoing_tx(struct outgoing_tx * otx)178 static void destroy_outgoing_tx(struct outgoing_tx *otx)
179 {
180 	list_del(&otx->list);
181 }
182 
clear_otx_channel(struct channel * channel,struct outgoing_tx * otx)183 static void clear_otx_channel(struct channel *channel, struct outgoing_tx *otx)
184 {
185 	if (otx->channel != channel)
186 		fatal("channel %p, otx %p has channel %p", channel, otx, otx->channel);
187 	otx->channel = NULL;
188 }
189 
broadcast_done(struct bitcoind * bitcoind,bool success,const char * msg,struct outgoing_tx * otx)190 static void broadcast_done(struct bitcoind *bitcoind,
191 			   bool success, const char *msg,
192 			   struct outgoing_tx *otx)
193 {
194 	/* Channel gone?  Stop. */
195 	if (!otx->channel) {
196 		tal_free(otx);
197 		return;
198 	}
199 
200 	/* No longer needs to be disconnected if channel dies. */
201 	tal_del_destructor2(otx->channel, clear_otx_channel, otx);
202 
203 	if (otx->failed_or_success) {
204 		otx->failed_or_success(otx->channel, success, msg);
205 		tal_free(otx);
206 	} else {
207 		/* For continual rebroadcasting, until channel freed. */
208 		tal_steal(otx->channel, otx);
209 		list_add_tail(&bitcoind->ld->topology->outgoing_txs, &otx->list);
210 		tal_add_destructor(otx, destroy_outgoing_tx);
211 	}
212 }
213 
broadcast_tx_ahf(struct chain_topology * topo,struct channel * channel,const struct bitcoin_tx * tx,bool allowhighfees,void (* failed)(struct channel * channel,bool success,const char * err))214 void broadcast_tx_ahf(struct chain_topology *topo,
215 		      struct channel *channel, const struct bitcoin_tx *tx,
216 		      bool allowhighfees,
217 		      void (*failed)(struct channel *channel,
218 				     bool success,
219 				     const char *err))
220 {
221 	/* Channel might vanish: topo owns it to start with. */
222 	struct outgoing_tx *otx = tal(topo, struct outgoing_tx);
223 	const u8 *rawtx = linearize_tx(otx, tx);
224 
225 	otx->channel = channel;
226 	bitcoin_txid(tx, &otx->txid);
227 	otx->hextx = tal_hex(otx, rawtx);
228 	otx->failed_or_success = failed;
229 	tal_free(rawtx);
230 	tal_add_destructor2(channel, clear_otx_channel, otx);
231 
232 	log_debug(topo->log, "Broadcasting txid %s",
233 		  type_to_string(tmpctx, struct bitcoin_txid, &otx->txid));
234 
235 	wallet_transaction_add(topo->ld->wallet, tx->wtx, 0, 0);
236 	bitcoind_sendrawtx_ahf(topo->bitcoind, otx->hextx, allowhighfees,
237 			       broadcast_done, otx);
238 }
broadcast_tx(struct chain_topology * topo,struct channel * channel,const struct bitcoin_tx * tx,void (* failed)(struct channel * channel,bool success,const char * err))239 void broadcast_tx(struct chain_topology *topo,
240 		  struct channel *channel, const struct bitcoin_tx *tx,
241 		  void (*failed)(struct channel *channel,
242 				 bool success,
243 				 const char *err))
244 {
245 	return broadcast_tx_ahf(topo, channel, tx, false, failed);
246 }
247 
248 
closeinfo_txid_confirmed(struct lightningd * ld,struct channel * channel,const struct bitcoin_txid * txid,const struct bitcoin_tx * tx,unsigned int depth)249 static enum watch_result closeinfo_txid_confirmed(struct lightningd *ld,
250 						  struct channel *channel,
251 						  const struct bitcoin_txid *txid,
252 						  const struct bitcoin_tx *tx,
253 						  unsigned int depth)
254 {
255 	/* Sanity check. */
256 	if (tx != NULL) {
257 		struct bitcoin_txid txid2;
258 
259 		bitcoin_txid(tx, &txid2);
260 		if (!bitcoin_txid_eq(txid, &txid2)) {
261 			channel_internal_error(channel, "Txid for %s is not %s",
262 					       type_to_string(tmpctx,
263 							      struct bitcoin_tx,
264 							      tx),
265 					       type_to_string(tmpctx,
266 							      struct bitcoin_txid,
267 							      txid));
268 			return DELETE_WATCH;
269 		}
270 	}
271 
272 	/* We delete ourselves first time, so should not be reorged out!! */
273 	assert(depth > 0);
274 	/* Subtle: depth 1 == current block. */
275 	wallet_confirm_tx(ld->wallet, txid,
276 			  get_block_height(ld->topology) + 1 - depth);
277 	return DELETE_WATCH;
278 }
279 
280 /* We need to know if close_info UTXOs (which the wallet doesn't natively know
281  * how to spend, so is not in the normal path) get reconfirmed.
282  *
283  * This can happen on startup (where we manually unwind 100 blocks) or on a
284  * reorg.  The db NULLs out the confirmation_height, so we can't easily figure
285  * out just the new ones (and removing the ON DELETE SET NULL clause is
286  * non-trivial).
287  *
288  * So every time, we just set a notification for every tx in this class we're
289  * not already watching: there are not usually many, nor many reorgs, so the
290  * redundancy is OK.
291  */
watch_for_utxo_reconfirmation(struct chain_topology * topo,struct wallet * wallet)292 static void watch_for_utxo_reconfirmation(struct chain_topology *topo,
293 					  struct wallet *wallet)
294 {
295 	struct utxo **unconfirmed;
296 
297 	unconfirmed = wallet_get_unconfirmed_closeinfo_utxos(tmpctx, wallet);
298 	for (size_t i = 0; i < tal_count(unconfirmed); i++) {
299 		assert(unconfirmed[i]->close_info != NULL);
300 		assert(unconfirmed[i]->blockheight == NULL);
301 
302 		if (find_txwatch(topo, &unconfirmed[i]->outpoint.txid, NULL))
303 			continue;
304 
305 		notleak(watch_txid(topo, topo, NULL,
306 				   &unconfirmed[i]->outpoint.txid,
307 				   closeinfo_txid_confirmed));
308 	}
309 }
310 
feerate_name(enum feerate feerate)311 const char *feerate_name(enum feerate feerate)
312 {
313 	switch (feerate) {
314 	case FEERATE_OPENING: return "opening";
315 	case FEERATE_MUTUAL_CLOSE: return "mutual_close";
316 	case FEERATE_UNILATERAL_CLOSE: return "unilateral_close";
317 	case FEERATE_DELAYED_TO_US: return "delayed_to_us";
318 	case FEERATE_HTLC_RESOLUTION: return "htlc_resolution";
319 	case FEERATE_PENALTY: return "penalty";
320 	case FEERATE_MIN: return "min_acceptable";
321 	case FEERATE_MAX: return "max_acceptable";
322 	}
323 	abort();
324 }
325 
param_feerate_estimate(struct command * cmd,u32 ** feerate_per_kw,enum feerate feerate)326 struct command_result *param_feerate_estimate(struct command *cmd,
327 					      u32 **feerate_per_kw,
328 					      enum feerate feerate)
329 {
330 	*feerate_per_kw = tal(cmd, u32);
331 	**feerate_per_kw = try_get_feerate(cmd->ld->topology, feerate);
332 	if (!**feerate_per_kw)
333 		return command_fail(cmd, LIGHTNINGD, "Cannot estimate fees");
334 
335 	return NULL;
336 }
337 
338 /* Mutual recursion via timer. */
339 static void next_updatefee_timer(struct chain_topology *topo);
340 
init_feerate_history(struct chain_topology * topo,enum feerate feerate,u32 val)341 static void init_feerate_history(struct chain_topology *topo,
342 				 enum feerate feerate, u32 val)
343 {
344 	for (size_t i = 0; i < FEE_HISTORY_NUM; i++)
345 		topo->feehistory[feerate][i] = val;
346 }
347 
add_feerate_history(struct chain_topology * topo,enum feerate feerate,u32 val)348 static void add_feerate_history(struct chain_topology *topo,
349 				enum feerate feerate, u32 val)
350 {
351 	memmove(&topo->feehistory[feerate][1], &topo->feehistory[feerate][0],
352 		(FEE_HISTORY_NUM - 1) * sizeof(u32));
353 	topo->feehistory[feerate][0] = val;
354 }
355 
356 /* We sanitize feerates if necessary to put them in descending order. */
update_feerates(struct bitcoind * bitcoind,const u32 * satoshi_per_kw,struct chain_topology * topo)357 static void update_feerates(struct bitcoind *bitcoind,
358 			    const u32 *satoshi_per_kw,
359 			    struct chain_topology *topo)
360 {
361 	u32 old_feerates[NUM_FEERATES];
362 	/* Smoothing factor alpha for simple exponential smoothing. The goal is to
363 	 * have the feerate account for 90 percent of the values polled in the last
364 	 * 2 minutes. The following will do that in a polling interval
365 	 * independent manner. */
366 	double alpha = 1 - pow(0.1,(double)topo->poll_seconds / 120);
367 	bool feerate_changed = false;
368 
369 	for (size_t i = 0; i < NUM_FEERATES; i++) {
370 		u32 feerate = satoshi_per_kw[i];
371 
372 		/* Takes into account override_fee_rate */
373 		old_feerates[i] = try_get_feerate(topo, i);
374 
375 		/* If estimatefee failed, don't do anything. */
376 		if (!feerate)
377 			continue;
378 
379 		/* Initial smoothed feerate is the polled feerate */
380 		if (!old_feerates[i]) {
381 			feerate_changed = true;
382 			old_feerates[i] = feerate;
383 			init_feerate_history(topo, i, feerate);
384 
385 			log_debug(topo->log,
386 					  "Smoothed feerate estimate for %s initialized to polled estimate %u",
387 					  feerate_name(i), feerate);
388 		} else {
389 			if (feerate != old_feerates[i])
390 				feerate_changed = true;
391 			add_feerate_history(topo, i, feerate);
392 		}
393 
394 		/* Smooth the feerate to avoid spikes. */
395 		u32 feerate_smooth = feerate * alpha + old_feerates[i] * (1 - alpha);
396 		/* But to avoid updating forever, only apply smoothing when its
397 		 * effect is more then 10 percent */
398 		if (abs((int)feerate - (int)feerate_smooth) > (0.1 * feerate)) {
399 			feerate = feerate_smooth;
400 			log_debug(topo->log,
401 					  "... polled feerate estimate for %s (%u) smoothed to %u (alpha=%.2f)",
402 					  feerate_name(i), satoshi_per_kw[i],
403 					  feerate, alpha);
404 		}
405 
406 		if (feerate < feerate_floor()) {
407 			feerate = feerate_floor();
408 			log_debug(topo->log,
409 					  "... feerate estimate for %s hit floor %u",
410 					  feerate_name(i), feerate);
411 		}
412 
413 		if (feerate != topo->feerate[i]) {
414 			log_debug(topo->log, "Feerate estimate for %s set to %u (was %u)",
415 				  feerate_name(i),
416 				  feerate, topo->feerate[i]);
417 		}
418 		topo->feerate[i] = feerate;
419 	}
420 
421 	if (topo->feerate_uninitialized) {
422 		/* This doesn't mean we *have* a fee estimate, but it does
423 		 * mean we tried. */
424 		topo->feerate_uninitialized = false;
425 		maybe_completed_init(topo);
426 	}
427 
428 	if (feerate_changed)
429 		notify_feerate_change(bitcoind->ld);
430 
431 	next_updatefee_timer(topo);
432 }
433 
start_fee_estimate(struct chain_topology * topo)434 static void start_fee_estimate(struct chain_topology *topo)
435 {
436 	topo->updatefee_timer = NULL;
437 	if (topo->stopping)
438 		return;
439 	/* Once per new block head, update fee estimates. */
440 	bitcoind_estimate_fees(topo->bitcoind, NUM_FEERATES, update_feerates,
441 			       topo);
442 }
443 
opening_feerate(struct chain_topology * topo)444 u32 opening_feerate(struct chain_topology *topo)
445 {
446 	return try_get_feerate(topo, FEERATE_OPENING);
447 }
448 
mutual_close_feerate(struct chain_topology * topo)449 u32 mutual_close_feerate(struct chain_topology *topo)
450 {
451 	return try_get_feerate(topo, FEERATE_MUTUAL_CLOSE);
452 }
453 
unilateral_feerate(struct chain_topology * topo)454 u32 unilateral_feerate(struct chain_topology *topo)
455 {
456 	return try_get_feerate(topo, FEERATE_UNILATERAL_CLOSE);
457 }
458 
delayed_to_us_feerate(struct chain_topology * topo)459 u32 delayed_to_us_feerate(struct chain_topology *topo)
460 {
461 	return try_get_feerate(topo, FEERATE_DELAYED_TO_US);
462 }
463 
htlc_resolution_feerate(struct chain_topology * topo)464 u32 htlc_resolution_feerate(struct chain_topology *topo)
465 {
466 	return try_get_feerate(topo, FEERATE_HTLC_RESOLUTION);
467 }
468 
penalty_feerate(struct chain_topology * topo)469 u32 penalty_feerate(struct chain_topology *topo)
470 {
471 	return try_get_feerate(topo, FEERATE_PENALTY);
472 }
473 
json_feerates(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)474 static struct command_result *json_feerates(struct command *cmd,
475 					    const char *buffer,
476 					    const jsmntok_t *obj UNNEEDED,
477 					    const jsmntok_t *params)
478 {
479 	struct chain_topology *topo = cmd->ld->topology;
480 	struct json_stream *response;
481 	u32 feerates[NUM_FEERATES];
482 	bool missing;
483 	enum feerate_style *style;
484 
485 	if (!param(cmd, buffer, params,
486 		   p_req("style", param_feerate_style, &style),
487 		   NULL))
488 		return command_param_failed();
489 
490 	missing = false;
491 	for (size_t i = 0; i < ARRAY_SIZE(feerates); i++) {
492 		feerates[i] = try_get_feerate(topo, i);
493 		if (!feerates[i])
494 			missing = true;
495 	}
496 
497 	response = json_stream_success(cmd);
498 
499 	if (missing)
500 		json_add_string(response, "warning_missing_feerates",
501 				"Some fee estimates unavailable: bitcoind startup?");
502 
503 	json_object_start(response, feerate_style_name(*style));
504 	for (size_t i = 0; i < ARRAY_SIZE(feerates); i++) {
505 		if (!feerates[i] || i == FEERATE_MIN || i == FEERATE_MAX)
506 			continue;
507 		json_add_num(response, feerate_name(i),
508 			     feerate_to_style(feerates[i], *style));
509 	}
510 	json_add_u64(response, "min_acceptable",
511 		     feerate_to_style(feerate_min(cmd->ld, NULL), *style));
512 	json_add_u64(response, "max_acceptable",
513 		     feerate_to_style(feerate_max(cmd->ld, NULL), *style));
514 	json_object_end(response);
515 
516 	if (!missing) {
517 		/* It actually is negotiated per-channel... */
518 		bool anchor_outputs
519 			= feature_offered(cmd->ld->our_features->bits[INIT_FEATURE],
520 					  OPT_ANCHOR_OUTPUTS);
521 
522 		json_object_start(response, "onchain_fee_estimates");
523 		/* eg 020000000001016f51de645a47baa49a636b8ec974c28bdff0ac9151c0f4eda2dbe3b41dbe711d000000001716001401fad90abcd66697e2592164722de4a95ebee165ffffffff0240420f00000000002200205b8cd3b914cf67cdd8fa6273c930353dd36476734fbd962102c2df53b90880cdb73f890000000000160014c2ccab171c2a5be9dab52ec41b825863024c54660248304502210088f65e054dbc2d8f679de3e40150069854863efa4a45103b2bb63d060322f94702200d3ae8923924a458cffb0b7360179790830027bb6b29715ba03e12fc22365de1012103d745445c9362665f22e0d96e9e766f273f3260dea39c8a76bfa05dd2684ddccf00000000 == weight 702 */
524 		json_add_num(response, "opening_channel_satoshis",
525 			     opening_feerate(cmd->ld->topology) * 702 / 1000);
526 		/* eg. 02000000000101afcfac637d44d4e0df52031dba55b18d3f1bd79ad4b7ebbee964f124c5163dc30100000000ffffffff02400d03000000000016001427213e2217b4f56bd19b6c8393dc9f61be691233ca1f0c0000000000160014071c49cad2f420f3c805f9f6b98a57269cb1415004004830450221009a12b4d5ae1d41781f79bedecfa3e65542b1799a46c272287ba41f009d2e27ff0220382630c899207487eba28062f3989c4b656c697c23a8c89c1d115c98d82ff261014730440220191ddf13834aa08ea06dca8191422e85d217b065462d1b405b665eefa0684ed70220252409bf033eeab3aae89ae27596d7e0491bcc7ae759c5644bced71ef3cccef30147522102324266de8403b3ab157a09f1f784d587af61831c998c151bcc21bb74c2b2314b2102e3bd38009866c9da8ec4aa99cc4ea9c6c0dd46df15c61ef0ce1f271291714e5752ae00000000 == weight 673 */
527 		json_add_u64(response, "mutual_close_satoshis",
528 			     mutual_close_feerate(cmd->ld->topology) * 673 / 1000);
529 		/* eg. 02000000000101c4fecaae1ea940c15ec502de732c4c386d51f981317605bbe5ad2c59165690ab00000000009db0e280010a2d0f00000000002200208d290003cedb0dd00cd5004c2d565d55fc70227bf5711186f4fa9392f8f32b4a0400483045022100952fcf8c730c91cf66bcb742cd52f046c0db3694dc461e7599be330a22466d790220740738a6f9d9e1ae5c86452fa07b0d8dddc90f8bee4ded24a88fe4b7400089eb01483045022100db3002a93390fc15c193da57d6ce1020e82705e760a3aa935ebe864bd66dd8e8022062ee9c6aa7b88ff4580e2671900a339754116371d8f40eba15b798136a76cd150147522102324266de8403b3ab157a09f1f784d587af61831c998c151bcc21bb74c2b2314b2102e3bd38009866c9da8ec4aa99cc4ea9c6c0dd46df15c61ef0ce1f271291714e5752ae9a3ed620 == weight 598 */
530 		json_add_u64(response, "unilateral_close_satoshis",
531 			     unilateral_feerate(cmd->ld->topology) * 598 / 1000);
532 
533 		/* This really depends on whether we *negotiated*
534 		 * option_anchor_outputs for a particular channel! */
535 		json_add_u64(response, "htlc_timeout_satoshis",
536 			     htlc_timeout_fee(htlc_resolution_feerate(cmd->ld->topology),
537 					      anchor_outputs).satoshis /* Raw: estimate */);
538 		json_add_u64(response, "htlc_success_satoshis",
539 			     htlc_success_fee(htlc_resolution_feerate(cmd->ld->topology),
540 					      anchor_outputs).satoshis /* Raw: estimate */);
541 		json_object_end(response);
542 	}
543 
544 	return command_success(cmd, response);
545 }
546 
547 static const struct json_command feerates_command = {
548 	"feerates",
549 	"bitcoin",
550 	json_feerates,
551 	"Return feerate estimates, either satoshi-per-kw ({style} perkw) or satoshi-per-kb ({style} perkb)."
552 };
553 AUTODATA(json_command, &feerates_command);
554 
json_parse_feerate(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)555 static struct command_result *json_parse_feerate(struct command *cmd,
556 						 const char *buffer,
557 						 const jsmntok_t *obj UNNEEDED,
558 						 const jsmntok_t *params)
559 {
560 	struct json_stream *response;
561 	u32 *feerate;
562 
563 	if (!param(cmd, buffer, params,
564 		   p_req("feerate", param_feerate, &feerate),
565 		   NULL))
566 		return command_param_failed();
567 
568 	response = json_stream_success(cmd);
569 	json_add_num(response, feerate_style_name(FEERATE_PER_KSIPA),
570 		     feerate_to_style(*feerate, FEERATE_PER_KSIPA));
571 	return command_success(cmd, response);
572 }
573 
574 static const struct json_command parse_feerate_command = {
575 	"parsefeerate",
576 	"bitcoin",
577 	json_parse_feerate,
578 	"Return current feerate in perkw + perkb for given feerate string."
579 };
580 AUTODATA(json_command, &parse_feerate_command);
581 
next_updatefee_timer(struct chain_topology * topo)582 static void next_updatefee_timer(struct chain_topology *topo)
583 {
584 	assert(!topo->updatefee_timer);
585 	topo->updatefee_timer = new_reltimer(topo->ld->timers, topo,
586 					     time_from_sec(topo->poll_seconds),
587 					     start_fee_estimate, topo);
588 }
589 
590 struct sync_waiter {
591 	/* Linked from chain_topology->sync_waiters */
592 	struct list_node list;
593 	void (*cb)(struct chain_topology *topo, void *arg);
594 	void *arg;
595 };
596 
destroy_sync_waiter(struct sync_waiter * waiter)597 static void destroy_sync_waiter(struct sync_waiter *waiter)
598 {
599 	list_del(&waiter->list);
600 }
601 
topology_add_sync_waiter_(const tal_t * ctx,struct chain_topology * topo,void (* cb)(struct chain_topology * topo,void * arg),void * arg)602 void topology_add_sync_waiter_(const tal_t *ctx,
603 			       struct chain_topology *topo,
604 			       void (*cb)(struct chain_topology *topo,
605 					  void *arg),
606 			       void *arg)
607 {
608 	struct sync_waiter *w = tal(ctx, struct sync_waiter);
609 	w->cb = cb;
610 	w->arg = arg;
611 	list_add_tail(topo->sync_waiters, &w->list);
612 	tal_add_destructor(w, destroy_sync_waiter);
613 }
614 
615 /* Once we're run out of new blocks to add, call this. */
updates_complete(struct chain_topology * topo)616 static void updates_complete(struct chain_topology *topo)
617 {
618 	if (!bitcoin_blkid_eq(&topo->tip->blkid, &topo->prev_tip)) {
619 		/* Tell lightningd about new block. */
620 		notify_new_block(topo->bitcoind->ld, topo->tip->height);
621 
622 		/* Tell watch code to re-evaluate all txs. */
623 		watch_topology_changed(topo);
624 
625 		/* Maybe need to rebroadcast. */
626 		rebroadcast_txs(topo, NULL);
627 
628 		/* We've processed these UTXOs */
629 		db_set_intvar(topo->bitcoind->ld->wallet->db,
630 			      "last_processed_block", topo->tip->height);
631 
632 		topo->prev_tip = topo->tip->blkid;
633 	}
634 
635 	/* If bitcoind is synced, we're now synced. */
636 	if (topo->bitcoind->synced && !topology_synced(topo)) {
637 		struct sync_waiter *w;
638 		struct list_head *list = topo->sync_waiters;
639 
640 		/* Mark topology_synced() before callbacks. */
641 		topo->sync_waiters = NULL;
642 
643 		while ((w = list_pop(list, struct sync_waiter, list))) {
644 			/* In case it doesn't free itself. */
645 			tal_del_destructor(w, destroy_sync_waiter);
646 			tal_steal(list, w);
647 			w->cb(topo, w->arg);
648 		}
649 		tal_free(list);
650 	}
651 
652 	/* Try again soon. */
653 	next_topology_timer(topo);
654 }
655 
record_utxo_spent(struct lightningd * ld,const struct bitcoin_txid * txid,const struct bitcoin_outpoint * outpoint,u32 blockheight,struct amount_sat * input_amt)656 static void record_utxo_spent(struct lightningd *ld,
657 			      const struct bitcoin_txid *txid,
658 			      const struct bitcoin_outpoint *outpoint,
659 			      u32 blockheight,
660 			      struct amount_sat *input_amt)
661 {
662 	struct utxo *utxo;
663 	struct chain_coin_mvt *mvt;
664 	u8 *ctx = tal(NULL, u8);
665 
666 	utxo = wallet_utxo_get(ctx, ld->wallet, outpoint);
667 	if (!utxo) {
668 		log_broken(ld->log, "No record of utxo %s",
669 			    type_to_string(tmpctx, struct bitcoin_outpoint,
670 					   outpoint));
671 		return;
672 	}
673 
674 	*input_amt = utxo->amount;
675 	mvt = new_coin_spend_track(ctx, txid, outpoint, blockheight);
676 	notify_chain_mvt(ld, mvt);
677 	tal_free(ctx);
678 }
679 
record_outputs_as_withdraws(const tal_t * ctx,struct lightningd * ld,const struct bitcoin_tx * tx,const struct bitcoin_txid * txid,u32 blockheight)680 static void record_outputs_as_withdraws(const tal_t *ctx,
681 					struct lightningd *ld,
682 					const struct bitcoin_tx *tx,
683 					const struct bitcoin_txid *txid,
684 					u32 blockheight)
685 {
686 	struct chain_coin_mvt *mvt;
687 	struct bitcoin_outpoint outpoint;
688 
689 	outpoint.txid = *txid;
690 	for (outpoint.n = 0; outpoint.n < tx->wtx->num_outputs; outpoint.n++) {
691 		struct amount_asset asset;
692 		struct amount_sat outval;
693 		if (elements_tx_output_is_fee(tx, outpoint.n))
694 			continue;
695 		asset = bitcoin_tx_output_get_amount(tx, outpoint.n);
696 		assert(amount_asset_is_main(&asset));
697 		outval = amount_asset_to_sat(&asset);
698 		mvt = new_coin_withdrawal_sat(ctx, "wallet", txid,
699 					      &outpoint, blockheight,
700 					      outval);
701 		notify_chain_mvt(ld, mvt);
702 	}
703 }
704 
record_tx_outs_and_fees(struct lightningd * ld,const struct bitcoin_tx * tx,const struct bitcoin_txid * txid,u32 blockheight,struct amount_sat inputs_total,bool our_tx)705 static void record_tx_outs_and_fees(struct lightningd *ld,
706 				    const struct bitcoin_tx *tx,
707 				    const struct bitcoin_txid *txid,
708 				    u32 blockheight,
709 				    struct amount_sat inputs_total,
710 				    bool our_tx)
711 {
712 	struct amount_sat fee, out_val;
713 	struct chain_coin_mvt *mvt;
714 	bool ok;
715 	struct wally_psbt *psbt = NULL;
716 	u8 *ctx = tal(NULL, u8);
717 
718 	/* We own every input on this tx, so track withdrawals precisely */
719 	if (our_tx) {
720 		record_outputs_as_withdraws(ctx, ld, tx, txid, blockheight);
721 		fee = bitcoin_tx_compute_fee_w_inputs(tx, inputs_total);
722 		goto log_fee;
723 	}
724 
725 	/* FIXME: look up stashed psbt! */
726 	if (!psbt) {
727 		fee = bitcoin_tx_compute_fee_w_inputs(tx, inputs_total);
728 		ok = amount_sat_sub(&out_val, inputs_total, fee);
729 		assert(ok);
730 
731 		/* We don't have detailed withdrawal info for this tx,
732 		 * so we log the wallet withdrawal as a single entry */
733 		mvt = new_coin_withdrawal_sat(ctx, "wallet", txid, NULL,
734 					      blockheight, out_val);
735 		notify_chain_mvt(ld, mvt);
736 		goto log_fee;
737 	}
738 
739 	fee = AMOUNT_SAT(0);
740 
741 	/* Note that to figure out the *total* 'onchain'
742 	 * cost of a channel, you'll want to also include
743 	 * fees logged here, to the 'wallet' account (for funding tx).
744 	 * You can do this in post by accounting for any 'chain_fees' logged for
745 	 * the funding txid when looking at a channel. */
746 log_fee:
747 	notify_chain_mvt(ld,
748 			new_coin_chain_fees_sat(ctx, "wallet", txid,
749 						blockheight, fee));
750 
751 	tal_free(ctx);
752 }
753 
754 /**
755  * topo_update_spends -- Tell the wallet about all spent outpoints
756  */
topo_update_spends(struct chain_topology * topo,struct block * b)757 static void topo_update_spends(struct chain_topology *topo, struct block *b)
758 {
759 	const struct short_channel_id *spent_scids;
760 	for (size_t i = 0; i < tal_count(b->full_txs); i++) {
761 		const struct bitcoin_tx *tx = b->full_txs[i];
762 		bool our_tx = true, includes_our_spend = false;
763 		struct bitcoin_txid txid;
764 		struct amount_sat inputs_total = AMOUNT_SAT(0);
765 
766 		txid = b->txids[i];
767 
768 		for (size_t j = 0; j < tx->wtx->num_inputs; j++) {
769 			struct bitcoin_outpoint outpoint;
770 			bool our_spend;
771 
772 			bitcoin_tx_input_get_outpoint(tx, j, &outpoint);
773 
774 			our_spend = wallet_outpoint_spend(
775 			    topo->ld->wallet, tmpctx, b->height, &outpoint);
776 			our_tx &= our_spend;
777 			includes_our_spend |= our_spend;
778 			if (our_spend) {
779 				struct amount_sat input_amt;
780 				bool ok;
781 
782 				record_utxo_spent(topo->ld, &txid, &outpoint,
783 						  b->height, &input_amt);
784 				ok = amount_sat_add(&inputs_total, inputs_total, input_amt);
785 				assert(ok);
786 			}
787 		}
788 
789 		if (includes_our_spend)
790 			record_tx_outs_and_fees(topo->ld, tx, &txid,
791 						b->height, inputs_total, our_tx);
792 	}
793 	/* Retrieve all potential channel closes from the UTXO set and
794 	 * tell gossipd about them. */
795 	spent_scids =
796 	    wallet_utxoset_get_spent(tmpctx, topo->ld->wallet, b->height);
797 
798 	for (size_t i=0; i<tal_count(spent_scids); i++) {
799 		gossipd_notify_spend(topo->bitcoind->ld, &spent_scids[i]);
800 	}
801 	tal_free(spent_scids);
802 }
803 
topo_add_utxos(struct chain_topology * topo,struct block * b)804 static void topo_add_utxos(struct chain_topology *topo, struct block *b)
805 {
806 	for (size_t i = 0; i < tal_count(b->full_txs); i++) {
807 		const struct bitcoin_tx *tx = b->full_txs[i];
808 		struct bitcoin_outpoint outpoint;
809 
810 		bitcoin_txid(tx, &outpoint.txid);
811 		for (outpoint.n = 0;
812 		     outpoint.n < tx->wtx->num_outputs;
813 		     outpoint.n++) {
814 			if (tx->wtx->outputs[outpoint.n].features
815 			    & WALLY_TX_IS_COINBASE)
816 				continue;
817 
818 			const u8 *script = bitcoin_tx_output_get_script(tmpctx, tx, outpoint.n);
819 			struct amount_asset amt = bitcoin_tx_output_get_amount(tx, outpoint.n);
820 
821 			if (amount_asset_is_main(&amt) && is_p2wsh(script, NULL)) {
822 				wallet_utxoset_add(topo->ld->wallet, &outpoint,
823 						   b->height, i, script,
824 						   amount_asset_to_sat(&amt));
825 			}
826 		}
827 	}
828 }
829 
add_tip(struct chain_topology * topo,struct block * b)830 static void add_tip(struct chain_topology *topo, struct block *b)
831 {
832 	/* Attach to tip; b is now the tip. */
833 	assert(b->height == topo->tip->height + 1);
834 	b->prev = topo->tip;
835 	topo->tip->next = b;	/* FIXME this doesn't seem to be used anywhere */
836 	topo->tip = b;
837 	wallet_block_add(topo->ld->wallet, b);
838 
839 	topo_add_utxos(topo, b);
840 	topo_update_spends(topo, b);
841 
842 	/* Only keep the transactions we care about. */
843 	filter_block_txs(topo, b);
844 
845 	block_map_add(&topo->block_map, b);
846 	topo->max_blockheight = b->height;
847 }
848 
new_block(struct chain_topology * topo,struct bitcoin_block * blk,unsigned int height)849 static struct block *new_block(struct chain_topology *topo,
850 			       struct bitcoin_block *blk,
851 			       unsigned int height)
852 {
853 	struct block *b = tal(topo, struct block);
854 
855 	bitcoin_block_blkid(blk, &b->blkid);
856 	log_debug(topo->log, "Adding block %u: %s",
857 		  height,
858 		  type_to_string(tmpctx, struct bitcoin_blkid, &b->blkid));
859 	assert(!block_map_get(&topo->block_map, &b->blkid));
860 	b->next = NULL;
861 	b->prev = NULL;
862 
863 	b->height = height;
864 
865 	b->hdr = blk->hdr;
866 
867 	b->full_txs = tal_steal(b, blk->tx);
868 	b->txids = tal_steal(b, blk->txids);
869 
870 	return b;
871 }
872 
remove_tip(struct chain_topology * topo)873 static void remove_tip(struct chain_topology *topo)
874 {
875 	struct block *b = topo->tip;
876 	struct bitcoin_txid *txs;
877 	size_t i, n;
878 	const struct short_channel_id *removed_scids;
879 
880 	log_debug(topo->log, "Removing stale block %u: %s",
881 			  topo->tip->height,
882 			  type_to_string(tmpctx, struct bitcoin_blkid, &b->blkid));
883 
884 	/* Move tip back one. */
885 	topo->tip = b->prev;
886 
887 	if (!topo->tip)
888 		fatal("Initial block %u (%s) reorganized out!",
889 		      b->height,
890 		      type_to_string(tmpctx, struct bitcoin_blkid, &b->blkid));
891 
892 	txs = wallet_transactions_by_height(b, topo->ld->wallet, b->height);
893 	n = tal_count(txs);
894 
895 	/* Notify that txs are kicked out (their height will be set NULL in db) */
896 	for (i = 0; i < n; i++)
897 		txwatch_fire(topo, &txs[i], 0);
898 
899 	/* Grab these before we delete block from db */
900 	removed_scids = wallet_utxoset_get_created(tmpctx, topo->ld->wallet,
901 						   b->height);
902 	wallet_block_remove(topo->ld->wallet, b);
903 
904 	/* This may have unconfirmed txs: reconfirm as we add blocks. */
905 	watch_for_utxo_reconfirmation(topo, topo->ld->wallet);
906 	block_map_del(&topo->block_map, b);
907 	tal_free(b);
908 
909 	/* These no longer exist, so gossipd drops any reference to them just
910 	 * as if they were spent. */
911 	for (size_t i=0; i<tal_count(removed_scids); i++)
912 		gossipd_notify_spend(topo->bitcoind->ld, &removed_scids[i]);
913 }
914 
get_new_block(struct bitcoind * bitcoind,struct bitcoin_blkid * blkid,struct bitcoin_block * blk,struct chain_topology * topo)915 static void get_new_block(struct bitcoind *bitcoind,
916 			  struct bitcoin_blkid *blkid,
917 			  struct bitcoin_block *blk,
918 			  struct chain_topology *topo)
919 {
920 	if (!blkid && !blk) {
921 		/* No such block, we're done. */
922 		updates_complete(topo);
923 		return;
924 	}
925 	assert(blkid && blk);
926 
927 	/* Annotate all transactions with the chainparams */
928 	for (size_t i = 0; i < tal_count(blk->tx); i++)
929 		blk->tx[i]->chainparams = chainparams;
930 
931 	/* Unexpected predecessor?  Free predecessor, refetch it. */
932 	if (!bitcoin_blkid_eq(&topo->tip->blkid, &blk->hdr.prev_hash))
933 		remove_tip(topo);
934 	else
935 		add_tip(topo, new_block(topo, blk, topo->tip->height + 1));
936 
937 	/* Try for next one. */
938 	try_extend_tip(topo);
939 }
940 
try_extend_tip(struct chain_topology * topo)941 static void try_extend_tip(struct chain_topology *topo)
942 {
943 	topo->extend_timer = NULL;
944 	if (topo->stopping)
945 		return;
946 	bitcoind_getrawblockbyheight(topo->bitcoind, topo->tip->height + 1,
947 				     get_new_block, topo);
948 }
949 
init_topo(struct bitcoind * bitcoind UNUSED,struct bitcoin_blkid * blkid UNUSED,struct bitcoin_block * blk,struct chain_topology * topo)950 static void init_topo(struct bitcoind *bitcoind UNUSED,
951 		      struct bitcoin_blkid *blkid UNUSED,
952 		      struct bitcoin_block *blk,
953 		      struct chain_topology *topo)
954 {
955 	topo->root = new_block(topo, blk, topo->max_blockheight);
956 	block_map_add(&topo->block_map, topo->root);
957 	topo->tip = topo->root;
958 	topo->prev_tip = topo->tip->blkid;
959 
960 	/* In case we don't get all the way to updates_complete */
961 	db_set_intvar(topo->bitcoind->ld->wallet->db,
962 		      "last_processed_block", topo->tip->height);
963 
964 	maybe_completed_init(topo);
965 }
966 
get_block_height(const struct chain_topology * topo)967 u32 get_block_height(const struct chain_topology *topo)
968 {
969 	return topo->tip->height;
970 }
971 
get_network_blockheight(const struct chain_topology * topo)972 u32 get_network_blockheight(const struct chain_topology *topo)
973 {
974 	if (topo->tip->height > topo->headercount)
975 		return topo->tip->height;
976 	else
977 		return topo->headercount;
978 }
979 
980 
try_get_feerate(const struct chain_topology * topo,enum feerate feerate)981 u32 try_get_feerate(const struct chain_topology *topo, enum feerate feerate)
982 {
983 	return topo->feerate[feerate];
984 }
985 
feerate_min(struct lightningd * ld,bool * unknown)986 u32 feerate_min(struct lightningd *ld, bool *unknown)
987 {
988 	u32 min;
989 
990 	if (unknown)
991 		*unknown = false;
992 
993 	/* We can't allow less than feerate_floor, since that won't relay */
994 	if (ld->config.ignore_fee_limits)
995 		min = 1;
996 	else {
997 		min = try_get_feerate(ld->topology, FEERATE_MIN);
998 		if (!min) {
999 			if (unknown)
1000 				*unknown = true;
1001 		} else {
1002 			const u32 *hist = ld->topology->feehistory[FEERATE_MIN];
1003 
1004 			/* If one of last three was an outlier, use that. */
1005 			for (size_t i = 0; i < FEE_HISTORY_NUM; i++) {
1006 				if (hist[i] < min)
1007 					min = hist[i];
1008 			}
1009 		}
1010 	}
1011 
1012 	if (min < feerate_floor())
1013 		return feerate_floor();
1014 	return min;
1015 }
1016 
feerate_max(struct lightningd * ld,bool * unknown)1017 u32 feerate_max(struct lightningd *ld, bool *unknown)
1018 {
1019 	u32 feerate;
1020 	const u32 *feehistory = ld->topology->feehistory[FEERATE_MAX];
1021 
1022 	if (unknown)
1023 		*unknown = false;
1024 
1025 	if (ld->config.ignore_fee_limits)
1026 		return UINT_MAX;
1027 
1028 	/* If we don't know feerate, don't limit other side. */
1029 	feerate = try_get_feerate(ld->topology, FEERATE_MAX);
1030 	if (!feerate) {
1031 		if (unknown)
1032 			*unknown = true;
1033 		return UINT_MAX;
1034 	}
1035 
1036 	/* If one of last three was an outlier, use that. */
1037 	for (size_t i = 0; i < FEE_HISTORY_NUM; i++) {
1038 		if (feehistory[i] > feerate)
1039 			feerate = feehistory[i];
1040 	}
1041 	return feerate;
1042 }
1043 
1044 /* On shutdown, channels get deleted last.  That frees from our list, so
1045  * do it now instead. */
destroy_chain_topology(struct chain_topology * topo)1046 static void destroy_chain_topology(struct chain_topology *topo)
1047 {
1048 	struct outgoing_tx *otx;
1049 
1050 	while ((otx = list_pop(&topo->outgoing_txs, struct outgoing_tx, list)))
1051 		tal_free(otx);
1052 
1053 	/* htable uses malloc, so it would leak here */
1054 	txwatch_hash_clear(&topo->txwatches);
1055 	txowatch_hash_clear(&topo->txowatches);
1056 	block_map_clear(&topo->block_map);
1057 }
1058 
new_topology(struct lightningd * ld,struct log * log)1059 struct chain_topology *new_topology(struct lightningd *ld, struct log *log)
1060 {
1061 	struct chain_topology *topo = tal(ld, struct chain_topology);
1062 
1063 	topo->ld = ld;
1064 	block_map_init(&topo->block_map);
1065 	list_head_init(&topo->outgoing_txs);
1066 	txwatch_hash_init(&topo->txwatches);
1067 	txowatch_hash_init(&topo->txowatches);
1068 	topo->log = log;
1069 	memset(topo->feerate, 0, sizeof(topo->feerate));
1070 	topo->bitcoind = new_bitcoind(topo, ld, log);
1071 	topo->poll_seconds = 30;
1072 	topo->feerate_uninitialized = true;
1073 	topo->root = NULL;
1074 	topo->sync_waiters = tal(topo, struct list_head);
1075 	topo->stopping = false;
1076 	list_head_init(topo->sync_waiters);
1077 
1078 	return topo;
1079 }
1080 
check_blockcount(struct chain_topology * topo,u32 blockcount)1081 static void check_blockcount(struct chain_topology *topo, u32 blockcount)
1082 {
1083 	/* If bitcoind's current blockheight is below the requested
1084 	 * height, refuse.  You can always explicitly request a reindex from
1085 	 * that block number using --rescan=. */
1086 	if (blockcount < topo->max_blockheight) {
1087 		/* UINT32_MAX == no blocks in database */
1088 		if (topo->max_blockheight == UINT32_MAX) {
1089 			/* Relative rescan, but we didn't know the blockheight */
1090 			/* Protect against underflow in subtraction.
1091 			 * Possible in regtest mode. */
1092 			if (blockcount < topo->bitcoind->ld->config.rescan)
1093 				topo->max_blockheight = 0;
1094 			else
1095 				topo->max_blockheight = blockcount - topo->bitcoind->ld->config.rescan;
1096 		} else
1097 			fatal("bitcoind has gone backwards from %u to %u blocks!",
1098 			      topo->max_blockheight, blockcount);
1099 	}
1100 
1101 	/* Rollback to the given blockheight, so we start track
1102 	 * correctly again */
1103 	wallet_blocks_rollback(topo->ld->wallet, topo->max_blockheight);
1104 	/* This may have unconfirmed txs: reconfirm as we add blocks. */
1105 	watch_for_utxo_reconfirmation(topo, topo->ld->wallet);
1106 }
1107 
1108 static void retry_check_chain(struct chain_topology *topo);
1109 
1110 static void
check_chain(struct bitcoind * bitcoind,const char * chain,const u32 headercount,const u32 blockcount,const bool ibd,const bool first_call,struct chain_topology * topo)1111 check_chain(struct bitcoind *bitcoind, const char *chain,
1112 	    const u32 headercount, const u32 blockcount, const bool ibd,
1113 	    const bool first_call, struct chain_topology *topo)
1114 {
1115 	if (!streq(chain, chainparams->bip70_name))
1116 		fatal("Wrong network! Our Bitcoin backend is running on '%s',"
1117 		      " but we expect '%s'.", chain, chainparams->bip70_name);
1118 
1119 	topo->headercount = headercount;
1120 
1121 	if (first_call) {
1122 		/* Has the Bitcoin backend gone backward ? */
1123 		check_blockcount(topo, blockcount);
1124 		/* Get up to speed with topology. */
1125 		bitcoind_getrawblockbyheight(topo->bitcoind, topo->max_blockheight,
1126 					     init_topo, topo);
1127 	}
1128 
1129 	if (ibd) {
1130 		if (first_call)
1131 			log_unusual(bitcoind->log,
1132 				    "Waiting for initial block download (this can take"
1133 				    " a while!)");
1134 		else
1135 			log_debug(bitcoind->log,
1136 				  "Still waiting for initial block download");
1137 	} else if (headercount != blockcount) {
1138 		if (first_call)
1139 			log_unusual(bitcoind->log,
1140 				    "Waiting for bitcoind to catch up"
1141 				    " (%u blocks of %u)",
1142 				    blockcount, headercount);
1143 		else
1144 			log_debug(bitcoind->log,
1145 				  "Waiting for bitcoind to catch up"
1146 				  " (%u blocks of %u)",
1147 				  blockcount, headercount);
1148 	} else {
1149 		if (!first_call)
1150 			log_unusual(bitcoind->log,
1151 				    "Bitcoin backend now synced.");
1152 		bitcoind->synced = true;
1153 		return;
1154 	}
1155 
1156 	assert(!bitcoind->checkchain_timer);
1157 	bitcoind->checkchain_timer
1158 		= new_reltimer(bitcoind->ld->timers, bitcoind,
1159 			       /* Be 4x more aggressive in this case. */
1160 			       time_divide(time_from_sec(bitcoind->ld->topology
1161 							 ->poll_seconds), 4),
1162 			       retry_check_chain, bitcoind->ld->topology);
1163 }
1164 
retry_check_chain(struct chain_topology * topo)1165 static void retry_check_chain(struct chain_topology *topo)
1166 {
1167 	topo->bitcoind->checkchain_timer = NULL;
1168 	if (topo->stopping)
1169 		return;
1170 	bitcoind_getchaininfo(topo->bitcoind, false, check_chain, topo);
1171 }
1172 
setup_topology(struct chain_topology * topo,u32 min_blockheight,u32 max_blockheight)1173 void setup_topology(struct chain_topology *topo,
1174 		    u32 min_blockheight, u32 max_blockheight)
1175 {
1176 	memset(&topo->feerate, 0, sizeof(topo->feerate));
1177 
1178 	topo->min_blockheight = min_blockheight;
1179 	topo->max_blockheight = max_blockheight;
1180 
1181 	/* This waits for bitcoind. */
1182 	bitcoind_check_commands(topo->bitcoind);
1183 
1184 	/* For testing.. */
1185 	log_debug(topo->ld->log, "All Bitcoin plugin commands registered");
1186 
1187 	/* Sanity checks, then topology initialization. */
1188 	topo->bitcoind->checkchain_timer = NULL;
1189 	bitcoind_getchaininfo(topo->bitcoind, true, check_chain, topo);
1190 
1191 	tal_add_destructor(topo, destroy_chain_topology);
1192 
1193 	start_fee_estimate(topo);
1194 
1195 	/* Once it gets initial block, it calls io_break() and we return. */
1196 	io_loop_with_timers(topo->ld);
1197 }
1198 
begin_topology(struct chain_topology * topo)1199 void begin_topology(struct chain_topology *topo)
1200 {
1201 	try_extend_tip(topo);
1202 }
1203 
stop_topology(struct chain_topology * topo)1204 void stop_topology(struct chain_topology *topo)
1205 {
1206 	/* Stop timers from re-arming. */
1207 	topo->stopping = true;
1208 
1209 	/* Remove timers while we're cleaning up plugins. */
1210 	tal_free(topo->bitcoind->checkchain_timer);
1211 	tal_free(topo->extend_timer);
1212 	tal_free(topo->updatefee_timer);
1213 }
1214