1 #include "address.h"
2 #include "locktime.h"
3 #include "preimage.h"
4 #include "pubkey.h"
5 #include "script.h"
6 #include <assert.h>
7 #include <ccan/endian/endian.h>
8 #include <ccan/mem/mem.h>
9 #include <common/utils.h>
10 #include <sodium/randombytes.h>
11 
12 /* To push 0-75 bytes onto stack. */
13 #define OP_PUSHBYTES(val) (val)
14 
15 /* Bitcoin's OP_HASH160 is RIPEMD(SHA256()) */
hash160(struct ripemd160 * redeemhash,const void * mem,size_t len)16 static void hash160(struct ripemd160 *redeemhash, const void *mem, size_t len)
17 {
18 	struct sha256 h;
19 
20 	sha256(&h, mem, len);
21 	ripemd160(redeemhash, h.u.u8, sizeof(h));
22 }
23 
add(u8 ** scriptp,const void * mem,size_t len)24 static void add(u8 **scriptp, const void *mem, size_t len)
25 {
26 	size_t oldlen = tal_count(*scriptp);
27 	tal_resize(scriptp, oldlen + len);
28 	memcpy(*scriptp + oldlen, mem, len);
29 }
30 
add_op(u8 ** scriptp,u8 op)31 static void add_op(u8 **scriptp, u8 op)
32 {
33 	add(scriptp, &op, 1);
34 }
35 
script_push_bytes(u8 ** scriptp,const void * mem,size_t len)36 void script_push_bytes(u8 **scriptp, const void *mem, size_t len)
37 {
38 	if (len < 76)
39 		add_op(scriptp, OP_PUSHBYTES(len));
40 	else if (len < 256) {
41 		char c = len;
42 		add_op(scriptp, OP_PUSHDATA1);
43 		add(scriptp, &c, 1);
44 	} else if (len < 65536) {
45 		le16 v = cpu_to_le16(len);
46 		add_op(scriptp, OP_PUSHDATA2);
47 		add(scriptp, &v, 2);
48 	} else {
49 		le32 v = cpu_to_le32(len);
50 		add_op(scriptp, OP_PUSHDATA4);
51 		add(scriptp, &v, 4);
52 	}
53 
54 	add(scriptp, memcheck(mem, len), len);
55 }
56 
add_number(u8 ** script,u32 num)57 static void add_number(u8 **script, u32 num)
58 {
59 	if (num == 0)
60 		add_op(script, 0);
61 	else if (num <= 16)
62 		add_op(script, 0x50 + num);
63 	else {
64 		le64 n = cpu_to_le64(num);
65 
66 		/* Beware: encoding is signed! */
67 		if (num <= 0x0000007F)
68 			script_push_bytes(script, &n, 1);
69 		else if (num <= 0x00007FFF)
70 			script_push_bytes(script, &n, 2);
71 		else if (num <= 0x007FFFFF)
72 			script_push_bytes(script, &n, 3);
73 		else if (num <= 0x7FFFFFFF)
74 			script_push_bytes(script, &n, 4);
75 		else
76 			script_push_bytes(script, &n, 5);
77 	}
78 }
79 
add_push_key(u8 ** scriptp,const struct pubkey * key)80 static void add_push_key(u8 **scriptp, const struct pubkey *key)
81 {
82 	u8 der[PUBKEY_CMPR_LEN];
83 	pubkey_to_der(der, key);
84 
85 	script_push_bytes(scriptp, der, sizeof(der));
86 }
87 
add_push_sig(u8 ** scriptp,const struct bitcoin_signature * sig)88 static void add_push_sig(u8 **scriptp, const struct bitcoin_signature *sig)
89 {
90 	u8 der[73];
91 	size_t len = signature_to_der(der, sig);
92 
93 	script_push_bytes(scriptp, der, len);
94 }
95 
stack_key(const tal_t * ctx,const struct pubkey * key)96 static u8 *stack_key(const tal_t *ctx, const struct pubkey *key)
97 {
98 	u8 der[PUBKEY_CMPR_LEN];
99 	pubkey_to_der(der, key);
100 
101 	return tal_dup_arr(ctx, u8, der, sizeof(der), 0);
102 }
103 
104 /* Bitcoin wants DER encoding. */
stack_sig(const tal_t * ctx,const struct bitcoin_signature * sig)105 static u8 *stack_sig(const tal_t *ctx, const struct bitcoin_signature *sig)
106 {
107 	u8 der[73];
108 	size_t len = signature_to_der(der, sig);
109 
110 	return tal_dup_arr(ctx, u8, der, len, 0);
111 }
112 
stack_preimage(const tal_t * ctx,const struct preimage * preimage)113 static u8 *stack_preimage(const tal_t *ctx, const struct preimage *preimage)
114 {
115 	return tal_dup_arr(ctx, u8, preimage->r, sizeof(preimage->r), 0);
116 }
117 
118 /* Bitcoin script stack values are a special, special snowflake.
119  *
120  * They're little endian values, but 0 is an empty value.  We only
121  * handle single byte values here. */
stack_number(const tal_t * ctx,unsigned int num)122 static u8 *stack_number(const tal_t *ctx, unsigned int num)
123 {
124 	u8 val;
125 
126 	if (num == 0)
127 		return tal_arr(ctx, u8, 0);
128 
129 	val = num;
130 	assert(val == num);
131 
132 	/* We use tal_dup_arr since we want tal_count() to work */
133 	return tal_dup_arr(ctx, u8, &val, 1, 0);
134 }
135 
136 /* tal_count() gives the length of the script. */
bitcoin_redeem_2of2(const tal_t * ctx,const struct pubkey * key1,const struct pubkey * key2)137 u8 *bitcoin_redeem_2of2(const tal_t *ctx,
138 			const struct pubkey *key1,
139 			const struct pubkey *key2)
140 {
141 	u8 *script = tal_arr(ctx, u8, 0);
142 	add_number(&script, 2);
143 	if (pubkey_cmp(key1, key2) < 0) {
144 		add_push_key(&script, key1);
145 		add_push_key(&script, key2);
146 	} else {
147 		add_push_key(&script, key2);
148 		add_push_key(&script, key1);
149 	}
150 	add_number(&script, 2);
151 	add_op(&script, OP_CHECKMULTISIG);
152 	return script;
153 }
154 
scriptpubkey_p2sh_hash(const tal_t * ctx,const struct ripemd160 * redeemhash)155 u8 *scriptpubkey_p2sh_hash(const tal_t *ctx, const struct ripemd160 *redeemhash)
156 {
157 	u8 *script = tal_arr(ctx, u8, 0);
158 
159 	add_op(&script, OP_HASH160);
160 	script_push_bytes(&script, redeemhash->u.u8, sizeof(redeemhash->u.u8));
161 	add_op(&script, OP_EQUAL);
162 	assert(tal_count(script) == BITCOIN_SCRIPTPUBKEY_P2SH_LEN);
163 	return script;
164 }
165 
166 /* Create p2sh for this redeem script. */
scriptpubkey_p2sh(const tal_t * ctx,const u8 * redeemscript)167 u8 *scriptpubkey_p2sh(const tal_t *ctx, const u8 *redeemscript)
168 {
169 	struct ripemd160 redeemhash;
170 
171 	hash160(&redeemhash, redeemscript, tal_count(redeemscript));
172 	return scriptpubkey_p2sh_hash(ctx, &redeemhash);
173 }
174 
175 /* Create an output script using p2pkh */
scriptpubkey_p2pkh(const tal_t * ctx,const struct bitcoin_address * addr)176 u8 *scriptpubkey_p2pkh(const tal_t *ctx, const struct bitcoin_address *addr)
177 {
178 	u8 *script = tal_arr(ctx, u8, 0);
179 
180 	add_op(&script, OP_DUP);
181 	add_op(&script, OP_HASH160);
182 	script_push_bytes(&script, &addr->addr, sizeof(addr->addr));
183 	add_op(&script, OP_EQUALVERIFY);
184 	add_op(&script, OP_CHECKSIG);
185 	assert(tal_count(script) == BITCOIN_SCRIPTPUBKEY_P2PKH_LEN);
186 	return script;
187 }
188 
scriptpubkey_opreturn(const tal_t * ctx)189 u8 *scriptpubkey_opreturn(const tal_t *ctx)
190 {
191 	u8 *script = tal_arr(ctx, u8, 0);
192 
193 	add_op(&script, OP_RETURN);
194 	return script;
195 }
scriptpubkey_opreturn_padded(const tal_t * ctx)196 u8 *scriptpubkey_opreturn_padded(const tal_t *ctx)
197 {
198 	u8 *script = tal_arr(ctx, u8, 0);
199 	u8 random[20];
200 	randombytes_buf(random, sizeof(random));
201 
202 	add_op(&script, OP_RETURN);
203 	script_push_bytes(&script, random, sizeof(random));
204 	return script;
205 }
206 
207 /* Create an input script which spends p2pkh */
bitcoin_redeem_p2pkh(const tal_t * ctx,const struct pubkey * pubkey,const struct bitcoin_signature * sig)208 u8 *bitcoin_redeem_p2pkh(const tal_t *ctx, const struct pubkey *pubkey,
209 			 const struct bitcoin_signature *sig)
210 {
211 	u8 *script = tal_arr(ctx, u8, 0);
212 
213 	add_push_sig(&script, sig);
214 	add_push_key(&script, pubkey);
215 
216 	return script;
217 }
218 
219 /* Create the redeemscript for a P2SH + P2WPKH (for signing tx) */
bitcoin_redeem_p2sh_p2wpkh(const tal_t * ctx,const struct pubkey * key)220 u8 *bitcoin_redeem_p2sh_p2wpkh(const tal_t *ctx, const struct pubkey *key)
221 {
222 	struct ripemd160 keyhash;
223 	u8 *script = tal_arr(ctx, u8, 0);
224 
225 	/* BIP141: BIP16 redeemScript pushed in the scriptSig is exactly a
226 	 * push of a version byte plus a push of a witness program. */
227 	add_number(&script, 0);
228 	pubkey_to_hash160(key, &keyhash);
229 	script_push_bytes(&script, &keyhash, sizeof(keyhash));
230 
231 	assert(tal_count(script) == BITCOIN_SCRIPTPUBKEY_P2WPKH_LEN);
232 	return script;
233 }
234 
bitcoin_scriptsig_redeem(const tal_t * ctx,const u8 * redeemscript TAKES)235 u8 *bitcoin_scriptsig_redeem(const tal_t *ctx,
236 			     const u8 *redeemscript TAKES)
237 {
238 	u8 *script;
239 
240 	/* BIP141: The scriptSig must be exactly a push of the BIP16
241 	 * redeemScript or validation fails. */
242 	script = tal_arr(ctx, u8, 0);
243 	script_push_bytes(&script, redeemscript,
244 			  tal_count(redeemscript));
245 
246 	if (taken(redeemscript))
247 		tal_free(redeemscript);
248 
249 	return script;
250 }
251 
bitcoin_scriptsig_p2sh_p2wpkh(const tal_t * ctx,const struct pubkey * key)252 u8 *bitcoin_scriptsig_p2sh_p2wpkh(const tal_t *ctx, const struct pubkey *key)
253 {
254 	u8 *redeemscript =
255 		bitcoin_redeem_p2sh_p2wpkh(NULL, key);
256 	return bitcoin_scriptsig_redeem(ctx, take(redeemscript));
257 }
258 
bitcoin_witness_p2wpkh(const tal_t * ctx,const struct bitcoin_signature * sig,const struct pubkey * key)259 u8 **bitcoin_witness_p2wpkh(const tal_t *ctx,
260 			    const struct bitcoin_signature *sig,
261 			    const struct pubkey *key)
262 {
263 	u8 **witness;
264 
265 	/* BIP141: The witness must consist of exactly 2 items (≤ 520
266 	 * bytes each). The first one a signature, and the second one
267 	 * a public key. */
268 	witness = tal_arr(ctx, u8 *, 2);
269 	witness[0] = stack_sig(witness, sig);
270 	witness[1] = stack_key(witness, key);
271 	return witness;
272 }
273 
274 /* Create an output script for a 32-byte witness. */
scriptpubkey_p2wsh(const tal_t * ctx,const u8 * witnessscript)275 u8 *scriptpubkey_p2wsh(const tal_t *ctx, const u8 *witnessscript)
276 {
277 	struct sha256 h;
278 	u8 *script = tal_arr(ctx, u8, 0);
279 
280 	add_op(&script, OP_0);
281 	sha256(&h, witnessscript, tal_count(witnessscript));
282 	script_push_bytes(&script, h.u.u8, sizeof(h.u.u8));
283 	assert(tal_count(script) == BITCOIN_SCRIPTPUBKEY_P2WSH_LEN);
284 	return script;
285 }
286 
287 /* Create an output script for a 20-byte witness. */
scriptpubkey_p2wpkh(const tal_t * ctx,const struct pubkey * key)288 u8 *scriptpubkey_p2wpkh(const tal_t *ctx, const struct pubkey *key)
289 {
290 	struct ripemd160 h;
291 	u8 *script = tal_arr(ctx, u8, 0);
292 
293 	add_op(&script, OP_0);
294 	pubkey_to_hash160(key, &h);
295 	script_push_bytes(&script, &h, sizeof(h));
296 	return script;
297 }
298 
scriptpubkey_p2wpkh_derkey(const tal_t * ctx,const u8 der[33])299 u8 *scriptpubkey_p2wpkh_derkey(const tal_t *ctx, const u8 der[33])
300 {
301 	u8 *script = tal_arr(ctx, u8, 0);
302 	struct ripemd160 h;
303 
304 	add_op(&script, OP_0);
305 	hash160(&h, der, PUBKEY_CMPR_LEN);
306 	script_push_bytes(&script, &h, sizeof(h));
307 	return script;
308 }
309 
scriptpubkey_witness_raw(const tal_t * ctx,u8 version,const u8 * wprog,size_t wprog_size)310 u8 *scriptpubkey_witness_raw(const tal_t *ctx, u8 version,
311 			     const u8 *wprog, size_t wprog_size)
312 {
313 	u8 *script = tal_arr(ctx, u8, 0);
314 	add_number(&script, version);
315 	script_push_bytes(&script, wprog, wprog_size);
316 	return script;
317 }
318 
319 /* BOLT #3:
320  *
321  * #### `to_remote` Output
322  *
323  * If `option_anchor_outputs` applies to the commitment
324  * transaction, the `to_remote` output is encumbered by a one
325  * block csv lock.
326  *    <remote_pubkey> OP_CHECKSIGVERIFY 1 OP_CHECKSEQUENCEVERIFY
327  */
328 /* BOLT- #3
329  * ##### Leased channel (`option_will_fund`)
330  *
331  * If a `lease` applies to the channel, the `to_remote` output
332  * of the `initiator` ensures the `leasor` funds are not
333  * spendable until the lease expires.
334  *
335  * <remote_pubkey> OP_CHECKSIGVERIFY MAX(1, lease_end - blockheight) OP_CHECKSEQUENCEVERIFY
336  */
337 
anchor_to_remote_redeem(const tal_t * ctx,const struct pubkey * remote_key,u32 csv_lock)338 u8 *anchor_to_remote_redeem(const tal_t *ctx,
339 			    const struct pubkey *remote_key,
340 			    u32 csv_lock)
341 {
342 	u8 *script = tal_arr(ctx, u8, 0);
343 	add_push_key(&script, remote_key);
344 	add_op(&script, OP_CHECKSIGVERIFY);
345 	add_number(&script, csv_lock);
346 	add_op(&script, OP_CHECKSEQUENCEVERIFY);
347 
348 	assert(is_anchor_witness_script(script, tal_bytelen(script)));
349 	return script;
350 }
351 
is_anchor_witness_script(const u8 * script,size_t script_len)352 bool is_anchor_witness_script(const u8 *script, size_t script_len)
353 {
354 	size_t len = 34 + 1 + 1 + 1;
355 	/* With option_will_fund, the pushbytes can be up to 2 bytes more
356 	 *
357 	 * <remote_pubkey> OP_CHECKSIGVERIFY
358 	 * 		MAX(1, lease_end - blockheight)
359 	 * 		OP_CHECKSEQUENCEVERIFY
360 	 */
361 	if (script_len < len || script_len > len + 2)
362 		return false;
363 	if (script[0] != OP_PUSHBYTES(33))
364 		return false;
365 	if (script[34] != OP_CHECKSIGVERIFY)
366 		return false;
367 	/* FIXME: check for push value */
368 	if (script[script_len - 1] != OP_CHECKSEQUENCEVERIFY)
369 		return false;
370 	return true;
371 }
372 
373 /* Create a witness which spends the 2of2. */
bitcoin_witness_2of2(const tal_t * ctx,const struct bitcoin_signature * sig1,const struct bitcoin_signature * sig2,const struct pubkey * key1,const struct pubkey * key2)374 u8 **bitcoin_witness_2of2(const tal_t *ctx,
375 			  const struct bitcoin_signature *sig1,
376 			  const struct bitcoin_signature *sig2,
377 			  const struct pubkey *key1,
378 			  const struct pubkey *key2)
379 {
380 	u8 **witness = tal_arr(ctx, u8 *, 4);
381 
382 	/* OP_CHECKMULTISIG has an out-by-one bug, which MBZ */
383 	witness[0] = stack_number(witness, 0);
384 
385 	/* sig order should match key order. */
386 	if (pubkey_cmp(key1, key2) < 0) {
387 		witness[1] = stack_sig(witness, sig1);
388 		witness[2] = stack_sig(witness, sig2);
389 	} else {
390 		witness[1] = stack_sig(witness, sig2);
391 		witness[2] = stack_sig(witness, sig1);
392 	}
393 
394 	witness[3] = bitcoin_redeem_2of2(witness, key1, key2);
395 	return witness;
396 }
397 
398 /* Create scriptcode (fake witness, basically) for P2WPKH */
p2wpkh_scriptcode(const tal_t * ctx,const struct pubkey * key)399 u8 *p2wpkh_scriptcode(const tal_t *ctx, const struct pubkey *key)
400 {
401 	struct ripemd160 pkhash;
402 	u8 *script = tal_arr(ctx, u8, 0);
403 	pubkey_to_hash160(key, &pkhash);
404 
405 	/* BIP143:
406 	 *
407 	 * For P2WPKH witness program, the scriptCode is
408 	 * 0x1976a914{20-byte-pubkey-hash}88ac.
409 	 */
410 
411 	/* PUSH(25): OP_DUP OP_HASH160 PUSH(20) 20-byte-pubkey-hash
412 	 * OP_EQUALVERIFY OP_CHECKSIG */
413 	add_op(&script, OP_DUP);
414 	add_op(&script, OP_HASH160);
415 	script_push_bytes(&script, &pkhash, sizeof(pkhash));
416 	add_op(&script, OP_EQUALVERIFY);
417 	add_op(&script, OP_CHECKSIG);
418 
419 	return script;
420 }
421 
is_p2pkh(const u8 * script,struct bitcoin_address * addr)422 bool is_p2pkh(const u8 *script, struct bitcoin_address *addr)
423 {
424 	size_t script_len = tal_count(script);
425 
426 	if (script_len != BITCOIN_SCRIPTPUBKEY_P2PKH_LEN)
427 		return false;
428 	if (script[0] != OP_DUP)
429 		return false;
430 	if (script[1] != OP_HASH160)
431 		return false;
432 	if (script[2] != OP_PUSHBYTES(20))
433 		return false;
434 	if (script[23] != OP_EQUALVERIFY)
435 		return false;
436 	if (script[24] != OP_CHECKSIG)
437 		return false;
438 	if (addr)
439 		memcpy(addr, script+3, 20);
440 	return true;
441 }
442 
is_p2sh(const u8 * script,struct ripemd160 * addr)443 bool is_p2sh(const u8 *script, struct ripemd160 *addr)
444 {
445 	size_t script_len = tal_count(script);
446 
447 	if (script_len != BITCOIN_SCRIPTPUBKEY_P2SH_LEN)
448 		return false;
449 	if (script[0] != OP_HASH160)
450 		return false;
451 	if (script[1] != OP_PUSHBYTES(20))
452 		return false;
453 	if (script[22] != OP_EQUAL)
454 		return false;
455 	if (addr)
456 		memcpy(addr, script+2, 20);
457 	return true;
458 }
459 
is_p2wsh(const u8 * script,struct sha256 * addr)460 bool is_p2wsh(const u8 *script, struct sha256 *addr)
461 {
462 	size_t script_len = tal_count(script);
463 
464 	if (script_len != BITCOIN_SCRIPTPUBKEY_P2WSH_LEN)
465 		return false;
466 	if (script[0] != OP_0)
467 		return false;
468 	if (script[1] != OP_PUSHBYTES(sizeof(struct sha256)))
469 		return false;
470 	if (addr)
471 		memcpy(addr, script+2, sizeof(struct sha256));
472 	return true;
473 }
474 
is_p2wpkh(const u8 * script,struct bitcoin_address * addr)475 bool is_p2wpkh(const u8 *script, struct bitcoin_address *addr)
476 {
477 	size_t script_len = tal_count(script);
478 
479 	if (script_len != BITCOIN_SCRIPTPUBKEY_P2WPKH_LEN)
480 		return false;
481 	if (script[0] != OP_0)
482 		return false;
483 	if (script[1] != OP_PUSHBYTES(sizeof(struct ripemd160)))
484 		return false;
485 	if (addr)
486 		memcpy(addr, script+2, sizeof(*addr));
487 	return true;
488 }
489 
is_known_scripttype(const u8 * script)490 bool is_known_scripttype(const u8 *script)
491 {
492 	return is_p2wpkh(script, NULL) || is_p2wsh(script, NULL)
493 		|| is_p2sh(script, NULL) || is_p2pkh(script, NULL);
494 }
495 
bitcoin_witness_sig_and_element(const tal_t * ctx,const struct bitcoin_signature * sig,const void * elem,size_t elemsize,const u8 * witnessscript)496 u8 **bitcoin_witness_sig_and_element(const tal_t *ctx,
497 				     const struct bitcoin_signature *sig,
498 				     const void *elem, size_t elemsize,
499 				     const u8 *witnessscript)
500 {
501 	u8 **witness = tal_arr(ctx, u8 *, 3);
502 
503 	witness[0] = stack_sig(witness, sig);
504 	witness[1] = tal_dup_arr(witness, u8, elem, elemsize, 0);
505 	witness[2] = tal_dup_talarr(witness, u8, witnessscript);
506 
507 	return witness;
508 }
509 
510 /* BOLT #3:
511  *
512  * This output sends funds back to the owner of this commitment transaction and
513  * thus must be timelocked using `OP_CHECKSEQUENCEVERIFY`. It can be claimed, without delay,
514  * by the other party if they know the revocation private key. The output is a
515  * version-0 P2WSH, with a witness script:
516  *
517  *     OP_IF
518  *         # Penalty transaction
519  *         <revocationpubkey>
520  *     OP_ELSE
521  *         `to_self_delay`
522  *         OP_CHECKSEQUENCEVERIFY
523  *         OP_DROP
524  *         <local_delayedpubkey>
525  *     OP_ENDIF
526  *     OP_CHECKSIG
527  */
528 /* BOLT- #3
529  * ##### Leased channel (`option_will_fund`)
530  * If a `lease` applies to the channel, the `to_local` output of the `accepter`
531  * ensures the `leasor` funds are not spendable until the lease expires.
532  *
533  * In a leased channel, the `to_local` output that pays the `accepter` node
534  * is modified so that its CSV is equal to the greater of the
535  * `to_self_delay` or the `lease_end` - `blockheight`.
536  *
537  *  OP_IF
538  *      # Penalty transaction
539  *      <revocationpubkey>
540  *  OP_ELSE
541  *      MAX(`to_self_delay`, `lease_end` - `blockheight`)
542  *      OP_CHECKSEQUENCEVERIFY
543  *      OP_DROP
544  *      <local_delayedpubkey>
545  *  OP_ENDIF
546  *  OP_CHECKSIG
547  */
bitcoin_wscript_to_local(const tal_t * ctx,u16 to_self_delay,u32 lease_remaining,const struct pubkey * revocation_pubkey,const struct pubkey * local_delayedkey)548 u8 *bitcoin_wscript_to_local(const tal_t *ctx, u16 to_self_delay,
549 			     u32 lease_remaining,
550 			     const struct pubkey *revocation_pubkey,
551 			     const struct pubkey *local_delayedkey)
552 {
553 	u8 *script = tal_arr(ctx, u8, 0);
554 	add_op(&script, OP_IF);
555 	add_push_key(&script, revocation_pubkey);
556 	add_op(&script, OP_ELSE);
557 	add_number(&script, max_unsigned(lease_remaining, to_self_delay));
558 	add_op(&script, OP_CHECKSEQUENCEVERIFY);
559 	add_op(&script, OP_DROP);
560 	add_push_key(&script, local_delayedkey);
561 	add_op(&script, OP_ENDIF);
562 	add_op(&script, OP_CHECKSIG);
563 	return script;
564 }
565 
566 /* BOLT #3:
567  *
568  * #### Offered HTLC Outputs
569  *
570  * This output sends funds to either an HTLC-timeout transaction after the
571  * HTLC-timeout or to the remote node using the payment preimage or the
572  * revocation key. The output is a P2WSH, with a witness script (no
573  * option_anchor_outputs):
574  *
575  *     # To remote node with revocation key
576  *     OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
577  *     OP_IF
578  *         OP_CHECKSIG
579  *     OP_ELSE
580  *         <remote_htlcpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
581  *         OP_NOTIF
582  *             # To local node via HTLC-timeout transaction (timelocked).
583  *             OP_DROP 2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
584  *         OP_ELSE
585  *             # To remote node with preimage.
586  *             OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
587  *             OP_CHECKSIG
588  *         OP_ENDIF
589  *     OP_ENDIF
590  *
591  * Or, with `option_anchor_outputs`:
592  *
593  *  # To remote node with revocation key
594  *  OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
595  *  OP_IF
596  *      OP_CHECKSIG
597  *  OP_ELSE
598  *      <remote_htlcpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
599  *      OP_NOTIF
600  *          # To local node via HTLC-timeout transaction (timelocked).
601  *          OP_DROP 2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
602  *      OP_ELSE
603  *          # To remote node with preimage.
604  *          OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
605  *          OP_CHECKSIG
606  *      OP_ENDIF
607  *      1 OP_CHECKSEQUENCEVERIFY OP_DROP
608  *  OP_ENDIF
609  */
bitcoin_wscript_htlc_offer_ripemd160(const tal_t * ctx,const struct pubkey * localhtlckey,const struct pubkey * remotehtlckey,const struct ripemd160 * payment_ripemd,const struct pubkey * revocationkey,bool option_anchor_outputs)610 u8 *bitcoin_wscript_htlc_offer_ripemd160(const tal_t *ctx,
611 					 const struct pubkey *localhtlckey,
612 					 const struct pubkey *remotehtlckey,
613 					 const struct ripemd160 *payment_ripemd,
614 					 const struct pubkey *revocationkey,
615 					 bool option_anchor_outputs)
616 {
617 	u8 *script = tal_arr(ctx, u8, 0);
618 	struct ripemd160 ripemd;
619 
620 	add_op(&script, OP_DUP);
621 	add_op(&script, OP_HASH160);
622 	pubkey_to_hash160(revocationkey, &ripemd);
623 	script_push_bytes(&script, &ripemd, sizeof(ripemd));
624 	add_op(&script, OP_EQUAL);
625 	add_op(&script, OP_IF);
626 	add_op(&script, OP_CHECKSIG);
627 	add_op(&script, OP_ELSE);
628 	add_push_key(&script, remotehtlckey);
629 	add_op(&script, OP_SWAP);
630 	add_op(&script, OP_SIZE);
631 	add_number(&script, 32);
632 	add_op(&script, OP_EQUAL);
633 	add_op(&script, OP_NOTIF);
634 	add_op(&script, OP_DROP);
635 	add_number(&script, 2);
636 	add_op(&script, OP_SWAP);
637 	add_push_key(&script, localhtlckey);
638 	add_number(&script, 2);
639 	add_op(&script, OP_CHECKMULTISIG);
640 	add_op(&script, OP_ELSE);
641 	add_op(&script, OP_HASH160);
642 	script_push_bytes(&script,
643 			  payment_ripemd->u.u8, sizeof(payment_ripemd->u.u8));
644 	add_op(&script, OP_EQUALVERIFY);
645 	add_op(&script, OP_CHECKSIG);
646 	add_op(&script, OP_ENDIF);
647 	if (option_anchor_outputs) {
648 		add_number(&script, 1);
649 		add_op(&script, OP_CHECKSEQUENCEVERIFY);
650 		add_op(&script, OP_DROP);
651 	}
652 	add_op(&script, OP_ENDIF);
653 
654 	return script;
655 }
656 
bitcoin_wscript_htlc_offer(const tal_t * ctx,const struct pubkey * localhtlckey,const struct pubkey * remotehtlckey,const struct sha256 * payment_hash,const struct pubkey * revocationkey,bool option_anchor_outputs)657 u8 *bitcoin_wscript_htlc_offer(const tal_t *ctx,
658 			       const struct pubkey *localhtlckey,
659 			       const struct pubkey *remotehtlckey,
660 			       const struct sha256 *payment_hash,
661 			       const struct pubkey *revocationkey,
662 			       bool option_anchor_outputs)
663 {
664 	struct ripemd160 ripemd;
665 
666 	ripemd160(&ripemd, payment_hash->u.u8, sizeof(payment_hash->u));
667 	return bitcoin_wscript_htlc_offer_ripemd160(ctx, localhtlckey,
668 						    remotehtlckey,
669 						    &ripemd, revocationkey,
670 						    option_anchor_outputs);
671 }
672 
673 /* BOLT #3:
674  *
675  * #### Received HTLC Outputs
676  *
677  * This output sends funds to either the remote node after the HTLC-timeout or
678  * using the revocation key, or to an HTLC-success transaction with a
679  * successful payment preimage. The output is a P2WSH, with a witness script
680  * (no `option_anchor_outputs`):
681  *
682  *     # To remote node with revocation key
683  *     OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
684  *     OP_IF
685  *         OP_CHECKSIG
686  *     OP_ELSE
687  *         <remote_htlcpubkey> OP_SWAP
688  *             OP_SIZE 32 OP_EQUAL
689  *         OP_IF
690  *             # To local node via HTLC-success transaction.
691  *             OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
692  *             2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
693  *         OP_ELSE
694  *             # To remote node after timeout.
695  *             OP_DROP <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
696  *             OP_CHECKSIG
697  *         OP_ENDIF
698  *     OP_ENDIF
699  *
700  * Or, with `option_anchor_outputs`:
701  *
702  *  # To remote node with revocation key
703  *  OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
704  *  OP_IF
705  *      OP_CHECKSIG
706  *  OP_ELSE
707  *      <remote_htlcpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
708  *      OP_IF
709  *          # To local node via HTLC-success transaction.
710  *          OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
711  *          2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
712  *      OP_ELSE
713  *          # To remote node after timeout.
714  *          OP_DROP <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
715  *          OP_CHECKSIG
716  *      OP_ENDIF
717  *      1 OP_CHECKSEQUENCEVERIFY OP_DROP
718  *  OP_ENDIF
719  */
bitcoin_wscript_htlc_receive_ripemd(const tal_t * ctx,const struct abs_locktime * htlc_abstimeout,const struct pubkey * localhtlckey,const struct pubkey * remotehtlckey,const struct ripemd160 * payment_ripemd,const struct pubkey * revocationkey,bool option_anchor_outputs)720 u8 *bitcoin_wscript_htlc_receive_ripemd(const tal_t *ctx,
721 					const struct abs_locktime *htlc_abstimeout,
722 					const struct pubkey *localhtlckey,
723 					const struct pubkey *remotehtlckey,
724 					const struct ripemd160 *payment_ripemd,
725 					const struct pubkey *revocationkey,
726 					bool option_anchor_outputs)
727 {
728 	u8 *script = tal_arr(ctx, u8, 0);
729 	struct ripemd160 ripemd;
730 
731 	add_op(&script, OP_DUP);
732 	add_op(&script, OP_HASH160);
733 	pubkey_to_hash160(revocationkey, &ripemd);
734 	script_push_bytes(&script, &ripemd, sizeof(ripemd));
735 	add_op(&script, OP_EQUAL);
736 	add_op(&script, OP_IF);
737 	add_op(&script, OP_CHECKSIG);
738 	add_op(&script, OP_ELSE);
739 	add_push_key(&script, remotehtlckey);
740 	add_op(&script, OP_SWAP);
741 	add_op(&script, OP_SIZE);
742 	add_number(&script, 32);
743 	add_op(&script, OP_EQUAL);
744 	add_op(&script, OP_IF);
745 	add_op(&script, OP_HASH160);
746 	script_push_bytes(&script,
747 			  payment_ripemd->u.u8, sizeof(payment_ripemd->u.u8));
748 	add_op(&script, OP_EQUALVERIFY);
749 	add_number(&script, 2);
750 	add_op(&script, OP_SWAP);
751 	add_push_key(&script, localhtlckey);
752 	add_number(&script, 2);
753 	add_op(&script, OP_CHECKMULTISIG);
754 	add_op(&script, OP_ELSE);
755 	add_op(&script, OP_DROP);
756 	add_number(&script, htlc_abstimeout->locktime);
757 	add_op(&script, OP_CHECKLOCKTIMEVERIFY);
758 	add_op(&script, OP_DROP);
759 	add_op(&script, OP_CHECKSIG);
760 	add_op(&script, OP_ENDIF);
761 	if (option_anchor_outputs) {
762 		add_number(&script, 1);
763 		add_op(&script, OP_CHECKSEQUENCEVERIFY);
764 		add_op(&script, OP_DROP);
765 	}
766 	add_op(&script, OP_ENDIF);
767 
768 	return script;
769 }
770 
bitcoin_wscript_htlc_receive(const tal_t * ctx,const struct abs_locktime * htlc_abstimeout,const struct pubkey * localhtlckey,const struct pubkey * remotehtlckey,const struct sha256 * payment_hash,const struct pubkey * revocationkey,bool option_anchor_outputs)771 u8 *bitcoin_wscript_htlc_receive(const tal_t *ctx,
772 				 const struct abs_locktime *htlc_abstimeout,
773 				 const struct pubkey *localhtlckey,
774 				 const struct pubkey *remotehtlckey,
775 				 const struct sha256 *payment_hash,
776 				 const struct pubkey *revocationkey,
777 				 bool option_anchor_outputs)
778 {
779 	struct ripemd160 ripemd;
780 
781 	ripemd160(&ripemd, payment_hash->u.u8, sizeof(payment_hash->u));
782 	return bitcoin_wscript_htlc_receive_ripemd(ctx, htlc_abstimeout,
783 						   localhtlckey, remotehtlckey,
784 						   &ripemd, revocationkey,
785 						   option_anchor_outputs);
786 }
787 
788 /* BOLT #3:
789  *
790  * ## HTLC-Timeout and HTLC-Success Transactions
791  *
792  *...
793  *   * `txin[0]` witness stack: `0 <remotehtlcsig> <localhtlcsig>  <payment_preimage>` for HTLC-success, `0 <remotehtlcsig> <localhtlcsig> <>` for HTLC-timeout
794  */
bitcoin_witness_htlc_timeout_tx(const tal_t * ctx,const struct bitcoin_signature * localhtlcsig,const struct bitcoin_signature * remotehtlcsig,const u8 * wscript)795 u8 **bitcoin_witness_htlc_timeout_tx(const tal_t *ctx,
796 				     const struct bitcoin_signature *localhtlcsig,
797 				     const struct bitcoin_signature *remotehtlcsig,
798 				     const u8 *wscript)
799 {
800 	u8 **witness = tal_arr(ctx, u8 *, 5);
801 
802 	witness[0] = stack_number(witness, 0);
803 	witness[1] = stack_sig(witness, remotehtlcsig);
804 	witness[2] = stack_sig(witness, localhtlcsig);
805 	witness[3] = stack_number(witness, 0);
806 	witness[4] = tal_dup_talarr(witness, u8, wscript);
807 
808 	return witness;
809 }
810 
bitcoin_witness_htlc_success_tx(const tal_t * ctx,const struct bitcoin_signature * localhtlcsig,const struct bitcoin_signature * remotesig,const struct preimage * preimage,const u8 * wscript)811 u8 **bitcoin_witness_htlc_success_tx(const tal_t *ctx,
812 				     const struct bitcoin_signature *localhtlcsig,
813 				     const struct bitcoin_signature *remotesig,
814 				     const struct preimage *preimage,
815 				     const u8 *wscript)
816 {
817 	u8 **witness = tal_arr(ctx, u8 *, 5);
818 
819 	witness[0] = stack_number(witness, 0);
820 	witness[1] = stack_sig(witness, remotesig);
821 	witness[2] = stack_sig(witness, localhtlcsig);
822 	witness[3] = stack_preimage(witness, preimage);
823 	witness[4] = tal_dup_talarr(witness, u8, wscript);
824 
825 	return witness;
826 }
bitcoin_wscript_htlc_tx(const tal_t * ctx,u16 to_self_delay,const struct pubkey * revocation_pubkey,const struct pubkey * local_delayedkey)827 u8 *bitcoin_wscript_htlc_tx(const tal_t *ctx,
828 			    u16 to_self_delay,
829 			    const struct pubkey *revocation_pubkey,
830 			    const struct pubkey *local_delayedkey)
831 {
832 	u8 *script = tal_arr(ctx, u8, 0);
833 
834 	/* BOLT #3:
835 	 *
836 	 * The witness script for the output is:
837 	 *
838 	 *     OP_IF
839 	 *         # Penalty transaction
840 	 *         <revocationpubkey>
841 	 *     OP_ELSE
842 	 *         `to_self_delay`
843 	 *         OP_CHECKSEQUENCEVERIFY
844 	 *         OP_DROP
845 	 *         <local_delayedpubkey>
846 	 *     OP_ENDIF
847 	 *     OP_CHECKSIG
848 	 */
849 	add_op(&script, OP_IF);
850 	add_push_key(&script, revocation_pubkey);
851 	add_op(&script, OP_ELSE);
852 	add_number(&script, to_self_delay);
853 	add_op(&script, OP_CHECKSEQUENCEVERIFY);
854 	add_op(&script, OP_DROP);
855 	add_push_key(&script, local_delayedkey);
856 	add_op(&script, OP_ENDIF);
857 	add_op(&script, OP_CHECKSIG);
858 
859 	return script;
860 }
861 
bitcoin_wscript_anchor(const tal_t * ctx,const struct pubkey * funding_pubkey)862 u8 *bitcoin_wscript_anchor(const tal_t *ctx,
863 			   const struct pubkey *funding_pubkey)
864 {
865 	u8 *script = tal_arr(ctx, u8, 0);
866 
867 	/* BOLT #3:
868 	 * #### `to_local_anchor` and `to_remote_anchor` Output (option_anchor_outputs)
869 	 *...
870 	 *  <local_funding_pubkey/remote_funding_pubkey> OP_CHECKSIG OP_IFDUP
871 	 *  OP_NOTIF
872 	 *      OP_16 OP_CHECKSEQUENCEVERIFY
873 	 *  OP_ENDIF
874 	 */
875 	add_push_key(&script, funding_pubkey);
876 	add_op(&script, OP_CHECKSIG);
877 	add_op(&script, OP_IFDUP);
878 	add_op(&script, OP_NOTIF);
879 	add_number(&script, 16);
880 	add_op(&script, OP_CHECKSEQUENCEVERIFY);
881 	add_op(&script, OP_ENDIF);
882 
883 	return script;
884 }
885 
scripteq(const u8 * s1,const u8 * s2)886 bool scripteq(const u8 *s1, const u8 *s2)
887 {
888 	memcheck(s1, tal_count(s1));
889 	memcheck(s2, tal_count(s2));
890 
891 	if (tal_count(s1) != tal_count(s2))
892 		return false;
893 	return memcmp(s1, s2, tal_count(s1)) == 0;
894 }
895