Clarify docs on ShutdownScript::new_witness_program somewhat
[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::{PubkeyHash, ScriptHash, WPubkeyHash, WScriptHash};
7 use bitcoin::secp256k1::key::PublicKey;
8
9 use ln::features::InitFeatures;
10 use ln::msgs::DecodeError;
11 use util::ser::{Readable, Writeable, Writer};
12
13 use core::convert::TryFrom;
14 use core::num::NonZeroU8;
15 use io;
16
17 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
18 ///
19 /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md
20 #[derive(Clone)]
21 pub struct ShutdownScript(ShutdownScriptImpl);
22
23 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
24 #[derive(Debug)]
25 pub struct InvalidShutdownScript {
26         /// The script that did not meet the requirements from [BOLT #2].
27         ///
28         /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md
29         pub script: Script
30 }
31
32 #[derive(Clone)]
33 enum ShutdownScriptImpl {
34         /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
35         /// serialization.
36         Legacy(PublicKey),
37
38         /// [`Script`] adhering to a script pubkey format specified in BOLT #2.
39         Bolt2(Script),
40 }
41
42 impl Writeable for ShutdownScript {
43         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
44                 self.0.write(w)
45         }
46
47         fn serialized_length(&self) -> usize {
48                 self.0.serialized_length()
49         }
50 }
51
52 impl Readable for ShutdownScript {
53         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
54                 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
55         }
56 }
57
58 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
59         (0, Legacy),
60         (1, Bolt2),
61 );
62
63 impl ShutdownScript {
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))
67         }
68
69         /// Generates a P2PKH script pubkey from the given [`PubkeyHash`].
70         pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Self {
71                 Self(ShutdownScriptImpl::Bolt2(Script::new_p2pkh(pubkey_hash)))
72         }
73
74         /// Generates a P2SH script pubkey from the given [`ScriptHash`].
75         pub fn new_p2sh(script_hash: &ScriptHash) -> Self {
76                 Self(ShutdownScriptImpl::Bolt2(Script::new_p2sh(script_hash)))
77         }
78
79         /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
80         pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
81                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wpkh(pubkey_hash)))
82         }
83
84         /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
85         pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
86                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wsh(script_hash)))
87         }
88
89         /// Generates a witness script pubkey from the given segwit version and program.
90         ///
91         /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
92         /// [`ShutdownScript::new_p2wsh`] instead.
93         ///
94         /// # Errors
95         ///
96         /// This function may return an error if `program` is invalid for the segwit `version`.
97         pub fn new_witness_program(version: NonZeroU8, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
98                 let script = Builder::new()
99                         .push_int(version.get().into())
100                         .push_slice(&program)
101                         .into_script();
102                 Self::try_from(script)
103         }
104
105         /// Converts the shutdown script into the underlying [`Script`].
106         pub fn into_inner(self) -> Script {
107                 self.into()
108         }
109
110         /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
111         pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
112                 match &self.0 {
113                         ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
114                         ShutdownScriptImpl::Bolt2(_) => None,
115                 }
116         }
117
118         /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
119         ///
120         /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
121         pub fn is_compatible(&self, features: &InitFeatures) -> bool {
122                 match &self.0 {
123                         ShutdownScriptImpl::Legacy(_) => true,
124                         ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
125                 }
126         }
127 }
128
129 fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
130         if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
131                 true
132         } else if features.supports_shutdown_anysegwit() {
133                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.into_u8()
134         } else {
135                 false
136         }
137 }
138
139 impl TryFrom<Script> for ShutdownScript {
140         type Error = InvalidShutdownScript;
141
142         fn try_from(script: Script) -> Result<Self, Self::Error> {
143                 Self::try_from((script, &InitFeatures::known()))
144         }
145 }
146
147 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
148         type Error = InvalidShutdownScript;
149
150         fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
151                 if is_bolt2_compliant(&script, features) {
152                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))
153                 } else {
154                         Err(InvalidShutdownScript { script })
155                 }
156         }
157 }
158
159 impl Into<Script> for ShutdownScript {
160         fn into(self) -> Script {
161                 match self.0 {
162                         ShutdownScriptImpl::Legacy(pubkey) =>
163                                 Script::new_v0_wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
164                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
165                 }
166         }
167 }
168
169 impl core::fmt::Display for ShutdownScript{
170         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
171                 match &self.0 {
172                         ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
173                         ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
174                 }
175         }
176 }
177
178 #[cfg(test)]
179 mod shutdown_script_tests {
180         use super::ShutdownScript;
181         use bitcoin::bech32::u5;
182         use bitcoin::blockdata::opcodes;
183         use bitcoin::blockdata::script::{Builder, Script};
184         use bitcoin::secp256k1::Secp256k1;
185         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
186         use ln::features::InitFeatures;
187         use core::convert::TryFrom;
188         use core::num::NonZeroU8;
189
190         fn pubkey() -> bitcoin::util::ecdsa::PublicKey {
191                 let secp_ctx = Secp256k1::signing_only();
192                 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();
193                 bitcoin::util::ecdsa::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
194         }
195
196         fn redeem_script() -> Script {
197                 let pubkey = pubkey();
198                 Builder::new()
199                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
200                         .push_key(&pubkey)
201                         .push_key(&pubkey)
202                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
203                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
204                         .into_script()
205         }
206
207         #[test]
208         fn generates_p2wpkh_from_pubkey() {
209                 let pubkey = pubkey();
210                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
211                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
212
213                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.key);
214                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
215                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
216                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
217         }
218
219         #[test]
220         fn generates_p2pkh_from_pubkey_hash() {
221                 let pubkey_hash = pubkey().pubkey_hash();
222                 let p2pkh_script = Script::new_p2pkh(&pubkey_hash);
223
224                 let shutdown_script = ShutdownScript::new_p2pkh(&pubkey_hash);
225                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
226                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
227                 assert_eq!(shutdown_script.into_inner(), p2pkh_script);
228                 assert!(ShutdownScript::try_from(p2pkh_script).is_ok());
229         }
230
231         #[test]
232         fn generates_p2sh_from_script_hash() {
233                 let script_hash = redeem_script().script_hash();
234                 let p2sh_script = Script::new_p2sh(&script_hash);
235
236                 let shutdown_script = ShutdownScript::new_p2sh(&script_hash);
237                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
238                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
239                 assert_eq!(shutdown_script.into_inner(), p2sh_script);
240                 assert!(ShutdownScript::try_from(p2sh_script).is_ok());
241         }
242
243         #[test]
244         fn generates_p2wpkh_from_pubkey_hash() {
245                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
246                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
247
248                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
249                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
250                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
251                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
252                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
253         }
254
255         #[test]
256         fn generates_p2wsh_from_script_hash() {
257                 let script_hash = redeem_script().wscript_hash();
258                 let p2wsh_script = Script::new_v0_wsh(&script_hash);
259
260                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
261                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
262                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
263                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
264                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
265         }
266
267         #[test]
268         fn generates_segwit_from_non_v0_witness_program() {
269                 let version = u5::try_from_u8(16).unwrap();
270                 let witness_program = Script::new_witness_program(version, &[0; 40]);
271
272                 let version = NonZeroU8::new(version.to_u8()).unwrap();
273                 let shutdown_script = ShutdownScript::new_witness_program(version, &[0; 40]).unwrap();
274                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
275                 assert!(!shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
276                 assert_eq!(shutdown_script.into_inner(), witness_program);
277         }
278
279         #[test]
280         fn fails_from_unsupported_script() {
281                 let op_return = Script::new_op_return(&[0; 42]);
282                 assert!(ShutdownScript::try_from(op_return).is_err());
283         }
284
285         #[test]
286         fn fails_from_invalid_segwit_version() {
287                 let version = NonZeroU8::new(17).unwrap();
288                 assert!(ShutdownScript::new_witness_program(version, &[0; 40]).is_err());
289         }
290
291         #[test]
292         fn fails_from_invalid_segwit_v0_witness_program() {
293                 let witness_program = Script::new_witness_program(u5::try_from_u8(0).unwrap(), &[0; 2]);
294                 assert!(ShutdownScript::try_from(witness_program).is_err());
295         }
296
297         #[test]
298         fn fails_from_invalid_segwit_non_v0_witness_program() {
299                 let version = u5::try_from_u8(16).unwrap();
300                 let witness_program = Script::new_witness_program(version, &[0; 42]);
301                 assert!(ShutdownScript::try_from(witness_program).is_err());
302
303                 let version = NonZeroU8::new(version.to_u8()).unwrap();
304                 assert!(ShutdownScript::new_witness_program(version, &[0; 42]).is_err());
305         }
306 }