1 #include <bitcoin/script.h>
2 #include <ccan/array_size/array_size.h>
3 #include <common/initial_commit_tx.h>
4 #include <common/keyset.h>
5 #include <common/permute_tx.h>
6 #include <common/status.h>
7 #include <common/type_to_string.h>
8 
9 /* BOLT #3:
10  *
11  * The 48-bit commitment number is obscured by `XOR` with the lower 48 bits of:
12  *
13  *     SHA256(payment_basepoint from open_channel || payment_basepoint from accept_channel)
14  */
commit_number_obscurer(const struct pubkey * opener_payment_basepoint,const struct pubkey * accepter_payment_basepoint)15 u64 commit_number_obscurer(const struct pubkey *opener_payment_basepoint,
16 			   const struct pubkey *accepter_payment_basepoint)
17 {
18 	u8 ders[PUBKEY_CMPR_LEN * 2];
19 	struct sha256 sha;
20 	be64 obscurer = 0;
21 
22 	pubkey_to_der(ders, opener_payment_basepoint);
23 	pubkey_to_der(ders + PUBKEY_CMPR_LEN, accepter_payment_basepoint);
24 
25 	sha256(&sha, ders, sizeof(ders));
26 	/* Lower 48 bits */
27 	memcpy((u8 *)&obscurer + 2, sha.u.u8 + sizeof(sha.u.u8) - 6, 6);
28 	return be64_to_cpu(obscurer);
29 }
30 
try_subtract_fee(enum side opener,enum side side,struct amount_sat base_fee,struct amount_msat * self,struct amount_msat * other)31 bool try_subtract_fee(enum side opener, enum side side,
32 		      struct amount_sat base_fee,
33 		      struct amount_msat *self,
34 		      struct amount_msat *other)
35 {
36 	struct amount_msat *opener_amount;
37 
38 	if (opener == side)
39 		opener_amount = self;
40 	else
41 		opener_amount = other;
42 
43 	if (amount_msat_sub_sat(opener_amount, *opener_amount, base_fee))
44 		return true;
45 
46 	*opener_amount = AMOUNT_MSAT(0);
47 	return false;
48 }
49 
to_self_wscript(const tal_t * ctx,u16 to_self_delay,u32 csv,const struct keyset * keyset)50 u8 *to_self_wscript(const tal_t *ctx,
51 		    u16 to_self_delay,
52 		    u32 csv,
53 		    const struct keyset *keyset)
54 {
55 	return bitcoin_wscript_to_local(ctx, to_self_delay, csv,
56 					&keyset->self_revocation_key,
57 					&keyset->self_delayed_payment_key);
58 }
59 
tx_add_anchor_output(struct bitcoin_tx * tx,const struct pubkey * funding_key)60 void tx_add_anchor_output(struct bitcoin_tx *tx,
61 			  const struct pubkey *funding_key)
62 {
63 	u8 *wscript = bitcoin_wscript_anchor(tmpctx, funding_key);
64 	u8 *p2wsh = scriptpubkey_p2wsh(tmpctx, wscript);
65 
66 	/* BOLT #3:
67 	 * The amount of the output is fixed at 330 sats, the default
68 	 * dust limit for P2WSH.
69 	 */
70 	bitcoin_tx_add_output(tx, p2wsh, wscript, AMOUNT_SAT(330));
71 }
72 
initial_commit_tx(const tal_t * ctx,const struct bitcoin_outpoint * funding,struct amount_sat funding_sats,const struct pubkey funding_key[NUM_SIDES],enum side opener,u16 to_self_delay,const struct keyset * keyset,u32 feerate_per_kw,struct amount_sat dust_limit,struct amount_msat self_pay,struct amount_msat other_pay,struct amount_sat self_reserve,u64 obscured_commitment_number,struct wally_tx_output * direct_outputs[NUM_SIDES],enum side side,u32 csv_lock,bool option_anchor_outputs,char ** err_reason)73 struct bitcoin_tx *initial_commit_tx(const tal_t *ctx,
74 				     const struct bitcoin_outpoint *funding,
75 				     struct amount_sat funding_sats,
76 				     const struct pubkey funding_key[NUM_SIDES],
77 				     enum side opener,
78 				     u16 to_self_delay,
79 				     const struct keyset *keyset,
80 				     u32 feerate_per_kw,
81 				     struct amount_sat dust_limit,
82 				     struct amount_msat self_pay,
83 				     struct amount_msat other_pay,
84 				     struct amount_sat self_reserve,
85 				     u64 obscured_commitment_number,
86 				     struct wally_tx_output *direct_outputs[NUM_SIDES],
87 				     enum side side,
88 				     u32 csv_lock,
89 				     bool option_anchor_outputs,
90 				     char** err_reason)
91 {
92 	struct amount_sat base_fee;
93 	struct bitcoin_tx *tx;
94 	size_t n, untrimmed;
95 	bool to_local, to_remote;
96 	struct amount_msat total_pay;
97 	struct amount_sat amount;
98 	enum side lessor = !opener;
99 	u32 sequence;
100 	void *dummy_local = (void *)LOCAL, *dummy_remote = (void *)REMOTE;
101 	/* There is a direct, and possibly an anchor output for each side. */
102 	const void *output_order[2 * NUM_SIDES];
103 	const u8 *funding_wscript = bitcoin_redeem_2of2(tmpctx,
104 							&funding_key[LOCAL],
105 							&funding_key[REMOTE]);
106 
107 	if (!amount_msat_add(&total_pay, self_pay, other_pay))
108 		abort();
109 	assert(!amount_msat_greater_sat(total_pay, funding_sats));
110 
111 	/* BOLT #3:
112 	 *
113 	 * 1. Calculate which committed HTLCs need to be trimmed (see
114 	 * [Trimmed Outputs](#trimmed-outputs)).
115 	 */
116 	untrimmed = 0;
117 
118 	/* BOLT #3:
119 	 *
120 	 * 2. Calculate the base [commitment transaction
121 	 * fee](#fee-calculation).
122 	 */
123 	base_fee = commit_tx_base_fee(feerate_per_kw, untrimmed,
124 				      option_anchor_outputs);
125 
126 	/* BOLT:
127 	 * If `option_anchor_outputs` applies to the commitment
128 	 * transaction, also subtract two times the fixed anchor size
129 	 * of 330 sats from the funder (either `to_local` or
130 	 * `to_remote`).
131 	 */
132 	if (option_anchor_outputs
133 	    && !amount_sat_add(&base_fee, base_fee, AMOUNT_SAT(660))) {
134 		*err_reason = "Funder cannot afford anchor outputs";
135 		return NULL;
136 	}
137 
138 	/* BOLT #3:
139 	 *
140 	 * 3. Subtract this base fee from the funder (either `to_local` or
141 	 * `to_remote`).
142 	 * If `option_anchors` applies to the commitment transaction,
143 	 * also subtract two times the fixed anchor size of 330 sats from the
144 	 * funder (either `to_local` or `to_remote`).
145 	 */
146 	if (!try_subtract_fee(opener, side, base_fee, &self_pay, &other_pay)) {
147 		/* BOLT #2:
148 		 *
149 		 * The receiving node MUST fail the channel if:
150 		 *...
151 		 *   - it considers `feerate_per_kw` too small for timely
152 		 *     processing or unreasonably large.
153 		 */
154 		*err_reason = "Funder cannot afford fee on initial commitment transaction";
155 		status_unusual("Funder cannot afford fee"
156 			       " on initial commitment transaction");
157 		return NULL;
158 	}
159 
160 	/* FIXME, should be in #2:
161 	 *
162 	 * The receiving node MUST fail the channel if:
163 	 *...
164 	 * - both `to_local` and `to_remote` amounts for the initial
165 	 *   commitment transaction are less than or equal to
166 	 *   `channel_reserve_satoshis`.
167 	 */
168 	if (!amount_msat_greater_sat(self_pay, self_reserve)
169 	    && !amount_msat_greater_sat(other_pay, self_reserve)) {
170 		*err_reason = "Neither self amount nor other amount exceed reserve on "
171 				   "initial commitment transaction";
172 		status_unusual("Neither self amount %s"
173 			       " nor other amount %s"
174 			       " exceed reserve %s"
175 			       " on initial commitment transaction",
176 			       type_to_string(tmpctx, struct amount_msat,
177 					      &self_pay),
178 			       type_to_string(tmpctx, struct amount_msat,
179 					      &other_pay),
180 			       type_to_string(tmpctx, struct amount_sat,
181 					      &self_reserve));
182 		return NULL;
183 	}
184 
185 
186 	/* Worst-case sizing: both to-local and to-remote outputs + anchors. */
187 	tx = bitcoin_tx(ctx, chainparams, 1, untrimmed + 4, 0);
188 
189 	/* This could be done in a single loop, but we follow the BOLT
190 	 * literally to make comments in test vectors clearer. */
191 
192 	n = 0;
193 	/* BOLT #3:
194 	 *
195 	 * 4. For every offered HTLC, if it is not trimmed, add an
196 	 *    [offered HTLC output](#offered-htlc-outputs).
197 	 */
198 
199 	/* BOLT #3:
200 	 *
201 	 * 5. For every received HTLC, if it is not trimmed, add an
202 	 *    [received HTLC output](#received-htlc-outputs).
203 	 */
204 
205 	/* BOLT #3:
206 	 *
207 	 * 6. If the `to_local` amount is greater or equal to
208 	 *    `dust_limit_satoshis`, add a [`to_local`
209 	 *    output](#to_local-output).
210 	 */
211 	if (amount_msat_greater_eq_sat(self_pay, dust_limit)) {
212 		u8 *wscript = to_self_wscript(tmpctx,
213 					      to_self_delay,
214 					      side == lessor ? csv_lock : 0,
215 					      keyset);
216 		amount = amount_msat_to_sat_round_down(self_pay);
217 		int pos = bitcoin_tx_add_output(
218 		    tx, scriptpubkey_p2wsh(tx, wscript), wscript, amount);
219 		assert(pos == n);
220 		output_order[n] = dummy_local;
221 		n++;
222 		to_local = true;
223 	} else
224 		to_local = false;
225 
226 	/* BOLT #3:
227 	 *
228 	 * 7. If the `to_remote` amount is greater or equal to
229 	 *    `dust_limit_satoshis`, add a [`to_remote`
230 	 *    output](#to_remote-output).
231 	 */
232 	if (amount_msat_greater_eq_sat(other_pay, dust_limit)) {
233 		/* BOLT #3:
234 		 *
235 		 * If `option_anchors` applies to the commitment
236 		 * transaction, the `to_remote` output is encumbered by a one
237 		 * block csv lock.
238 		 *    <remote_pubkey> OP_CHECKSIGVERIFY 1 OP_CHECKSEQUENCEVERIFY
239 		 *
240 		 *...
241 		 * Otherwise, this output is a simple P2WPKH to `remotepubkey`.
242 		 */
243 		u8 *scriptpubkey;
244 		int pos;
245 
246 		amount = amount_msat_to_sat_round_down(other_pay);
247 		if (option_anchor_outputs) {
248 			const u8 *redeem
249 				= anchor_to_remote_redeem(tmpctx,
250 						&keyset->other_payment_key,
251 						(!side) == lessor ? csv_lock : 1);
252 			scriptpubkey = scriptpubkey_p2wsh(tmpctx, redeem);
253 		} else {
254 			scriptpubkey = scriptpubkey_p2wpkh(tmpctx,
255 							   &keyset->other_payment_key);
256 		}
257 		pos = bitcoin_tx_add_output(tx, scriptpubkey, NULL, amount);
258 		assert(pos == n);
259 		output_order[n] = dummy_remote;
260 		n++;
261 		to_remote = true;
262 	} else
263 		to_remote = false;
264 
265 	/* BOLT #3:
266 	 * 8. If `option_anchors` applies to the commitment transaction:
267 	 *    * if `to_local` exists or there are untrimmed HTLCs, add a
268 	 *      [`to_local_anchor` output]...
269 	 *    * if `to_remote` exists or there are untrimmed HTLCs, add a
270 	 *      [`to_remote_anchor` output]
271 	 */
272 	if (option_anchor_outputs) {
273 		if (to_local || untrimmed != 0) {
274 			tx_add_anchor_output(tx, &funding_key[side]);
275 			output_order[n] = NULL;
276 			n++;
277 		}
278 
279 		if (to_remote || untrimmed != 0) {
280 			tx_add_anchor_output(tx, &funding_key[!side]);
281 			output_order[n] = NULL;
282 			n++;
283 		}
284 	}
285 
286 	assert(n <= tx->wtx->num_outputs);
287 	assert(n <= ARRAY_SIZE(output_order));
288 
289 	/* BOLT #3:
290 	 *
291 	 * 9. Sort the outputs into [BIP 69+CLTV
292 	 *    order](#transaction-input-and-output-ordering)
293 	 */
294 	permute_outputs(tx, NULL, output_order);
295 
296 	/* BOLT #3:
297 	 *
298 	 * ## Commitment Transaction
299 	 *
300 	 * * version: 2
301 	 */
302 	assert(tx->wtx->version == 2);
303 
304 	/* BOLT #3:
305 	 *
306 	 * * locktime: upper 8 bits are 0x20, lower 24 bits are the
307 	 * lower 24 bits of the obscured commitment number
308 	 */
309 	bitcoin_tx_set_locktime(tx,
310 	    (0x20000000 | (obscured_commitment_number & 0xFFFFFF)));
311 
312 	/* BOLT #3:
313 	 *
314 	 * * txin count: 1
315 	 *    * `txin[0]` outpoint: `txid` and `output_index` from
316 	 *      `funding_created` message
317 	 *    * `txin[0]` sequence: upper 8 bits are 0x80, lower 24 bits are upper 24 bits of the obscured commitment number
318 	 *    * `txin[0]` script bytes: 0
319 	 */
320 	sequence = (0x80000000 | ((obscured_commitment_number>>24) & 0xFFFFFF));
321 	bitcoin_tx_add_input(tx, funding, sequence,
322 			     NULL, funding_sats, NULL, funding_wscript);
323 
324 	if (direct_outputs != NULL) {
325 		direct_outputs[LOCAL] = direct_outputs[REMOTE] = NULL;
326 		for (size_t i = 0; i < tx->wtx->num_outputs; i++) {
327 			if (output_order[i] == dummy_local)
328 				direct_outputs[LOCAL] = &tx->wtx->outputs[i];
329 			else if (output_order[i] == dummy_remote)
330 				direct_outputs[REMOTE] = &tx->wtx->outputs[i];
331 		}
332 	}
333 
334 	/* This doesn't reorder outputs, so we can do this after mapping outputs. */
335 	bitcoin_tx_finalize(tx);
336 
337 	assert(bitcoin_tx_check(tx));
338 
339 	return tx;
340 }
341