#include "config.h"
#include "../../common/blockheight_states.c"
#include "../../common/channel_id.c"
/* Normally fee_states does not allow feerate < 253 */
#define TEST_ALLOW_ZERO_FEERATE 1
#include "../../common/fee_states.c"
#include "../../common/initial_channel.c"
#include "../../common/keyset.c"
#include "../full_channel.c"
#include "../commit_tx.c"
#include <ccan/err/err.h>
#include <ccan/io/io.h>
#include <common/daemon.h>
#include <common/randbytes.h>
#include <common/setup.h>
#include <wire/wire_io.h>
#include <wire/wire_sync.h>

/* AUTOGENERATED MOCKS START */
/* Generated stub for io_read_wire_ */
struct io_plan *io_read_wire_(struct io_conn *conn UNNEEDED,
			      const tal_t *ctx UNNEEDED,
			      u8 **data UNNEEDED,
			      struct io_plan *(*next)(struct io_conn * UNNEEDED, void *) UNNEEDED,
			      void *next_arg UNNEEDED)
{ fprintf(stderr, "io_read_wire_ called!\n"); abort(); }
/* Generated stub for io_write_wire_ */
struct io_plan *io_write_wire_(struct io_conn *conn UNNEEDED,
			       const u8 *data TAKES UNNEEDED,
			       struct io_plan *(*next)(struct io_conn * UNNEEDED, void *) UNNEEDED,
			       void *next_arg UNNEEDED)
{ fprintf(stderr, "io_write_wire_ called!\n"); abort(); }
/* Generated stub for memleak_add_helper_ */
void memleak_add_helper_(const tal_t *p UNNEEDED, void (*cb)(struct htable *memtable UNNEEDED,
						    const tal_t *)){ }
/* Generated stub for memleak_scan_htable */
void memleak_scan_htable(struct htable *memtable UNNEEDED, const struct htable *ht UNNEEDED)
{ fprintf(stderr, "memleak_scan_htable called!\n"); abort(); }
/* Generated stub for send_backtrace */
void send_backtrace(const char *why UNNEEDED)
{ fprintf(stderr, "send_backtrace called!\n"); abort(); }
/* Generated stub for status_failed */
void status_failed(enum status_failreason code UNNEEDED,
		   const char *fmt UNNEEDED, ...)
{ fprintf(stderr, "status_failed called!\n"); abort(); }
/* Generated stub for wire_sync_write */
bool wire_sync_write(int fd UNNEEDED, const void *msg TAKES UNNEEDED)
{ fprintf(stderr, "wire_sync_write called!\n"); abort(); }
/* AUTOGENERATED MOCKS END */

void status_fmt(enum log_level level UNUSED,
		const struct node_id *node_id,
		const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vprintf(fmt, ap);
	printf("\n");
	va_end(ap);
}

/* bitcoind loves its backwards txids! */
static struct bitcoin_txid txid_from_hex(const char *hex)
{
	struct bitcoin_txid txid;

	if (!bitcoin_txid_from_hex(hex, strlen(hex), &txid))
		abort();
	return txid;
}

static struct bitcoin_tx *tx_from_hex(const tal_t *ctx, const char *hex)
{
	return bitcoin_tx_from_hex(ctx, hex, strlen(hex));
}

/* BOLT #3:
 *
 *     local_feerate_per_kw: 0
 *     ...
 *     local_feerate_per_kw: 647
 *     ...
 *     local_feerate_per_kw: 648
 *     ...
 *     local_feerate_per_kw: 2069
 *     ...
 *     local_feerate_per_kw: 2070
 *     ...
 *     local_feerate_per_kw: 2194
 *     ...
 *     local_feerate_per_kw: 2195
 *     ...
 *     local_feerate_per_kw: 3702
 *     ...
 *     local_feerate_per_kw: 3703
 *     ...
 *     local_feerate_per_kw: 4914
 *     ...
 *     local_feerate_per_kw: 4915
 *     ...
 *     local_feerate_per_kw: 9651180
 *     ...
 *     local_feerate_per_kw: 9651181
 *     ...
 *     local_feerate_per_kw: 9651936
 */
static u32 feerates[] = {
	647, 648,
	2069, 2070,
	2194, 2195,
	3702, 3703,
	4914, 4915,
	9651180, 9651181,
	9651936
};

