From 1bb66cde2a3f2f64aa022a8fc075ed0933ee13ca Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Tue, 7 Feb 2017 12:14:21 +1030 Subject: [PATCH] bitcoin/scrpt: add vanilla p2pkh support. We are about to use it for our funding tx change output. Signed-off-by: Rusty Russell --- bitcoin/script.c | 40 ++++++++++++++++++++++++++++++++++++++++ bitcoin/script.h | 7 +++++++ 2 files changed, 47 insertions(+) diff --git a/bitcoin/script.c b/bitcoin/script.c index c4e324be4..32f7ff849 100644 --- a/bitcoin/script.c +++ b/bitcoin/script.c @@ -1,3 +1,4 @@ +#include "address.h" #include "locktime.h" #include "pubkey.h" #include "script.h" @@ -109,6 +110,16 @@ static void add_push_key(u8 **scriptp, const struct pubkey *key) add_push_bytes(scriptp, der, sizeof(der)); } +static void add_push_sig(u8 **scriptp, const secp256k1_ecdsa_signature *sig) +{ + u8 der[73]; + size_t len = signature_to_der(der, sig); + + /* Append sighash type */ + der[len++] = SIGHASH_ALL; + add_push_bytes(scriptp, der, len); +} + static u8 *stack_key(const tal_t *ctx, const struct pubkey *key) { u8 der[PUBKEY_DER_LEN]; @@ -197,6 +208,35 @@ u8 *scriptpubkey_p2sh(const tal_t *ctx, const u8 *redeemscript) return script; } +/* Create an output script using p2pkh */ +u8 *scriptpubkey_p2pkh(const tal_t *ctx, const struct pubkey *pubkey) +{ + struct bitcoin_address addr; + u8 der[PUBKEY_DER_LEN]; + u8 *script = tal_arr(ctx, u8, 0); + + pubkey_to_der(der, pubkey); + hash160(&addr.addr, der, sizeof(der)); + add_op(&script, OP_DUP); + add_op(&script, OP_HASH160); + add_push_bytes(&script, &addr.addr, sizeof(addr.addr)); + add_op(&script, OP_EQUALVERIFY); + add_op(&script, OP_CHECKSIG); + return script; +} + +/* Create an input script which spends p2pkh */ +u8 *bitcoin_redeem_p2pkh(const tal_t *ctx, const struct pubkey *pubkey, + const secp256k1_ecdsa_signature *sig) +{ + u8 *script = tal_arr(ctx, u8, 0); + + add_push_sig(&script, sig); + add_push_key(&script, pubkey); + + return script; +} + /* Create the redeemscript for a P2SH + P2WPKH (for signing tx) */ u8 *bitcoin_redeem_p2wpkh(const tal_t *ctx, const struct pubkey *key) { diff --git a/bitcoin/script.h b/bitcoin/script.h index c45a575f6..c8de05abd 100644 --- a/bitcoin/script.h +++ b/bitcoin/script.h @@ -33,6 +33,13 @@ u8 *bitcoin_redeem_secret_or_delay(const tal_t *ctx, /* Create an output script using p2sh for this redeem script. */ u8 *scriptpubkey_p2sh(const tal_t *ctx, const u8 *redeemscript); +/* Create an output script using p2pkh */ +u8 *scriptpubkey_p2pkh(const tal_t *ctx, const struct pubkey *pubkey); + +/* Create an input script which spends p2pkh */ +u8 *bitcoin_redeem_p2pkh(const tal_t *ctx, const struct pubkey *pubkey, + const secp256k1_ecdsa_signature *sig); + /* Create the redeemscript for a P2SH + P2WPKH. */ u8 *bitcoin_redeem_p2wpkh(const tal_t *ctx, const struct pubkey *key);