From 1245ffaae34272b4eb7a00bdd5736bdb90c12827 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Tue, 3 May 2016 11:24:56 +0930 Subject: [PATCH] script: add check for 32-byte preimage. We need to enforce this onchain as we do in the protocol off-chain, otherwise we can have an onchain redemption we can't redeem upstream via the protocol. While Laolu points out there's a 520 byte limit on witness stack element, that can still make for a larger tx and make problems for the steal tx case. The downside is that even the timeout transaction, which used to spend the HTLC with an empty 'secret', now needs a 32-byte secret, making it a little larger. We create a 'bitcoin_witness_htlc' helper for this case. See: http://lists.linuxfoundation.org/pipermail/lightning-dev/2016-May/000529.html Signed-off-by: Rusty Russell --- bitcoin/script.c | 25 +++++++++++++++++++++++++ bitcoin/script.h | 6 ++++++ 2 files changed, 31 insertions(+) diff --git a/bitcoin/script.c b/bitcoin/script.c index a820717c2..65b0c5895 100644 --- a/bitcoin/script.c +++ b/bitcoin/script.c @@ -300,6 +300,11 @@ u8 *bitcoin_redeem_htlc_send(const tal_t *ctx, u8 *script = tal_arr(ctx, u8, 0); struct ripemd160 ripemd; + /* Must be 32 bytes long. */ + add_op(&script, OP_SIZE); + add_number(&script, 32); + add_op(&script, OP_EQUALVERIFY); + add_op(&script, OP_HASH160); add_op(&script, OP_DUP); /* Did they supply HTLC R value? */ @@ -348,6 +353,10 @@ u8 *bitcoin_redeem_htlc_recv(const tal_t *ctx, u8 *script = tal_arr(ctx, u8, 0); struct ripemd160 ripemd; + add_op(&script, OP_SIZE); + add_number(&script, 32); + add_op(&script, OP_EQUALVERIFY); + add_op(&script, OP_HASH160); add_op(&script, OP_DUP); @@ -477,6 +486,22 @@ u8 **bitcoin_witness_secret(const tal_t *ctx, return witness; } +u8 **bitcoin_witness_htlc(const tal_t *ctx, + const struct sha256 *htlc_or_revocation_preimage, + const struct bitcoin_signature *sig, + const u8 *witnessscript) +{ + static const struct sha256 no_preimage; + + /* Use 32 zeroes if no preimage. */ + if (!htlc_or_revocation_preimage) + htlc_or_revocation_preimage = &no_preimage; + + return bitcoin_witness_secret(ctx, htlc_or_revocation_preimage, + sizeof(*htlc_or_revocation_preimage), sig, + witnessscript); +} + bool scripteq(const u8 *s1, size_t s1len, const u8 *s2, size_t s2len) { memcheck(s1, s1len); diff --git a/bitcoin/script.h b/bitcoin/script.h index 74db37fce..88906988d 100644 --- a/bitcoin/script.h +++ b/bitcoin/script.h @@ -87,6 +87,12 @@ u8 **bitcoin_witness_secret(const tal_t *ctx, const struct bitcoin_signature *sig, const u8 *witnessscript); +/* Create a witness which spends bitcoin_redeeem_htlc_recv/send */ +u8 **bitcoin_witness_htlc(const tal_t *ctx, + const struct sha256 *htlc_or_revocation_preimage, + const struct bitcoin_signature *sig, + const u8 *witnessscript); + /* Is this a pay to script hash? */ bool is_p2sh(const u8 *script, size_t script_len);