1 //! Abstractions for scripts used in the Lightning Network.
3 use bitcoin::{WitnessProgram, WPubkeyHash, WScriptHash};
4 use bitcoin::blockdata::opcodes::all::OP_PUSHBYTES_0 as SEGWIT_V0;
5 use bitcoin::blockdata::script::{Script, ScriptBuf};
6 use bitcoin::hashes::Hash;
7 use bitcoin::secp256k1::PublicKey;
9 use crate::ln::channelmanager;
10 use crate::ln::features::InitFeatures;
11 use crate::ln::msgs::DecodeError;
12 use crate::util::ser::{Readable, Writeable, Writer};
16 #[allow(unused_imports)]
17 use crate::prelude::*;
19 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
21 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
22 #[derive(Clone, PartialEq, Eq)]
23 pub struct ShutdownScript(ShutdownScriptImpl);
25 /// An error occurring when converting from [`ScriptBuf`] to [`ShutdownScript`].
26 #[derive(Clone, Debug)]
27 pub struct InvalidShutdownScript {
28 /// The script that did not meet the requirements from [BOLT #2].
30 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
34 #[derive(Clone, PartialEq, Eq)]
35 enum ShutdownScriptImpl {
36 /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
40 /// [`ScriptBuf`] adhering to a script pubkey format specified in BOLT #2.
44 impl Writeable for ShutdownScript {
45 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
50 impl Readable for ShutdownScript {
51 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
52 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
56 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
62 /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
63 pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
64 Self(ShutdownScriptImpl::Legacy(pubkey))
67 /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
68 pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
69 Self(ShutdownScriptImpl::Bolt2(ScriptBuf::new_p2wpkh(pubkey_hash)))
72 /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
73 pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
74 Self(ShutdownScriptImpl::Bolt2(ScriptBuf::new_p2wsh(script_hash)))
77 /// Generates a witness script pubkey from the given segwit version and program.
79 /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
80 /// [`ShutdownScript::new_p2wsh`] instead.
84 /// This function may return an error if `program` is invalid for the segwit `version`.
85 pub fn new_witness_program(witness_program: &WitnessProgram) -> Result<Self, InvalidShutdownScript> {
86 Self::try_from(ScriptBuf::new_witness_program(witness_program))
89 /// Converts the shutdown script into the underlying [`ScriptBuf`].
90 pub fn into_inner(self) -> ScriptBuf {
94 /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
95 pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
97 ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
98 ShutdownScriptImpl::Bolt2(_) => None,
102 /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
104 /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
105 pub fn is_compatible(&self, features: &InitFeatures) -> bool {
107 ShutdownScriptImpl::Legacy(_) => true,
108 ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
113 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
114 /// counterparty features.
115 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
116 if script.is_p2pkh() || script.is_p2sh() || script.is_p2wpkh() || script.is_p2wsh() {
118 } else if features.supports_shutdown_anysegwit() {
119 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.to_u8()
125 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
126 // non-witness shutdown scripts which this rejects.
127 impl TryFrom<ScriptBuf> for ShutdownScript {
128 type Error = InvalidShutdownScript;
130 fn try_from(script: ScriptBuf) -> Result<Self, Self::Error> {
131 Self::try_from((script, &channelmanager::provided_init_features(&crate::util::config::UserConfig::default())))
135 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
136 // non-witness shutdown scripts which this rejects.
137 impl TryFrom<(ScriptBuf, &InitFeatures)> for ShutdownScript {
138 type Error = InvalidShutdownScript;
140 fn try_from((script, features): (ScriptBuf, &InitFeatures)) -> Result<Self, Self::Error> {
141 if is_bolt2_compliant(&script, features) && script.is_witness_program() {
142 Ok(Self(ShutdownScriptImpl::Bolt2(script)))
144 Err(InvalidShutdownScript { script })
149 impl Into<ScriptBuf> for ShutdownScript {
150 fn into(self) -> ScriptBuf {
152 ShutdownScriptImpl::Legacy(pubkey) =>
153 ScriptBuf::new_p2wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
154 ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
159 impl core::fmt::Display for ShutdownScript{
160 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
162 ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
163 ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
169 mod shutdown_script_tests {
170 use super::ShutdownScript;
172 use bitcoin::{WitnessProgram, WitnessVersion};
173 use bitcoin::blockdata::opcodes;
174 use bitcoin::blockdata::script::{Builder, ScriptBuf};
175 use bitcoin::secp256k1::Secp256k1;
176 use bitcoin::secp256k1::{PublicKey, SecretKey};
178 use crate::ln::features::InitFeatures;
179 use crate::prelude::*;
181 fn pubkey() -> bitcoin::key::PublicKey {
182 let secp_ctx = Secp256k1::signing_only();
183 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();
184 bitcoin::key::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
187 fn redeem_script() -> ScriptBuf {
188 let pubkey = pubkey();
190 .push_opcode(opcodes::all::OP_PUSHNUM_2)
193 .push_opcode(opcodes::all::OP_PUSHNUM_2)
194 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
198 fn any_segwit_features() -> InitFeatures {
199 let mut features = InitFeatures::empty();
200 features.set_shutdown_any_segwit_optional();
205 fn generates_p2wpkh_from_pubkey() {
206 let pubkey = pubkey();
207 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
208 let p2wpkh_script = ScriptBuf::new_p2wpkh(&pubkey_hash);
210 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.inner);
211 assert!(shutdown_script.is_compatible(&any_segwit_features()));
212 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
213 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
217 fn generates_p2wpkh_from_pubkey_hash() {
218 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
219 let p2wpkh_script = ScriptBuf::new_p2wpkh(&pubkey_hash);
221 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
222 assert!(shutdown_script.is_compatible(&any_segwit_features()));
223 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
224 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
225 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
229 fn generates_p2wsh_from_script_hash() {
230 let script_hash = redeem_script().wscript_hash();
231 let p2wsh_script = ScriptBuf::new_p2wsh(&script_hash);
233 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
234 assert!(shutdown_script.is_compatible(&any_segwit_features()));
235 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
236 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
237 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
241 fn generates_segwit_from_non_v0_witness_program() {
242 let witness_program = WitnessProgram::new(WitnessVersion::V16, &[0; 40]).unwrap();
243 let script = ScriptBuf::new_witness_program(&witness_program);
244 let shutdown_script = ShutdownScript::new_witness_program(&witness_program).unwrap();
245 assert!(shutdown_script.is_compatible(&any_segwit_features()));
246 assert!(!shutdown_script.is_compatible(&InitFeatures::empty()));
247 assert_eq!(shutdown_script.into_inner(), script);
251 fn fails_from_unsupported_script() {
252 let op_return = ScriptBuf::new_op_return(&[0; 42]);
253 assert!(ShutdownScript::try_from(op_return).is_err());