Avoid unnecessarily overriding `serialized_length`
[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::{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;
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 core::convert::TryFrom;
16 use crate::io;
17
18 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
19 ///
20 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
21 #[derive(Clone, PartialEq, Eq)]
22 pub struct ShutdownScript(ShutdownScriptImpl);
23
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].
28         ///
29         /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
30         pub script: Script
31 }
32
33 #[derive(Clone, PartialEq, Eq)]
34 enum ShutdownScriptImpl {
35         /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
36         /// serialization.
37         Legacy(PublicKey),
38
39         /// [`Script`] adhering to a script pubkey format specified in BOLT #2.
40         Bolt2(Script),
41 }
42
43 impl Writeable for ShutdownScript {
44         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
45                 self.0.write(w)
46         }
47 }
48
49 impl Readable for ShutdownScript {
50         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
51                 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
52         }
53 }
54
55 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
56         (0, Legacy),
57         (1, Bolt2),
58 );
59
60 impl ShutdownScript {
61         /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
62         pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
63                 Self(ShutdownScriptImpl::Legacy(pubkey))
64         }
65
66         /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
67         pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
68                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wpkh(pubkey_hash)))
69         }
70
71         /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
72         pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
73                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wsh(script_hash)))
74         }
75
76         /// Generates a witness script pubkey from the given segwit version and program.
77         ///
78         /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
79         /// [`ShutdownScript::new_p2wsh`] instead.
80         ///
81         /// # Errors
82         ///
83         /// This function may return an error if `program` is invalid for the segwit `version`.
84         pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
85                 let script = Builder::new()
86                         .push_int(version as i64)
87                         .push_slice(&program)
88                         .into_script();
89                 Self::try_from(script)
90         }
91
92         /// Converts the shutdown script into the underlying [`Script`].
93         pub fn into_inner(self) -> Script {
94                 self.into()
95         }
96
97         /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
98         pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
99                 match &self.0 {
100                         ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
101                         ShutdownScriptImpl::Bolt2(_) => None,
102                 }
103         }
104
105         /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
106         ///
107         /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
108         pub fn is_compatible(&self, features: &InitFeatures) -> bool {
109                 match &self.0 {
110                         ShutdownScriptImpl::Legacy(_) => true,
111                         ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
112                 }
113         }
114 }
115
116 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
117 /// counterparty features.
118 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
119         if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
120                 true
121         } else if features.supports_shutdown_anysegwit() {
122                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.to_u8()
123         } else {
124                 false
125         }
126 }
127
128 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
129 // non-witness shutdown scripts which this rejects.
130 impl TryFrom<Script> for ShutdownScript {
131         type Error = InvalidShutdownScript;
132
133         fn try_from(script: Script) -> Result<Self, Self::Error> {
134                 Self::try_from((script, &channelmanager::provided_init_features(&crate::util::config::UserConfig::default())))
135         }
136 }
137
138 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
139 // non-witness shutdown scripts which this rejects.
140 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
141         type Error = InvalidShutdownScript;
142
143         fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
144                 if is_bolt2_compliant(&script, features) && script.is_witness_program() {
145                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))
146                 } else {
147                         Err(InvalidShutdownScript { script })
148                 }
149         }
150 }
151
152 impl Into<Script> for ShutdownScript {
153         fn into(self) -> Script {
154                 match self.0 {
155                         ShutdownScriptImpl::Legacy(pubkey) =>
156                                 Script::new_v0_p2wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
157                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
158                 }
159         }
160 }
161
162 impl core::fmt::Display for ShutdownScript{
163         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
164                 match &self.0 {
165                         ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
166                         ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
167                 }
168         }
169 }
170
171 #[cfg(test)]
172 mod shutdown_script_tests {
173         use super::ShutdownScript;
174         use bitcoin::blockdata::opcodes;
175         use bitcoin::blockdata::script::{Builder, Script};
176         use bitcoin::secp256k1::Secp256k1;
177         use bitcoin::secp256k1::{PublicKey, SecretKey};
178         use crate::ln::features::InitFeatures;
179         use core::convert::TryFrom;
180         use bitcoin::util::address::WitnessVersion;
181
182         fn pubkey() -> bitcoin::util::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::util::key::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
186         }
187
188         fn redeem_script() -> Script {
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 = Script::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 = Script::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 = Script::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 = Script::new_witness_program(WitnessVersion::V16, &[0; 40]);
244                 let shutdown_script = ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 40]).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(), witness_program);
248         }
249
250         #[test]
251         fn fails_from_unsupported_script() {
252                 let op_return = Script::new_op_return(&[0; 42]);
253                 assert!(ShutdownScript::try_from(op_return).is_err());
254         }
255
256         #[test]
257         fn fails_from_invalid_segwit_v0_witness_program() {
258                 let witness_program = Script::new_witness_program(WitnessVersion::V0, &[0; 2]);
259                 assert!(ShutdownScript::try_from(witness_program).is_err());
260         }
261
262         #[test]
263         fn fails_from_invalid_segwit_non_v0_witness_program() {
264                 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 42]);
265                 assert!(ShutdownScript::try_from(witness_program).is_err());
266
267                 assert!(ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 42]).is_err());
268         }
269 }