/* BOLT #3:
 *
 *    htlc 0 direction: remote->local
 *    htlc 0 amount_msat: 1000000
 *    htlc 0 expiry: 500
 *    htlc 0 payment_preimage: 0000000000000000000000000000000000000000000000000000000000000000
 *    htlc 1 direction: remote->local
 *    htlc 1 amount_msat: 2000000
 *    htlc 1 expiry: 501
 *    htlc 1 payment_preimage: 0101010101010101010101010101010101010101010101010101010101010101
 *    htlc 2 direction: local->remote
 *    htlc 2 amount_msat: 2000000
 *    htlc 2 expiry: 502
 *    htlc 2 payment_preimage: 0202020202020202020202020202020202020202020202020202020202020202
 *    htlc 3 direction: local->remote
 *    htlc 3 amount_msat: 3000000
 *    htlc 3 expiry: 503
 *    htlc 3 payment_preimage: 0303030303030303030303030303030303030303030303030303030303030303
 *    htlc 4 direction: remote->local
 *    htlc 4 amount_msat: 4000000
 *    htlc 4 expiry: 504
 *    htlc 4 payment_preimage: 0404040404040404040404040404040404040404040404040404040404040404
 */
static const struct htlc **include_htlcs(struct channel *channel, enum side side)
{
	int i;
	const struct htlc **htlcs = tal_arr(channel, const struct htlc *, 5);
	const struct htlc **changed_htlcs;
	u8 *dummy_routing = tal_arr(htlcs, u8, TOTAL_PACKET_SIZE(ROUTING_INFO_SIZE));
	bool ret;

	for (i = 0; i < 5; i++) {
		struct preimage preimage;
		struct sha256 hash;
		enum channel_add_err e;
		enum side sender;
		struct amount_msat msatoshi = AMOUNT_MSAT(0);

		switch (i) {
		case 0:
			sender = !side;
			msatoshi = AMOUNT_MSAT(1000000);
			break;
		case 1:
			sender = !side;
			msatoshi = AMOUNT_MSAT(2000000);
			break;
		case 2:
			sender = side;
			msatoshi = AMOUNT_MSAT(2000000);
			break;
		case 3:
			sender = side;
			msatoshi = AMOUNT_MSAT(3000000);
			break;
		case 4:
			sender = !side;
			msatoshi = AMOUNT_MSAT(4000000);
			break;
		default:
			abort();
		}
		assert(msatoshi.millisatoshis != 0);

		memset(&preimage, i, sizeof(preimage));
		sha256(&hash, &preimage, sizeof(preimage));
		e = channel_add_htlc(channel, sender, i, msatoshi, 500+i, &hash,
				     dummy_routing, NULL, NULL, NULL, NULL, true);
		assert(e == CHANNEL_ERR_ADD_OK);
		htlcs[i] = channel_get_htlc(channel, sender, i);
	}
	tal_free(dummy_routing);

	/* Now make HTLCs fully committed. */
	changed_htlcs = tal_arr(htlcs, const struct htlc *, 0);
	ret = channel_sending_commit(channel, &changed_htlcs);
	assert(ret);
	ret = channel_rcvd_revoke_and_ack(channel, &changed_htlcs);
	assert(ret);
	ret = channel_rcvd_commit(channel, &changed_htlcs);
	assert(ret);
	ret = channel_sending_revoke_and_ack(channel);
	assert(ret);
	ret = channel_sending_commit(channel, &changed_htlcs);
	assert(ret);
	ret = channel_rcvd_revoke_and_ack(channel, &changed_htlcs);
	assert(!ret);
	return htlcs;
}

static struct pubkey pubkey_from_hex(const char *hex)
{
	struct pubkey pubkey;

	if (strstarts(hex, "0x"))
		hex += 2;
	if (!pubkey_from_hexstr(hex, strlen(hex), &pubkey))
		abort();
	return pubkey;
}

