Unblock channels awaiting monitor update based on `ChanMan` queue
[rust-lightning] / lightning / src / ln / script.rs
1 //! Abstractions for scripts used in the Lightning Network.
2
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;
8
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};
13
14 use crate::io;
15
16 #[allow(unused_imports)]
17 use crate::prelude::*;
18
19 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
20 ///
21 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
22 #[derive(Clone, PartialEq, Eq)]
23 pub struct ShutdownScript(ShutdownScriptImpl);
24
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].
29         ///
30         /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
31         pub script: ScriptBuf
32 }
33
34 #[derive(Clone, PartialEq, Eq)]
35 enum ShutdownScriptImpl {
36         /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
37         /// serialization.
38         Legacy(PublicKey),
39
40         /// [`ScriptBuf`] adhering to a script pubkey format specified in BOLT #2.
41         Bolt2(ScriptBuf),
42 }
43
44 impl Writeable for ShutdownScript {
45         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
46                 self.0.write(w)
47         }
48 }
49
50 impl Readable for ShutdownScript {
51         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
52                 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
53         }
54 }
55
56 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
57         (0, Legacy),
58         (1, Bolt2),
59 );
60
61 impl ShutdownScript {
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))
65         }
66
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)))
70         }
71
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)))
75         }
76
77         /// Generates a witness script pubkey from the given segwit version and program.
78         ///
79         /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
80         /// [`ShutdownScript::new_p2wsh`] instead.
81         ///
82         /// # Errors
83         ///
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))
87         }
88
89         /// Converts the shutdown script into the underlying [`ScriptBuf`].
90         pub fn into_inner(self) -> ScriptBuf {
91                 self.into()
92         }
93
94         /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
95         pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
96                 match &self.0 {
97                         ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
98                         ShutdownScriptImpl::Bolt2(_) => None,
99                 }
100         }
101
102         /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
103         ///
104         /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
105         pub fn is_compatible(&self, features: &InitFeatures) -> bool {
106                 match &self.0 {
107                         ShutdownScriptImpl::Legacy(_) => true,
108                         ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
109                 }
110         }
111 }
112
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() {
117                 true
118         } else if features.supports_shutdown_anysegwit() {
119                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.to_u8()
120         } else {
121                 false
122         }
123 }
124
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;
129
130         fn try_from(script: ScriptBuf) -> Result<Self, Self::Error> {
131                 Self::try_from((script, &channelmanager::provided_init_features(&crate::util::config::UserConfig::default())))
132         }
133 }
134
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;
139
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)))
143                 } else {
144                         Err(InvalidShutdownScript { script })
145                 }
146         }
147 }
148
149 impl Into<ScriptBuf> for ShutdownScript {
150         fn into(self) -> ScriptBuf {
151                 match self.0 {
152                         ShutdownScriptImpl::Legacy(pubkey) =>
153                                 ScriptBuf::new_p2wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
154                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
155                 }
156         }
157 }
158
159 impl core::fmt::Display for ShutdownScript{
160         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
161                 match &self.0 {
162                         ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
163                         ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
164                 }
165         }
166 }
167
168 #[cfg(test)]
169 mod shutdown_script_tests {
170         use super::ShutdownScript;
171
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};
177
178         use crate::ln::features::InitFeatures;
179         use crate::prelude::*;
180
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))
185         }
186
187         fn redeem_script() -> ScriptBuf {
188                 let pubkey = pubkey();
189                 Builder::new()
190                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
191                         .push_key(&pubkey)
192                         .push_key(&pubkey)
193                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
194                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
195                         .into_script()
196         }
197
198         fn any_segwit_features() -> InitFeatures {
199                 let mut features = InitFeatures::empty();
200                 features.set_shutdown_any_segwit_optional();
201                 features
202         }
203
204         #[test]
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);
209
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);
214         }
215
216         #[test]
217         fn generates_p2wpkh_from_pubkey_hash() {
218                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
219                 let p2wpkh_script = ScriptBuf::new_p2wpkh(&pubkey_hash);
220
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());
226         }
227
228         #[test]
229         fn generates_p2wsh_from_script_hash() {
230                 let script_hash = redeem_script().wscript_hash();
231                 let p2wsh_script = ScriptBuf::new_p2wsh(&script_hash);
232
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());
238         }
239
240         #[test]
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);
248         }
249
250         #[test]
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());
254         }
255 }