Use `crate::prelude::*` rather than specific imports
[rust-lightning] / lightning / src / ln / script.rs
1 //! Abstractions for scripts used in the Lightning Network.
2
3 use bitcoin::blockdata::opcodes::all::OP_PUSHBYTES_0 as SEGWIT_V0;
4 use bitcoin::blockdata::script::{Script, ScriptBuf};
5 use bitcoin::hashes::Hash;
6 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
7 use bitcoin::secp256k1::PublicKey;
8 use bitcoin::address::WitnessProgram;
9
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};
14
15 use crate::io;
16
17 #[allow(unused_imports)]
18 use crate::prelude::*;
19
20 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
21 ///
22 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
23 #[derive(Clone, PartialEq, Eq)]
24 pub struct ShutdownScript(ShutdownScriptImpl);
25
26 /// An error occurring when converting from [`ScriptBuf`] to [`ShutdownScript`].
27 #[derive(Clone, Debug)]
28 pub struct InvalidShutdownScript {
29         /// The script that did not meet the requirements from [BOLT #2].
30         ///
31         /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
32         pub script: ScriptBuf
33 }
34
35 #[derive(Clone, PartialEq, Eq)]
36 enum ShutdownScriptImpl {
37         /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
38         /// serialization.
39         Legacy(PublicKey),
40
41         /// [`ScriptBuf`] adhering to a script pubkey format specified in BOLT #2.
42         Bolt2(ScriptBuf),
43 }
44
45 impl Writeable for ShutdownScript {
46         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
47                 self.0.write(w)
48         }
49 }
50
51 impl Readable for ShutdownScript {
52         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
53                 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
54         }
55 }
56
57 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
58         (0, Legacy),
59         (1, Bolt2),
60 );
61
62 impl ShutdownScript {
63         /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
64         pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
65                 Self(ShutdownScriptImpl::Legacy(pubkey))
66         }
67
68         /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
69         pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
70                 Self(ShutdownScriptImpl::Bolt2(ScriptBuf::new_v0_p2wpkh(pubkey_hash)))
71         }
72
73         /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
74         pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
75                 Self(ShutdownScriptImpl::Bolt2(ScriptBuf::new_v0_p2wsh(script_hash)))
76         }
77
78         /// Generates a witness script pubkey from the given segwit version and program.
79         ///
80         /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
81         /// [`ShutdownScript::new_p2wsh`] instead.
82         ///
83         /// # Errors
84         ///
85         /// This function may return an error if `program` is invalid for the segwit `version`.
86         pub fn new_witness_program(witness_program: &WitnessProgram) -> Result<Self, InvalidShutdownScript> {
87                 Self::try_from(ScriptBuf::new_witness_program(witness_program))
88         }
89
90         /// Converts the shutdown script into the underlying [`ScriptBuf`].
91         pub fn into_inner(self) -> ScriptBuf {
92                 self.into()
93         }
94
95         /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
96         pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
97                 match &self.0 {
98                         ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
99                         ShutdownScriptImpl::Bolt2(_) => None,
100                 }
101         }
102
103         /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
104         ///
105         /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
106         pub fn is_compatible(&self, features: &InitFeatures) -> bool {
107                 match &self.0 {
108                         ShutdownScriptImpl::Legacy(_) => true,
109                         ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
110                 }
111         }
112 }
113
114 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
115 /// counterparty features.
116 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
117         if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
118                 true
119         } else if features.supports_shutdown_anysegwit() {
120                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.to_u8()
121         } else {
122                 false
123         }
124 }
125
126 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
127 // non-witness shutdown scripts which this rejects.
128 impl TryFrom<ScriptBuf> for ShutdownScript {
129         type Error = InvalidShutdownScript;
130
131         fn try_from(script: ScriptBuf) -> Result<Self, Self::Error> {
132                 Self::try_from((script, &channelmanager::provided_init_features(&crate::util::config::UserConfig::default())))
133         }
134 }
135
136 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
137 // non-witness shutdown scripts which this rejects.
138 impl TryFrom<(ScriptBuf, &InitFeatures)> for ShutdownScript {
139         type Error = InvalidShutdownScript;
140
141         fn try_from((script, features): (ScriptBuf, &InitFeatures)) -> Result<Self, Self::Error> {
142                 if is_bolt2_compliant(&script, features) && script.is_witness_program() {
143                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))
144                 } else {
145                         Err(InvalidShutdownScript { script })
146                 }
147         }
148 }
149
150 impl Into<ScriptBuf> for ShutdownScript {
151         fn into(self) -> ScriptBuf {
152                 match self.0 {
153                         ShutdownScriptImpl::Legacy(pubkey) =>
154                                 ScriptBuf::new_v0_p2wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
155                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
156                 }
157         }
158 }
159
160 impl core::fmt::Display for ShutdownScript{
161         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
162                 match &self.0 {
163                         ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
164                         ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
165                 }
166         }
167 }
168
169 #[cfg(test)]
170 mod shutdown_script_tests {
171         use super::ShutdownScript;
172
173         use bitcoin::address::{WitnessProgram, WitnessVersion};
174         use bitcoin::blockdata::opcodes;
175         use bitcoin::blockdata::script::{Builder, ScriptBuf};
176         use bitcoin::secp256k1::Secp256k1;
177         use bitcoin::secp256k1::{PublicKey, SecretKey};
178
179         use crate::ln::features::InitFeatures;
180         use crate::prelude::*;
181
182         fn pubkey() -> bitcoin::key::PublicKey {
183                 let secp_ctx = Secp256k1::signing_only();
184                 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();
185                 bitcoin::key::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
186         }
187
188         fn redeem_script() -> ScriptBuf {
189                 let pubkey = pubkey();
190                 Builder::new()
191                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
192                         .push_key(&pubkey)
193                         .push_key(&pubkey)
194                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
195                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
196                         .into_script()
197         }
198
199         fn any_segwit_features() -> InitFeatures {
200                 let mut features = InitFeatures::empty();
201                 features.set_shutdown_any_segwit_optional();
202                 features
203         }
204
205         #[test]
206         fn generates_p2wpkh_from_pubkey() {
207                 let pubkey = pubkey();
208                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
209                 let p2wpkh_script = ScriptBuf::new_v0_p2wpkh(&pubkey_hash);
210
211                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.inner);
212                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
213                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
214                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
215         }
216
217         #[test]
218         fn generates_p2wpkh_from_pubkey_hash() {
219                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
220                 let p2wpkh_script = ScriptBuf::new_v0_p2wpkh(&pubkey_hash);
221
222                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
223                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
224                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
225                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
226                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
227         }
228
229         #[test]
230         fn generates_p2wsh_from_script_hash() {
231                 let script_hash = redeem_script().wscript_hash();
232                 let p2wsh_script = ScriptBuf::new_v0_p2wsh(&script_hash);
233
234                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
235                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
236                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
237                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
238                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
239         }
240
241         #[test]
242         fn generates_segwit_from_non_v0_witness_program() {
243                 let witness_program = WitnessProgram::new(WitnessVersion::V16, &[0; 40]).unwrap();
244                 let script = ScriptBuf::new_witness_program(&witness_program);
245                 let shutdown_script = ShutdownScript::new_witness_program(&witness_program).unwrap();
246                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
247                 assert!(!shutdown_script.is_compatible(&InitFeatures::empty()));
248                 assert_eq!(shutdown_script.into_inner(), script);
249         }
250
251         #[test]
252         fn fails_from_unsupported_script() {
253                 let op_return = ScriptBuf::new_op_return(&[0; 42]);
254                 assert!(ShutdownScript::try_from(op_return).is_err());
255         }
256 }