static void tx_must_be_eq(const struct bitcoin_tx *a,
			  const struct bitcoin_tx *b)
{
	u8 *lina, *linb;
	size_t i;

	lina = linearize_tx(tmpctx, a);
	linb = linearize_tx(tmpctx, b);

	for (i = 0; i < tal_count(lina); i++) {
		if (i >= tal_count(linb))
			errx(1, "Second tx is truncated:\n"
			     "%s\n"
			     "%s",
			     tal_hex(tmpctx, lina),
			     tal_hex(tmpctx, linb));
		if (lina[i] != linb[i])
			errx(1, "tx differ at offset %zu:\n"
			     "%s\n"
			     "%s",
			     i,
			     tal_hex(tmpctx, lina),
			     tal_hex(tmpctx, linb));
	}
	if (i != tal_count(linb))
		errx(1, "First tx is truncated:\n"
		     "%s\n"
		     "%s",
		     tal_hex(tmpctx, lina),
		     tal_hex(tmpctx, linb));
}

static void txs_must_be_eq(struct bitcoin_tx **a, struct bitcoin_tx **b)
{
	size_t i;

	if (tal_count(a) != tal_count(b))
		errx(1, "A has %zu txs, B has %zu",
		     tal_count(a), tal_count(b));

	for (i = 0; i < tal_count(a); i++)
		tx_must_be_eq(a[i], b[i]);
}

static void send_and_fulfill_htlc(struct channel *channel,
				  enum side sender,
				  struct amount_msat msatoshi)
{
	struct preimage r;
	struct sha256 rhash;
	u8 *dummy_routing = tal_arr(channel, u8, TOTAL_PACKET_SIZE(ROUTING_INFO_SIZE));
	bool ret;
	const struct htlc *htlc, **changed_htlcs;

	memset(&r, 0, sizeof(r));
	sha256(&rhash, &r, sizeof(r));

	assert(channel_add_htlc(channel, sender, 1337, msatoshi, 900, &rhash,
				dummy_routing, NULL, NULL, NULL, NULL, true)
	       == CHANNEL_ERR_ADD_OK);
	htlc = channel_get_htlc(channel, sender, 1337);
	assert(htlc);

	changed_htlcs = tal_arr(channel, const struct htlc *, 0);

	if (sender == LOCAL) {
		/* Step through a complete cycle. */
		ret = channel_sending_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_rcvd_revoke_and_ack(channel, &changed_htlcs);
		assert(ret);
		ret = channel_rcvd_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_sending_revoke_and_ack(channel);
		assert(!ret);
		assert(channel_fulfill_htlc(channel, LOCAL, 1337, &r, NULL)
		       == CHANNEL_ERR_REMOVE_OK);
		ret = channel_rcvd_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_sending_revoke_and_ack(channel);
		assert(ret);
		ret = channel_sending_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_rcvd_revoke_and_ack(channel, &changed_htlcs);
		assert(!ret);
		assert(htlc->state == RCVD_REMOVE_ACK_REVOCATION);
	} else {
		ret = channel_rcvd_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_sending_revoke_and_ack(channel);
		assert(ret);
		ret = channel_sending_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_rcvd_revoke_and_ack(channel, &changed_htlcs);
		assert(!ret);
		assert(channel_fulfill_htlc(channel, REMOTE, 1337, &r, NULL)
		       == CHANNEL_ERR_REMOVE_OK);
		ret = channel_sending_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_rcvd_revoke_and_ack(channel, &changed_htlcs);
		assert(ret);
		ret = channel_rcvd_commit(channel, &changed_htlcs);
		assert(ret);
		ret = channel_sending_revoke_and_ack(channel);
		assert(!ret);
		assert(htlc->state == SENT_REMOVE_ACK_REVOCATION);
	}
	assert(!channel_get_htlc(channel, sender, 1337));
}

static void update_feerate(struct channel *channel, u32 feerate)
{
	bool ret;

	ret = channel_update_feerate(channel, feerate);
	assert(ret);
	if (channel->opener == LOCAL) {
		ret = channel_sending_commit(channel, NULL);
		assert(ret);
		ret = channel_rcvd_revoke_and_ack(channel, NULL);
		assert(ret);
		ret = channel_rcvd_commit(channel, NULL);
		assert(ret);
		ret = channel_sending_revoke_and_ack(channel);
		assert(!ret);
	} else {
		ret = channel_rcvd_commit(channel, NULL);
		assert(ret);
		ret = channel_sending_revoke_and_ack(channel);
		assert(ret);
		ret = channel_sending_commit(channel, NULL);
		assert(ret);
		ret = channel_rcvd_revoke_and_ack(channel, NULL);
		assert(!ret);
	}
	assert(channel_feerate(channel, LOCAL) == feerate);
	assert(channel_feerate(channel, REMOTE) == feerate);
}

