1 //! Abstractions for scripts used in the Lightning Network.
3 use bitcoin::bech32::u5;
4 use bitcoin::blockdata::opcodes::all::OP_PUSHBYTES_0 as SEGWIT_V0;
5 use bitcoin::blockdata::script::Script;
6 use bitcoin::hashes::Hash;
7 use bitcoin::hash_types::{PubkeyHash, ScriptHash, WPubkeyHash, WScriptHash};
8 use bitcoin::secp256k1::key::PublicKey;
10 use ln::features::InitFeatures;
11 use ln::msgs::DecodeError;
12 use util::ser::{Readable, Writeable, Writer};
14 use std::convert::TryFrom;
16 use core::num::NonZeroU8;
18 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
20 /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md
22 pub struct ShutdownScript(ShutdownScriptImpl);
24 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
26 pub struct InvalidShutdownScript(Script);
29 enum ShutdownScriptImpl {
30 /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
34 /// [`Script`] adhering to a script pubkey format specified in BOLT #2.
38 impl Writeable for ShutdownScript {
39 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
43 fn serialized_length(&self) -> usize {
44 self.0.serialized_length()
48 impl Readable for ShutdownScript {
49 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
50 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
54 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
60 /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
61 pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
62 Self(ShutdownScriptImpl::Legacy(pubkey))
65 /// Generates a P2PKH script pubkey from the given [`PubkeyHash`].
66 pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Self {
67 Self(ShutdownScriptImpl::Bolt2(Script::new_p2pkh(pubkey_hash)))
70 /// Generates a P2SH script pubkey from the given [`ScriptHash`].
71 pub fn new_p2sh(script_hash: &ScriptHash) -> Self {
72 Self(ShutdownScriptImpl::Bolt2(Script::new_p2sh(script_hash)))
75 /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
76 pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
77 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wpkh(pubkey_hash)))
80 /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
81 pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
82 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wsh(script_hash)))
85 /// Generates a P2WSH script pubkey from the given segwit version and program.
89 /// This function may panic if given a segwit program with an invalid length.
90 pub fn new_witness_program(version: NonZeroU8, program: &[u8]) -> Self {
91 let version = u5::try_from_u8(version.get()).expect("Invalid segwit version");
92 let script = Script::new_witness_program(version, program);
93 Self::try_from(script).expect("Invalid segwit program")
96 /// Converts the shutdown script into the underlying [`Script`].
97 pub fn into_inner(self) -> Script {
101 /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
102 pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
104 ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
105 ShutdownScriptImpl::Bolt2(_) => None,
110 impl TryFrom<Script> for ShutdownScript {
111 type Error = InvalidShutdownScript;
113 fn try_from(script: Script) -> Result<Self, Self::Error> {
114 Self::try_from((script, &InitFeatures::known()))
118 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
119 type Error = InvalidShutdownScript;
121 fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
122 if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
123 Ok(Self(ShutdownScriptImpl::Bolt2(script)))
124 } else if features.supports_shutdown_anysegwit() && script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.into_u8() {
125 Ok(Self(ShutdownScriptImpl::Bolt2(script))) // option_shutdown_anysegwit
127 Err(InvalidShutdownScript(script))
132 impl Into<Script> for ShutdownScript {
133 fn into(self) -> Script {
135 ShutdownScriptImpl::Legacy(pubkey) =>
136 Script::new_v0_wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
137 ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
143 mod shutdown_script_tests {
144 use super::ShutdownScript;
145 use bitcoin::bech32::u5;
146 use bitcoin::blockdata::opcodes;
147 use bitcoin::blockdata::script::{Builder, Script};
148 use bitcoin::secp256k1::Secp256k1;
149 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
150 use std::convert::TryFrom;
152 fn pubkey() -> bitcoin::util::ecdsa::PublicKey {
153 let secp_ctx = Secp256k1::signing_only();
154 let secret_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]).unwrap();
155 bitcoin::util::ecdsa::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
158 fn redeem_script() -> Script {
159 let pubkey = pubkey();
161 .push_opcode(opcodes::all::OP_PUSHNUM_2)
164 .push_opcode(opcodes::all::OP_PUSHNUM_2)
165 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
170 fn generates_p2wpkh_from_pubkey() {
171 let pubkey = pubkey();
172 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
173 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
175 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.key);
176 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
180 fn generates_p2pkh_from_pubkey_hash() {
181 let pubkey_hash = pubkey().pubkey_hash();
182 let p2pkh_script = Script::new_p2pkh(&pubkey_hash);
184 let shutdown_script = ShutdownScript::new_p2pkh(&pubkey_hash);
185 assert_eq!(shutdown_script.into_inner(), p2pkh_script);
186 assert!(ShutdownScript::try_from(p2pkh_script).is_ok());
190 fn generates_p2sh_from_script_hash() {
191 let script_hash = redeem_script().script_hash();
192 let p2sh_script = Script::new_p2sh(&script_hash);
194 let shutdown_script = ShutdownScript::new_p2sh(&script_hash);
195 assert_eq!(shutdown_script.into_inner(), p2sh_script);
196 assert!(ShutdownScript::try_from(p2sh_script).is_ok());
200 fn generates_p2wpkh_from_pubkey_hash() {
201 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
202 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
204 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
205 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
206 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
210 fn generates_p2wsh_from_script_hash() {
211 let script_hash = redeem_script().wscript_hash();
212 let p2wsh_script = Script::new_v0_wsh(&script_hash);
214 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
215 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
216 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
220 fn fails_from_unsupported_script() {
221 let op_return = Script::new_op_return(&[0; 42]);
222 assert!(ShutdownScript::try_from(op_return).is_err());
226 fn fails_from_invalid_segwit_v0_program() {
227 let witness_program = Script::new_witness_program(u5::try_from_u8(0).unwrap(), &[0; 2]);
228 assert!(ShutdownScript::try_from(witness_program).is_err());