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 ln::features::InitFeatures;
11 use ln::msgs::DecodeError;
12 use util::ser::{Readable, Writeable, Writer};
14 use core::convert::TryFrom;
17 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
19 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
20 #[derive(Clone, PartialEq)]
21 pub struct ShutdownScript(ShutdownScriptImpl);
23 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
24 #[derive(Clone, Debug)]
25 pub struct InvalidShutdownScript {
26 /// The script that did not meet the requirements from [BOLT #2].
28 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
32 #[derive(Clone, PartialEq)]
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 P2WPKH script pubkey from the given [`WPubkeyHash`].
70 pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
71 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wpkh(pubkey_hash)))
74 /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
75 pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
76 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wsh(script_hash)))
79 /// Generates a witness script pubkey from the given segwit version and program.
81 /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
82 /// [`ShutdownScript::new_p2wsh`] instead.
86 /// This function may return an error if `program` is invalid for the segwit `version`.
87 pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
88 let script = Builder::new()
89 .push_int(version as i64)
92 Self::try_from(script)
95 /// Converts the shutdown script into the underlying [`Script`].
96 pub fn into_inner(self) -> Script {
100 /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
101 pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
103 ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
104 ShutdownScriptImpl::Bolt2(_) => None,
108 /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
110 /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
111 pub fn is_compatible(&self, features: &InitFeatures) -> bool {
113 ShutdownScriptImpl::Legacy(_) => true,
114 ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
119 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
120 /// counterparty features.
121 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
122 if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
124 } else if features.supports_shutdown_anysegwit() {
125 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.into_u8()
131 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
132 // non-witness shutdown scripts which this rejects.
133 impl TryFrom<Script> for ShutdownScript {
134 type Error = InvalidShutdownScript;
136 fn try_from(script: Script) -> Result<Self, Self::Error> {
137 Self::try_from((script, &InitFeatures::known()))
141 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
142 // non-witness shutdown scripts which this rejects.
143 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
144 type Error = InvalidShutdownScript;
146 fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
147 if is_bolt2_compliant(&script, features) && script.is_witness_program() {
148 Ok(Self(ShutdownScriptImpl::Bolt2(script)))
150 Err(InvalidShutdownScript { script })
155 impl Into<Script> for ShutdownScript {
156 fn into(self) -> Script {
158 ShutdownScriptImpl::Legacy(pubkey) =>
159 Script::new_v0_p2wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
160 ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
165 impl core::fmt::Display for ShutdownScript{
166 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
168 ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
169 ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
175 mod shutdown_script_tests {
176 use super::ShutdownScript;
177 use bitcoin::blockdata::opcodes;
178 use bitcoin::blockdata::script::{Builder, Script};
179 use bitcoin::secp256k1::Secp256k1;
180 use bitcoin::secp256k1::{PublicKey, SecretKey};
181 use ln::features::InitFeatures;
182 use core::convert::TryFrom;
183 use bitcoin::util::address::WitnessVersion;
185 fn pubkey() -> bitcoin::util::key::PublicKey {
186 let secp_ctx = Secp256k1::signing_only();
187 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();
188 bitcoin::util::key::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
191 fn redeem_script() -> Script {
192 let pubkey = pubkey();
194 .push_opcode(opcodes::all::OP_PUSHNUM_2)
197 .push_opcode(opcodes::all::OP_PUSHNUM_2)
198 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
203 fn generates_p2wpkh_from_pubkey() {
204 let pubkey = pubkey();
205 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
206 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
208 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.inner);
209 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
210 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
211 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
215 fn generates_p2wpkh_from_pubkey_hash() {
216 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
217 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
219 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
220 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
221 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
222 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
223 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
227 fn generates_p2wsh_from_script_hash() {
228 let script_hash = redeem_script().wscript_hash();
229 let p2wsh_script = Script::new_v0_p2wsh(&script_hash);
231 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
232 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
233 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
234 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
235 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
239 fn generates_segwit_from_non_v0_witness_program() {
240 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 40]);
241 let shutdown_script = ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 40]).unwrap();
242 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
243 assert!(!shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
244 assert_eq!(shutdown_script.into_inner(), witness_program);
248 fn fails_from_unsupported_script() {
249 let op_return = Script::new_op_return(&[0; 42]);
250 assert!(ShutdownScript::try_from(op_return).is_err());
254 fn fails_from_invalid_segwit_v0_witness_program() {
255 let witness_program = Script::new_witness_program(WitnessVersion::V0, &[0; 2]);
256 assert!(ShutdownScript::try_from(witness_program).is_err());
260 fn fails_from_invalid_segwit_non_v0_witness_program() {
261 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 42]);
262 assert!(ShutdownScript::try_from(witness_program).is_err());
264 assert!(ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 42]).is_err());