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::{WPubkeyHash, WScriptHash};
7 use bitcoin::secp256k1::PublicKey;
8 use bitcoin::util::address::WitnessVersion;
10 use crate::ln::channelmanager;
11 use crate::ln::features::InitFeatures;
12 use crate::ln::msgs::DecodeError;
13 use crate::util::ser::{Readable, Writeable, Writer};
15 use core::convert::TryFrom;
18 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
20 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
21 #[derive(Clone, PartialEq, Eq)]
22 pub struct ShutdownScript(ShutdownScriptImpl);
24 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
25 #[derive(Clone, Debug)]
26 pub struct InvalidShutdownScript {
27 /// The script that did not meet the requirements from [BOLT #2].
29 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
33 #[derive(Clone, PartialEq, Eq)]
34 enum ShutdownScriptImpl {
35 /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
39 /// [`Script`] adhering to a script pubkey format specified in BOLT #2.
43 impl Writeable for ShutdownScript {
44 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
48 fn serialized_length(&self) -> usize {
49 self.0.serialized_length()
53 impl Readable for ShutdownScript {
54 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
55 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
59 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
65 /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
66 pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
67 Self(ShutdownScriptImpl::Legacy(pubkey))
70 /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
71 pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
72 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wpkh(pubkey_hash)))
75 /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
76 pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
77 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wsh(script_hash)))
80 /// Generates a witness script pubkey from the given segwit version and program.
82 /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
83 /// [`ShutdownScript::new_p2wsh`] instead.
87 /// This function may return an error if `program` is invalid for the segwit `version`.
88 pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
89 let script = Builder::new()
90 .push_int(version as i64)
93 Self::try_from(script)
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,
109 /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
111 /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
112 pub fn is_compatible(&self, features: &InitFeatures) -> bool {
114 ShutdownScriptImpl::Legacy(_) => true,
115 ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
120 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
121 /// counterparty features.
122 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
123 if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
125 } else if features.supports_shutdown_anysegwit() {
126 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.to_u8()
132 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
133 // non-witness shutdown scripts which this rejects.
134 impl TryFrom<Script> for ShutdownScript {
135 type Error = InvalidShutdownScript;
137 fn try_from(script: Script) -> Result<Self, Self::Error> {
138 Self::try_from((script, &channelmanager::provided_init_features(&crate::util::config::UserConfig::default())))
142 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
143 // non-witness shutdown scripts which this rejects.
144 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
145 type Error = InvalidShutdownScript;
147 fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
148 if is_bolt2_compliant(&script, features) && script.is_witness_program() {
149 Ok(Self(ShutdownScriptImpl::Bolt2(script)))
151 Err(InvalidShutdownScript { script })
156 impl Into<Script> for ShutdownScript {
157 fn into(self) -> Script {
159 ShutdownScriptImpl::Legacy(pubkey) =>
160 Script::new_v0_p2wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
161 ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
166 impl core::fmt::Display for ShutdownScript{
167 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
169 ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
170 ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
176 mod shutdown_script_tests {
177 use super::ShutdownScript;
178 use bitcoin::blockdata::opcodes;
179 use bitcoin::blockdata::script::{Builder, Script};
180 use bitcoin::secp256k1::Secp256k1;
181 use bitcoin::secp256k1::{PublicKey, SecretKey};
182 use crate::ln::features::InitFeatures;
183 use core::convert::TryFrom;
184 use bitcoin::util::address::WitnessVersion;
186 fn pubkey() -> bitcoin::util::key::PublicKey {
187 let secp_ctx = Secp256k1::signing_only();
188 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();
189 bitcoin::util::key::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
192 fn redeem_script() -> Script {
193 let pubkey = pubkey();
195 .push_opcode(opcodes::all::OP_PUSHNUM_2)
198 .push_opcode(opcodes::all::OP_PUSHNUM_2)
199 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
203 fn any_segwit_features() -> InitFeatures {
204 let mut features = InitFeatures::empty();
205 features.set_shutdown_any_segwit_optional();
210 fn generates_p2wpkh_from_pubkey() {
211 let pubkey = pubkey();
212 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
213 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
215 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.inner);
216 assert!(shutdown_script.is_compatible(&any_segwit_features()));
217 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
218 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
222 fn generates_p2wpkh_from_pubkey_hash() {
223 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
224 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
226 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
227 assert!(shutdown_script.is_compatible(&any_segwit_features()));
228 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
229 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
230 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
234 fn generates_p2wsh_from_script_hash() {
235 let script_hash = redeem_script().wscript_hash();
236 let p2wsh_script = Script::new_v0_p2wsh(&script_hash);
238 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
239 assert!(shutdown_script.is_compatible(&any_segwit_features()));
240 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
241 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
242 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
246 fn generates_segwit_from_non_v0_witness_program() {
247 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 40]);
248 let shutdown_script = ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 40]).unwrap();
249 assert!(shutdown_script.is_compatible(&any_segwit_features()));
250 assert!(!shutdown_script.is_compatible(&InitFeatures::empty()));
251 assert_eq!(shutdown_script.into_inner(), witness_program);
255 fn fails_from_unsupported_script() {
256 let op_return = Script::new_op_return(&[0; 42]);
257 assert!(ShutdownScript::try_from(op_return).is_err());
261 fn fails_from_invalid_segwit_v0_witness_program() {
262 let witness_program = Script::new_witness_program(WitnessVersion::V0, &[0; 2]);
263 assert!(ShutdownScript::try_from(witness_program).is_err());
267 fn fails_from_invalid_segwit_non_v0_witness_program() {
268 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 42]);
269 assert!(ShutdownScript::try_from(witness_program).is_err());
271 assert!(ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 42]).is_err());