3abb334ce478878d154f98b618df1c6ea6e1affe
[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 P2WSH script pubkey from the given segwit version and program.
90         ///
91         /// # Errors
92         ///
93         /// This function may return an error if `program` is invalid for the segwit `version`.
94         pub fn new_witness_program(version: NonZeroU8, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
95                 let script = Builder::new()
96                         .push_int(version.get().into())
97                         .push_slice(&program)
98                         .into_script();
99                 Self::try_from(script)
100         }
101
102         /// Converts the shutdown script into the underlying [`Script`].
103         pub fn into_inner(self) -> Script {
104                 self.into()
105         }
106
107         /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
108         pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
109                 match &self.0 {
110                         ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
111                         ShutdownScriptImpl::Bolt2(_) => None,
112                 }
113         }
114
115         /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
116         ///
117         /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
118         pub fn is_compatible(&self, features: &InitFeatures) -> bool {
119                 match &self.0 {
120                         ShutdownScriptImpl::Legacy(_) => true,
121                         ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
122                 }
123         }
124 }
125
126 fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
127         if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
128                 true
129         } else if features.supports_shutdown_anysegwit() {
130                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.into_u8()
131         } else {
132                 false
133         }
134 }
135
136 impl TryFrom<Script> for ShutdownScript {
137         type Error = InvalidShutdownScript;
138
139         fn try_from(script: Script) -> Result<Self, Self::Error> {
140                 Self::try_from((script, &InitFeatures::known()))
141         }
142 }
143
144 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
145         type Error = InvalidShutdownScript;
146
147         fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
148                 if is_bolt2_compliant(&script, features) {
149                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))
150                 } else {
151                         Err(InvalidShutdownScript { script })
152                 }
153         }
154 }
155
156 impl Into<Script> for ShutdownScript {
157         fn into(self) -> Script {
158                 match self.0 {
159                         ShutdownScriptImpl::Legacy(pubkey) =>
160                                 Script::new_v0_wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
161                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
162                 }
163         }
164 }
165
166 impl core::fmt::Display for ShutdownScript{
167         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
168                 match &self.0 {
169                         ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
170                         ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
171                 }
172         }
173 }
174
175 #[cfg(test)]
176 mod shutdown_script_tests {
177         use super::ShutdownScript;
178         use bitcoin::bech32::u5;
179         use bitcoin::blockdata::opcodes;
180         use bitcoin::blockdata::script::{Builder, Script};
181         use bitcoin::secp256k1::Secp256k1;
182         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
183         use ln::features::InitFeatures;
184         use core::convert::TryFrom;
185         use core::num::NonZeroU8;
186
187         fn pubkey() -> bitcoin::util::ecdsa::PublicKey {
188                 let secp_ctx = Secp256k1::signing_only();
189                 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();
190                 bitcoin::util::ecdsa::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
191         }
192
193         fn redeem_script() -> Script {
194                 let pubkey = pubkey();
195                 Builder::new()
196                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
197                         .push_key(&pubkey)
198                         .push_key(&pubkey)
199                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
200                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
201                         .into_script()
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 = Script::new_v0_wpkh(&pubkey_hash);
209
210                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.key);
211                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
212                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
213                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
214         }
215
216         #[test]
217         fn generates_p2pkh_from_pubkey_hash() {
218                 let pubkey_hash = pubkey().pubkey_hash();
219                 let p2pkh_script = Script::new_p2pkh(&pubkey_hash);
220
221                 let shutdown_script = ShutdownScript::new_p2pkh(&pubkey_hash);
222                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
223                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
224                 assert_eq!(shutdown_script.into_inner(), p2pkh_script);
225                 assert!(ShutdownScript::try_from(p2pkh_script).is_ok());
226         }
227
228         #[test]
229         fn generates_p2sh_from_script_hash() {
230                 let script_hash = redeem_script().script_hash();
231                 let p2sh_script = Script::new_p2sh(&script_hash);
232
233                 let shutdown_script = ShutdownScript::new_p2sh(&script_hash);
234                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
235                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
236                 assert_eq!(shutdown_script.into_inner(), p2sh_script);
237                 assert!(ShutdownScript::try_from(p2sh_script).is_ok());
238         }
239
240         #[test]
241         fn generates_p2wpkh_from_pubkey_hash() {
242                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
243                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
244
245                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
246                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
247                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
248                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
249                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
250         }
251
252         #[test]
253         fn generates_p2wsh_from_script_hash() {
254                 let script_hash = redeem_script().wscript_hash();
255                 let p2wsh_script = Script::new_v0_wsh(&script_hash);
256
257                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
258                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
259                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
260                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
261                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
262         }
263
264         #[test]
265         fn generates_segwit_from_non_v0_witness_program() {
266                 let version = u5::try_from_u8(16).unwrap();
267                 let witness_program = Script::new_witness_program(version, &[0; 40]);
268
269                 let version = NonZeroU8::new(version.to_u8()).unwrap();
270                 let shutdown_script = ShutdownScript::new_witness_program(version, &[0; 40]).unwrap();
271                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
272                 assert!(!shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
273                 assert_eq!(shutdown_script.into_inner(), witness_program);
274         }
275
276         #[test]
277         fn fails_from_unsupported_script() {
278                 let op_return = Script::new_op_return(&[0; 42]);
279                 assert!(ShutdownScript::try_from(op_return).is_err());
280         }
281
282         #[test]
283         fn fails_from_invalid_segwit_version() {
284                 let version = NonZeroU8::new(17).unwrap();
285                 assert!(ShutdownScript::new_witness_program(version, &[0; 40]).is_err());
286         }
287
288         #[test]
289         fn fails_from_invalid_segwit_v0_witness_program() {
290                 let witness_program = Script::new_witness_program(u5::try_from_u8(0).unwrap(), &[0; 2]);
291                 assert!(ShutdownScript::try_from(witness_program).is_err());
292         }
293
294         #[test]
295         fn fails_from_invalid_segwit_non_v0_witness_program() {
296                 let version = u5::try_from_u8(16).unwrap();
297                 let witness_program = Script::new_witness_program(version, &[0; 42]);
298                 assert!(ShutdownScript::try_from(witness_program).is_err());
299
300                 let version = NonZeroU8::new(version.to_u8()).unwrap();
301                 assert!(ShutdownScript::new_witness_program(version, &[0; 42]).is_err());
302         }
303 }