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