1 //! Abstractions for scripts used in the Lightning Network.
3 use bitcoin::blockdata::opcodes::all::OP_PUSHBYTES_0 as SEGWIT_V0;
4 use bitcoin::blockdata::script::{Builder, Script};
5 use bitcoin::hashes::Hash;
6 use bitcoin::hash_types::{PubkeyHash, ScriptHash, WPubkeyHash, WScriptHash};
7 use bitcoin::secp256k1::key::PublicKey;
9 use ln::features::InitFeatures;
10 use ln::msgs::DecodeError;
11 use util::ser::{Readable, Writeable, Writer};
13 use core::convert::TryFrom;
14 use core::num::NonZeroU8;
17 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
19 /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md
21 pub struct ShutdownScript(ShutdownScriptImpl);
23 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
25 pub struct InvalidShutdownScript {
26 /// The script that did not meet the requirements from [BOLT #2].
28 /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md
33 enum ShutdownScriptImpl {
34 /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
38 /// [`Script`] adhering to a script pubkey format specified in BOLT #2.
42 impl Writeable for ShutdownScript {
43 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
47 fn serialized_length(&self) -> usize {
48 self.0.serialized_length()
52 impl Readable for ShutdownScript {
53 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
54 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
58 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
64 /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
65 pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
66 Self(ShutdownScriptImpl::Legacy(pubkey))
69 /// Generates a P2PKH script pubkey from the given [`PubkeyHash`].
70 pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Self {
71 Self(ShutdownScriptImpl::Bolt2(Script::new_p2pkh(pubkey_hash)))
74 /// Generates a P2SH script pubkey from the given [`ScriptHash`].
75 pub fn new_p2sh(script_hash: &ScriptHash) -> Self {
76 Self(ShutdownScriptImpl::Bolt2(Script::new_p2sh(script_hash)))
79 /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
80 pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
81 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wpkh(pubkey_hash)))
84 /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
85 pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
86 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wsh(script_hash)))
89 /// Generates a witness script pubkey from the given segwit version and program.
91 /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
92 /// [`ShutdownScript::new_p2wsh`] instead.
96 /// This function may return an error if `program` is invalid for the segwit `version`.
97 pub fn new_witness_program(version: NonZeroU8, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
98 let script = Builder::new()
99 .push_int(version.get().into())
100 .push_slice(&program)
102 Self::try_from(script)
105 /// Converts the shutdown script into the underlying [`Script`].
106 pub fn into_inner(self) -> Script {
110 /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
111 pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
113 ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
114 ShutdownScriptImpl::Bolt2(_) => None,
118 /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
120 /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
121 pub fn is_compatible(&self, features: &InitFeatures) -> bool {
123 ShutdownScriptImpl::Legacy(_) => true,
124 ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
129 fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
130 if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
132 } else if features.supports_shutdown_anysegwit() {
133 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.into_u8()
139 impl TryFrom<Script> for ShutdownScript {
140 type Error = InvalidShutdownScript;
142 fn try_from(script: Script) -> Result<Self, Self::Error> {
143 Self::try_from((script, &InitFeatures::known()))
147 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
148 type Error = InvalidShutdownScript;
150 fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
151 if is_bolt2_compliant(&script, features) {
152 Ok(Self(ShutdownScriptImpl::Bolt2(script)))
154 Err(InvalidShutdownScript { script })
159 impl Into<Script> for ShutdownScript {
160 fn into(self) -> Script {
162 ShutdownScriptImpl::Legacy(pubkey) =>
163 Script::new_v0_wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
164 ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
169 impl core::fmt::Display for ShutdownScript{
170 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
172 ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
173 ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
179 mod shutdown_script_tests {
180 use super::ShutdownScript;
181 use bitcoin::bech32::u5;
182 use bitcoin::blockdata::opcodes;
183 use bitcoin::blockdata::script::{Builder, Script};
184 use bitcoin::secp256k1::Secp256k1;
185 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
186 use ln::features::InitFeatures;
187 use core::convert::TryFrom;
188 use core::num::NonZeroU8;
190 fn pubkey() -> bitcoin::util::ecdsa::PublicKey {
191 let secp_ctx = Secp256k1::signing_only();
192 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();
193 bitcoin::util::ecdsa::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
196 fn redeem_script() -> Script {
197 let pubkey = pubkey();
199 .push_opcode(opcodes::all::OP_PUSHNUM_2)
202 .push_opcode(opcodes::all::OP_PUSHNUM_2)
203 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
208 fn generates_p2wpkh_from_pubkey() {
209 let pubkey = pubkey();
210 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
211 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
213 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.key);
214 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
215 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
216 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
220 fn generates_p2pkh_from_pubkey_hash() {
221 let pubkey_hash = pubkey().pubkey_hash();
222 let p2pkh_script = Script::new_p2pkh(&pubkey_hash);
224 let shutdown_script = ShutdownScript::new_p2pkh(&pubkey_hash);
225 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
226 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
227 assert_eq!(shutdown_script.into_inner(), p2pkh_script);
228 assert!(ShutdownScript::try_from(p2pkh_script).is_ok());
232 fn generates_p2sh_from_script_hash() {
233 let script_hash = redeem_script().script_hash();
234 let p2sh_script = Script::new_p2sh(&script_hash);
236 let shutdown_script = ShutdownScript::new_p2sh(&script_hash);
237 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
238 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
239 assert_eq!(shutdown_script.into_inner(), p2sh_script);
240 assert!(ShutdownScript::try_from(p2sh_script).is_ok());
244 fn generates_p2wpkh_from_pubkey_hash() {
245 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
246 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
248 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
249 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
250 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
251 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
252 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
256 fn generates_p2wsh_from_script_hash() {
257 let script_hash = redeem_script().wscript_hash();
258 let p2wsh_script = Script::new_v0_wsh(&script_hash);
260 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
261 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
262 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
263 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
264 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
268 fn generates_segwit_from_non_v0_witness_program() {
269 let version = u5::try_from_u8(16).unwrap();
270 let witness_program = Script::new_witness_program(version, &[0; 40]);
272 let version = NonZeroU8::new(version.to_u8()).unwrap();
273 let shutdown_script = ShutdownScript::new_witness_program(version, &[0; 40]).unwrap();
274 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
275 assert!(!shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
276 assert_eq!(shutdown_script.into_inner(), witness_program);
280 fn fails_from_unsupported_script() {
281 let op_return = Script::new_op_return(&[0; 42]);
282 assert!(ShutdownScript::try_from(op_return).is_err());
286 fn fails_from_invalid_segwit_version() {
287 let version = NonZeroU8::new(17).unwrap();
288 assert!(ShutdownScript::new_witness_program(version, &[0; 40]).is_err());
292 fn fails_from_invalid_segwit_v0_witness_program() {
293 let witness_program = Script::new_witness_program(u5::try_from_u8(0).unwrap(), &[0; 2]);
294 assert!(ShutdownScript::try_from(witness_program).is_err());
298 fn fails_from_invalid_segwit_non_v0_witness_program() {
299 let version = u5::try_from_u8(16).unwrap();
300 let witness_program = Script::new_witness_program(version, &[0; 42]);
301 assert!(ShutdownScript::try_from(witness_program).is_err());
303 let version = NonZeroU8::new(version.to_u8()).unwrap();
304 assert!(ShutdownScript::new_witness_program(version, &[0; 42]).is_err());