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