int main(int argc, const char *argv[])
{
	common_setup(argv[0]);

	struct bitcoin_outpoint funding;
	/* We test from both sides. */
	struct channel *lchannel, *rchannel;
	struct channel_id cid;
	struct amount_sat funding_amount;
	u32 *feerate_per_kw;
	struct keyset keyset;
	struct pubkey local_funding_pubkey, remote_funding_pubkey;
	struct pubkey local_per_commitment_point;
	struct basepoints localbase, remotebase;
	struct pubkey *unknown;
	struct bitcoin_tx *raw_tx, **txs, **txs2;
	struct channel_config *local_config, *remote_config;
	struct amount_msat to_local, to_remote;
	const struct htlc **htlc_map, **htlcs;
	const u8 *funding_wscript, *funding_wscript_alt;
	bool option_anchor_outputs = false;
	bool option_anchors_zero_fee_htlc_tx = false;
	u32 blockheight = 0;
	int local_anchor;
	size_t i;

	chainparams = chainparams_for_network("bitcoin");

	feerate_per_kw = tal_arr(tmpctx, u32, NUM_SIDES);
	unknown = tal(tmpctx, struct pubkey);
	local_config = tal(tmpctx, struct channel_config);
	remote_config = tal(tmpctx, struct channel_config);

	/* BOLT #3:
	 *
	 * # Appendix C: Commitment and HTLC Transaction Test Vectors
	 *
	 * In the following:
	 *  - *local* transactions are considered, which implies that all
	 *    payments to *local* are delayed.
	 *  - It's assumed that *local* is the opener.
	 *  - Private keys are displayed as 32 bytes plus a trailing 1
	 *    (Bitcoin's convention for "compressed" private keys, i.e. keys for
	 *    which the public key is compressed).
	 *  - Transaction signatures are all deterministic, using RFC6979 (using
	 *    HMAC-SHA256).
	 *
	 * To start, common basic parameters for each test vector are defined:
	 * the HTLCs are not used for the first "simple commitment tx with no
	 * HTLCs" test, and HTLCs 5 and 6 are only used in the "same amount and
	 * preimage" test.
	 *
	 *     funding_tx_id: 8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be
	 *     funding_output_index: 0
	 *     funding_amount_satoshi: 10000000
	 *     commitment_number: 42
	 *     local_delay: 144
	 *     local_dust_limit_satoshi: 546
	 */
	funding.txid = txid_from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be");
	funding.n = 0;
	funding_amount = AMOUNT_SAT(10000000);

	remote_config->to_self_delay = 144;
	local_config->dust_limit = AMOUNT_SAT(546);
	/* This matters only because we check if added HTLC will create new
	 * output, for fee considerations. */
	remote_config->dust_limit = AMOUNT_SAT(546);

	local_config->max_htlc_value_in_flight = AMOUNT_MSAT(-1ULL);
	remote_config->max_htlc_value_in_flight = AMOUNT_MSAT(-1ULL);
	local_config->max_dust_htlc_exposure_msat = AMOUNT_MSAT(-1ULL);
	remote_config->max_dust_htlc_exposure_msat = AMOUNT_MSAT(-1ULL);
	local_config->channel_reserve = AMOUNT_SAT(0);
	remote_config->channel_reserve = AMOUNT_SAT(0);
	local_config->htlc_minimum = AMOUNT_MSAT(0);
	remote_config->htlc_minimum = AMOUNT_MSAT(0);
	local_config->max_accepted_htlcs = 0xFFFF;
	remote_config->max_accepted_htlcs = 0xFFFF;

	/* BOLT #3:
	 *
	 * # From remote_revocation_basepoint_secret
	 * INTERNAL: remote_revocation_basepoint: 02466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f27
	 *...
	 * # From local_delayed_payment_basepoint_secret
	 * INTERNAL: local_delayed_payment_basepoint: 023c72addb4fdf09af94f0c94d7fe92a386a7e70cf8a1d85916386bb2535c7b1b1
	*/
	remotebase.revocation = pubkey_from_hex("02466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f27");
	localbase.delayed_payment = pubkey_from_hex("023c72addb4fdf09af94f0c94d7fe92a386a7e70cf8a1d85916386bb2535c7b1b1");

	/* BOLT #3:
	 *
	 * local_payment_basepoint: 034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa
	 * remote_payment_basepoint: 032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991
	 * # obscured commitment number = 0x2bb038521914 ^ 42
	 */
	localbase.payment = pubkey_from_hex("034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa");
	remotebase.payment = pubkey_from_hex("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991");

	/* FIXME: Update bolt */
	localbase.htlc = localbase.payment;
	remotebase.htlc = remotebase.payment;

	/* We put unknown in for some things; valgrind will warn if used. */
	localbase.revocation = *unknown;
	remotebase.delayed_payment = *unknown;

	/* BOLT #3:
	 *
	 * local_funding_pubkey: 023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb
	 * remote_funding_pubkey: 030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1
	 */
	local_funding_pubkey = pubkey_from_hex("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb");
	remote_funding_pubkey = pubkey_from_hex("030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1");

	/* BOLT #3:
	 *
	 *     # funding wscript = 5221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae
	 */
	funding_wscript = tal_hexdata(tmpctx, "5221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae", strlen("5221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae"));

	/* BOLT #3:
	 *
	 *    commitment_number: 42
	 *...
	 *    name: simple commitment tx with no HTLCs
	 *    to_local_msat: 7000000000
	 *    to_remote_msat: 3000000000
	 *    local_feerate_per_kw: 15000
	 */

	to_local = AMOUNT_MSAT(7000000000);
	to_remote = AMOUNT_MSAT(3000000000);
	feerate_per_kw[LOCAL] = feerate_per_kw[REMOTE] = 15000;
	derive_channel_id(&cid, &funding);
	lchannel = new_full_channel(tmpctx, &cid,
				    &funding, 0,
				    take(new_height_states(NULL, LOCAL, &blockheight)),
				    0, /* No channel lease */
				    funding_amount, to_local,
				    take(new_fee_states(NULL, LOCAL,
							&feerate_per_kw[LOCAL])),
				    local_config,
				    remote_config,
				    &localbase, &remotebase,
				    &local_funding_pubkey,
				    &remote_funding_pubkey,
				    take(channel_type_static_remotekey(NULL)), false, LOCAL);
	rchannel = new_full_channel(tmpctx, &cid,
				    &funding, 0,
				    take(new_height_states(NULL, REMOTE, &blockheight)),
				    0, /* No channel lease */
				    funding_amount, to_remote,
				    take(new_fee_states(NULL, REMOTE,
							&feerate_per_kw[REMOTE])),
				    remote_config,
				    local_config,
				    &remotebase, &localbase,
				    &remote_funding_pubkey,
				    &local_funding_pubkey,
				    take(channel_type_static_remotekey(NULL)), false, REMOTE);

	/* BOLT #3:
	 *
	 * INTERNAL: local_per_commitment_point: 025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486
	 */
	local_per_commitment_point = pubkey_from_hex("025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486");
	/* BOLT #3:
	 * local_funding_pubkey: 023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb
	 * remote_funding_pubkey: 030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1
	 * local_privkey: bb13b121cdc357cd2e608b0aea294afca36e2b34cf958e2e6451a2f27469449101
	 * local_htlcpubkey: 030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7
	 * remote_htlcpubkey: 0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b
	 * local_delayedpubkey: 03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c
	 * local_revocation_pubkey: 0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19
	 */

	/* FIXME: Above is wrong for static remotekey!  local/remote pubkey are just the basepoints */
	keyset.self_payment_key = localbase.payment;
	keyset.other_payment_key = remotebase.payment;
	keyset.self_delayed_payment_key = pubkey_from_hex("03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c");
	keyset.self_revocation_key = pubkey_from_hex("0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19");

	keyset.self_htlc_key = pubkey_from_hex("030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7");
	keyset.other_htlc_key = pubkey_from_hex("0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b");

	raw_tx = commit_tx(tmpctx,
			   &funding,
			   funding_amount,
			   &local_funding_pubkey,
			   &remote_funding_pubkey,
			   LOCAL, remote_config->to_self_delay,
			   0, 0, /* No lease */
			   &keyset,
			   feerate_per_kw[LOCAL],
			   local_config->dust_limit,
			   to_local,
			   to_remote,
			   NULL, &htlc_map, NULL, 0x2bb038521914 ^ 42,
			   option_anchor_outputs, option_anchors_zero_fee_htlc_tx,
			   LOCAL, &local_anchor);

	txs = channel_txs(tmpctx, &funding, funding_amount,
			  &htlc_map, NULL, &funding_wscript_alt,
			  lchannel, &local_per_commitment_point, 42, LOCAL, 0, 0,
			  &local_anchor, NULL);
	assert(tal_count(txs) == 1);
	assert(tal_count(htlc_map) == 2);
	assert(scripteq(funding_wscript_alt, funding_wscript));
	tx_must_be_eq(txs[0], raw_tx);

	txs2 = channel_txs(tmpctx, &funding, funding_amount,
			   &htlc_map, NULL, &funding_wscript,
			   rchannel, &local_per_commitment_point, 42, REMOTE, 0, 0,
			   &local_anchor, NULL);
	txs_must_be_eq(txs, txs2);

	/* BOLT #3:
	 *
	 *    name: commitment tx with all five HTLCs untrimmed (minimum feerate)
	 *    to_local_msat: 6988000000
	 *    to_remote_msat: 3000000000
	 *    local_feerate_per_kw: 0
	 */
	to_local = AMOUNT_MSAT(6988000000);
	to_remote = AMOUNT_MSAT(3000000000);
	feerate_per_kw[LOCAL] = feerate_per_kw[REMOTE] = 0;

	/* Now, BOLT doesn't adjust owed amounts the same way we do
	 * here: it's as if local side paid for all the HTLCs.  We can
	 * fix this by having local side offer an HTLC, and having
	 * remote side accept it */
	send_and_fulfill_htlc(lchannel, LOCAL, AMOUNT_MSAT(7000000));
	send_and_fulfill_htlc(rchannel, REMOTE, AMOUNT_MSAT(7000000));

	assert(lchannel->view[LOCAL].owed[LOCAL].millisatoshis
	       == rchannel->view[REMOTE].owed[REMOTE].millisatoshis);
	assert(lchannel->view[REMOTE].owed[REMOTE].millisatoshis
	       == rchannel->view[LOCAL].owed[LOCAL].millisatoshis);

	txs = channel_txs(tmpctx, &funding, funding_amount,
			  &htlc_map, NULL, &funding_wscript,
			  lchannel, &local_per_commitment_point, 42, LOCAL, 0, 0,
			  &local_anchor, NULL);
	assert(tal_count(txs) == 1);
	txs2 = channel_txs(tmpctx, &funding, funding_amount,
			   &htlc_map, NULL, &funding_wscript,
			   rchannel, &local_per_commitment_point, 42, REMOTE, 0, 0,
			   &local_anchor, NULL);
	txs_must_be_eq(txs, txs2);

	update_feerate(lchannel, feerate_per_kw[LOCAL]);
	update_feerate(rchannel, feerate_per_kw[REMOTE]);

	htlcs = include_htlcs(lchannel, LOCAL);
	include_htlcs(rchannel, REMOTE);

	assert(lchannel->view[LOCAL].owed[LOCAL].millisatoshis
	       == rchannel->view[REMOTE].owed[REMOTE].millisatoshis);
	assert(lchannel->view[REMOTE].owed[REMOTE].millisatoshis
	       == rchannel->view[LOCAL].owed[LOCAL].millisatoshis);

	txs = channel_txs(tmpctx, &funding, funding_amount,
			  &htlc_map, NULL, &funding_wscript,
			  lchannel, &local_per_commitment_point, 42, LOCAL, 0, 0,
			  &local_anchor, NULL);
	assert(tal_count(txs) == 6);
	txs2 = channel_txs(tmpctx, &funding, funding_amount,
			   &htlc_map, NULL, &funding_wscript,
			   rchannel, &local_per_commitment_point, 42, REMOTE, 0, 0,
			   &local_anchor, NULL);
	txs_must_be_eq(txs, txs2);

	/* FIXME: Compare signatures! */
	/* BOLT #3:
	 *
	 *     htlc_success_tx (htlc #0): 02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b00000000000000000001e8030000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100d9e29616b8f3959f1d3d7f7ce893ffedcdc407717d0de8e37d808c91d3a7c50d022078c3033f6d00095c8720a4bc943c1b45727818c082e4e3ddbc6d3116435b624b014730440220636de5682ef0c5b61f124ec74e8aa2461a69777521d6998295dcea36bc3338110220165285594b23c50b28b82df200234566628a27bcd17f7f14404bd865354eb3ce012000000000000000000000000000000000000000000000000000000000000000008a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a914b8bcb07f6344b42ab04250c86a6e8b75d3fdbbc688527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f401b175ac686800000000
	 */
	raw_tx = tx_from_hex(tmpctx, "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b00000000000000000001e8030000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100d9e29616b8f3959f1d3d7f7ce893ffedcdc407717d0de8e37d808c91d3a7c50d022078c3033f6d00095c8720a4bc943c1b45727818c082e4e3ddbc6d3116435b624b014730440220636de5682ef0c5b61f124ec74e8aa2461a69777521d6998295dcea36bc3338110220165285594b23c50b28b82df200234566628a27bcd17f7f14404bd865354eb3ce012000000000000000000000000000000000000000000000000000000000000000008a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a914b8bcb07f6344b42ab04250c86a6e8b75d3fdbbc688527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f401b175ac686800000000");
	raw_tx->chainparams = chainparams;
	bitcoin_tx_input_set_witness(raw_tx, 0, NULL);
	tx_must_be_eq(raw_tx, txs[1]);

	/* BOLT #3:
	 *
	 *     htlc_timeout_tx (htlc #2): 02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b01000000000000000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220649fe8b20e67e46cbb0d09b4acea87dbec001b39b08dee7bdd0b1f03922a8640022037c462dff79df501cecfdb12ea7f4de91f99230bb544726f6e04527b1f89600401483045022100803159dee7935dba4a1d36a61055ce8fd62caa528573cc221ae288515405a252022029c59e7cffce374fe860100a4a63787e105c3cf5156d40b12dd53ff55ac8cf3f01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000
	 */
	raw_tx = tx_from_hex(tmpctx, "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b01000000000000000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220649fe8b20e67e46cbb0d09b4acea87dbec001b39b08dee7bdd0b1f03922a8640022037c462dff79df501cecfdb12ea7f4de91f99230bb544726f6e04527b1f89600401483045022100803159dee7935dba4a1d36a61055ce8fd62caa528573cc221ae288515405a252022029c59e7cffce374fe860100a4a63787e105c3cf5156d40b12dd53ff55ac8cf3f01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000");
	raw_tx->chainparams = chainparams;
	bitcoin_tx_input_set_witness(raw_tx, 0, NULL);
	tx_must_be_eq(raw_tx, txs[2]);

	/* BOLT #3:
	 *
	 *     htlc_success_tx (htlc #1): 02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b02000000000000000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220770fc321e97a19f38985f2e7732dd9fe08d16a2efa4bcbc0429400a447faf49102204d40b417f3113e1b0944ae0986f517564ab4acd3d190503faf97a6e420d4335201483045022100a437cc2ce77400ecde441b3398fea3c3ad8bdad8132be818227fe3c5b8345989022069d45e7fa0ae551ec37240845e2c561ceb2567eacf3076a6a43a502d05865faa012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000
	 */
	raw_tx = tx_from_hex(tmpctx, "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b02000000000000000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220770fc321e97a19f38985f2e7732dd9fe08d16a2efa4bcbc0429400a447faf49102204d40b417f3113e1b0944ae0986f517564ab4acd3d190503faf97a6e420d4335201483045022100a437cc2ce77400ecde441b3398fea3c3ad8bdad8132be818227fe3c5b8345989022069d45e7fa0ae551ec37240845e2c561ceb2567eacf3076a6a43a502d05865faa012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000");
	raw_tx->chainparams = chainparams;
	bitcoin_tx_input_set_witness(raw_tx, 0, NULL);
	tx_must_be_eq(raw_tx, txs[3]);

	/* BOLT #3:
	 *
	 *     htlc_timeout_tx (htlc #3): 02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b03000000000000000001b80b0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402207bcbf4f60a9829b05d2dbab84ed593e0291836be715dc7db6b72a64caf646af802201e489a5a84f7c5cc130398b841d138d031a5137ac8f4c49c770a4959dc3c13630147304402203121d9b9c055f354304b016a36662ee99e1110d9501cb271b087ddb6f382c2c80220549882f3f3b78d9c492de47543cb9a697cecc493174726146536c5954dac748701008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000
	 */
	raw_tx = tx_from_hex(tmpctx, "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b03000000000000000001b80b0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402207bcbf4f60a9829b05d2dbab84ed593e0291836be715dc7db6b72a64caf646af802201e489a5a84f7c5cc130398b841d138d031a5137ac8f4c49c770a4959dc3c13630147304402203121d9b9c055f354304b016a36662ee99e1110d9501cb271b087ddb6f382c2c80220549882f3f3b78d9c492de47543cb9a697cecc493174726146536c5954dac748701008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000");
	raw_tx->chainparams = chainparams;
	bitcoin_tx_input_set_witness(raw_tx, 0, NULL);
	tx_must_be_eq(raw_tx, txs[4]);

	/* BOLT #3:
	 *
	 *     htlc_success_tx (htlc #4): 02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b04000000000000000001a00f0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022076dca5cb81ba7e466e349b7128cdba216d4d01659e29b96025b9524aaf0d1899022060de85697b88b21c749702b7d2cfa7dfeaa1f472c8f1d7d9c23f2bf968464b8701483045022100d9080f103cc92bac15ec42464a95f070c7fb6925014e673ee2ea1374d36a7f7502200c65294d22eb20d48564954d5afe04a385551919d8b2ddb4ae2459daaeee1d95012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000
	 */
	raw_tx = tx_from_hex(tmpctx, "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b04000000000000000001a00f0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022076dca5cb81ba7e466e349b7128cdba216d4d01659e29b96025b9524aaf0d1899022060de85697b88b21c749702b7d2cfa7dfeaa1f472c8f1d7d9c23f2bf968464b8701483045022100d9080f103cc92bac15ec42464a95f070c7fb6925014e673ee2ea1374d36a7f7502200c65294d22eb20d48564954d5afe04a385551919d8b2ddb4ae2459daaeee1d95012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000");
	raw_tx->chainparams = chainparams;
	bitcoin_tx_input_set_witness(raw_tx, 0, NULL);
	tx_must_be_eq(raw_tx, txs[5]);

	/* FIXME: Compare HTLCs for these too! */
	for (i = 0; i < ARRAY_SIZE(feerates); i++) {
		feerate_per_kw[LOCAL] = feerate_per_kw[REMOTE] = feerates[i];

		*lchannel->fee_states->feerate[SENT_ADD_ACK_REVOCATION]
			= feerate_per_kw[LOCAL];
		*rchannel->fee_states->feerate[RCVD_ADD_ACK_REVOCATION]
			= feerate_per_kw[REMOTE];

		raw_tx = commit_tx(
		    tmpctx, &funding,
		    funding_amount,
		    &local_funding_pubkey,
		    &remote_funding_pubkey,
		    LOCAL, remote_config->to_self_delay,
		    0, 0, /* No lease */
		    &keyset, feerate_per_kw[LOCAL], local_config->dust_limit,
		    to_local, to_remote, htlcs, &htlc_map, NULL,
		    0x2bb038521914 ^ 42,
		    option_anchor_outputs, option_anchors_zero_fee_htlc_tx,
		    LOCAL, &local_anchor);

		txs = channel_txs(tmpctx, &funding, funding_amount,
				  &htlc_map, NULL, &funding_wscript,
				  lchannel, &local_per_commitment_point, 42,
				  LOCAL, 0, 0,
				  &local_anchor, NULL);
		tx_must_be_eq(txs[0], raw_tx);

		txs2 = channel_txs(tmpctx, &funding, funding_amount,
				   &htlc_map, NULL, &funding_wscript,
				   rchannel, &local_per_commitment_point,
				   42, REMOTE, 0, 0,
				   &local_anchor, NULL);
		txs_must_be_eq(txs, txs2);
	}

	common_shutdown();

	/* FIXME: Do BOLT comparison! */
	return 0;
}
