a123de741f043c3459b5b6acd0d3d47f6bf72ae4
[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 #[cfg(test)]
167 mod shutdown_script_tests {
168         use super::ShutdownScript;
169         use bitcoin::bech32::u5;
170         use bitcoin::blockdata::opcodes;
171         use bitcoin::blockdata::script::{Builder, Script};
172         use bitcoin::secp256k1::Secp256k1;
173         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
174         use ln::features::InitFeatures;
175         use core::convert::TryFrom;
176         use core::num::NonZeroU8;
177
178         fn pubkey() -> bitcoin::util::ecdsa::PublicKey {
179                 let secp_ctx = Secp256k1::signing_only();
180                 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();
181                 bitcoin::util::ecdsa::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
182         }
183
184         fn redeem_script() -> Script {
185                 let pubkey = pubkey();
186                 Builder::new()
187                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
188                         .push_key(&pubkey)
189                         .push_key(&pubkey)
190                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
191                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
192                         .into_script()
193         }
194
195         #[test]
196         fn generates_p2wpkh_from_pubkey() {
197                 let pubkey = pubkey();
198                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
199                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
200
201                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.key);
202                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
203                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
204                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
205         }
206
207         #[test]
208         fn generates_p2pkh_from_pubkey_hash() {
209                 let pubkey_hash = pubkey().pubkey_hash();
210                 let p2pkh_script = Script::new_p2pkh(&pubkey_hash);
211
212                 let shutdown_script = ShutdownScript::new_p2pkh(&pubkey_hash);
213                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
214                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
215                 assert_eq!(shutdown_script.into_inner(), p2pkh_script);
216                 assert!(ShutdownScript::try_from(p2pkh_script).is_ok());
217         }
218
219         #[test]
220         fn generates_p2sh_from_script_hash() {
221                 let script_hash = redeem_script().script_hash();
222                 let p2sh_script = Script::new_p2sh(&script_hash);
223
224                 let shutdown_script = ShutdownScript::new_p2sh(&script_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(), p2sh_script);
228                 assert!(ShutdownScript::try_from(p2sh_script).is_ok());
229         }
230
231         #[test]
232         fn generates_p2wpkh_from_pubkey_hash() {
233                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
234                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
235
236                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_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(), p2wpkh_script);
240                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
241         }
242
243         #[test]
244         fn generates_p2wsh_from_script_hash() {
245                 let script_hash = redeem_script().wscript_hash();
246                 let p2wsh_script = Script::new_v0_wsh(&script_hash);
247
248                 let shutdown_script = ShutdownScript::new_p2wsh(&script_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(), p2wsh_script);
252                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
253         }
254
255         #[test]
256         fn generates_segwit_from_non_v0_witness_program() {
257                 let version = u5::try_from_u8(16).unwrap();
258                 let witness_program = Script::new_witness_program(version, &[0; 40]);
259
260                 let version = NonZeroU8::new(version.to_u8()).unwrap();
261                 let shutdown_script = ShutdownScript::new_witness_program(version, &[0; 40]).unwrap();
262                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
263                 assert!(!shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
264                 assert_eq!(shutdown_script.into_inner(), witness_program);
265         }
266
267         #[test]
268         fn fails_from_unsupported_script() {
269                 let op_return = Script::new_op_return(&[0; 42]);
270                 assert!(ShutdownScript::try_from(op_return).is_err());
271         }
272
273         #[test]
274         fn fails_from_invalid_segwit_version() {
275                 let version = NonZeroU8::new(17).unwrap();
276                 assert!(ShutdownScript::new_witness_program(version, &[0; 40]).is_err());
277         }
278
279         #[test]
280         fn fails_from_invalid_segwit_v0_witness_program() {
281                 let witness_program = Script::new_witness_program(u5::try_from_u8(0).unwrap(), &[0; 2]);
282                 assert!(ShutdownScript::try_from(witness_program).is_err());
283         }
284
285         #[test]
286         fn fails_from_invalid_segwit_non_v0_witness_program() {
287                 let version = u5::try_from_u8(16).unwrap();
288                 let witness_program = Script::new_witness_program(version, &[0; 42]);
289                 assert!(ShutdownScript::try_from(witness_program).is_err());
290
291                 let version = NonZeroU8::new(version.to_u8()).unwrap();
292                 assert!(ShutdownScript::new_witness_program(version, &[0; 42]).is_err());
293         }
294 }