Require user cooperative close payout scripts to be Segwit
[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::{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 P2WPKH script pubkey from the given [`WPubkeyHash`].
70         pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
71                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wpkh(pubkey_hash)))
72         }
73
74         /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
75         pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
76                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wsh(script_hash)))
77         }
78
79         /// Generates a witness script pubkey from the given segwit version and program.
80         ///
81         /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
82         /// [`ShutdownScript::new_p2wsh`] instead.
83         ///
84         /// # Errors
85         ///
86         /// This function may return an error if `program` is invalid for the segwit `version`.
87         pub fn new_witness_program(version: NonZeroU8, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
88                 let script = Builder::new()
89                         .push_int(version.get().into())
90                         .push_slice(&program)
91                         .into_script();
92                 Self::try_from(script)
93         }
94
95         /// Converts the shutdown script into the underlying [`Script`].
96         pub fn into_inner(self) -> Script {
97                 self.into()
98         }
99
100         /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
101         pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
102                 match &self.0 {
103                         ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
104                         ShutdownScriptImpl::Bolt2(_) => None,
105                 }
106         }
107
108         /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
109         ///
110         /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
111         pub fn is_compatible(&self, features: &InitFeatures) -> bool {
112                 match &self.0 {
113                         ShutdownScriptImpl::Legacy(_) => true,
114                         ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
115                 }
116         }
117 }
118
119 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
120 /// counterparty features.
121 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
122         if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
123                 true
124         } else if features.supports_shutdown_anysegwit() {
125                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.into_u8()
126         } else {
127                 false
128         }
129 }
130
131 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
132 // non-witness shutdown scripts which this rejects.
133 impl TryFrom<Script> for ShutdownScript {
134         type Error = InvalidShutdownScript;
135
136         fn try_from(script: Script) -> Result<Self, Self::Error> {
137                 Self::try_from((script, &InitFeatures::known()))
138         }
139 }
140
141 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
142 // non-witness shutdown scripts which this rejects.
143 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
144         type Error = InvalidShutdownScript;
145
146         fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
147                 if is_bolt2_compliant(&script, features) && script.is_witness_program() {
148                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))
149                 } else {
150                         Err(InvalidShutdownScript { script })
151                 }
152         }
153 }
154
155 impl Into<Script> for ShutdownScript {
156         fn into(self) -> Script {
157                 match self.0 {
158                         ShutdownScriptImpl::Legacy(pubkey) =>
159                                 Script::new_v0_wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
160                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
161                 }
162         }
163 }
164
165 impl core::fmt::Display for ShutdownScript{
166         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
167                 match &self.0 {
168                         ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
169                         ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
170                 }
171         }
172 }
173
174 #[cfg(test)]
175 mod shutdown_script_tests {
176         use super::ShutdownScript;
177         use bitcoin::bech32::u5;
178         use bitcoin::blockdata::opcodes;
179         use bitcoin::blockdata::script::{Builder, Script};
180         use bitcoin::secp256k1::Secp256k1;
181         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
182         use ln::features::InitFeatures;
183         use core::convert::TryFrom;
184         use core::num::NonZeroU8;
185
186         fn pubkey() -> bitcoin::util::ecdsa::PublicKey {
187                 let secp_ctx = Secp256k1::signing_only();
188                 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();
189                 bitcoin::util::ecdsa::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
190         }
191
192         fn redeem_script() -> Script {
193                 let pubkey = pubkey();
194                 Builder::new()
195                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
196                         .push_key(&pubkey)
197                         .push_key(&pubkey)
198                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
199                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
200                         .into_script()
201         }
202
203         #[test]
204         fn generates_p2wpkh_from_pubkey() {
205                 let pubkey = pubkey();
206                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
207                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
208
209                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.key);
210                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
211                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
212                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
213         }
214
215         #[test]
216         fn generates_p2wpkh_from_pubkey_hash() {
217                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
218                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
219
220                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
221                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
222                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
223                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
224                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
225         }
226
227         #[test]
228         fn generates_p2wsh_from_script_hash() {
229                 let script_hash = redeem_script().wscript_hash();
230                 let p2wsh_script = Script::new_v0_wsh(&script_hash);
231
232                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
233                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
234                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
235                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
236                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
237         }
238
239         #[test]
240         fn generates_segwit_from_non_v0_witness_program() {
241                 let version = u5::try_from_u8(16).unwrap();
242                 let witness_program = Script::new_witness_program(version, &[0; 40]);
243
244                 let version = NonZeroU8::new(version.to_u8()).unwrap();
245                 let shutdown_script = ShutdownScript::new_witness_program(version, &[0; 40]).unwrap();
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(), witness_program);
249         }
250
251         #[test]
252         fn fails_from_unsupported_script() {
253                 let op_return = Script::new_op_return(&[0; 42]);
254                 assert!(ShutdownScript::try_from(op_return).is_err());
255         }
256
257         #[test]
258         fn fails_from_invalid_segwit_version() {
259                 let version = NonZeroU8::new(17).unwrap();
260                 assert!(ShutdownScript::new_witness_program(version, &[0; 40]).is_err());
261         }
262
263         #[test]
264         fn fails_from_invalid_segwit_v0_witness_program() {
265                 let witness_program = Script::new_witness_program(u5::try_from_u8(0).unwrap(), &[0; 2]);
266                 assert!(ShutdownScript::try_from(witness_program).is_err());
267         }
268
269         #[test]
270         fn fails_from_invalid_segwit_non_v0_witness_program() {
271                 let version = u5::try_from_u8(16).unwrap();
272                 let witness_program = Script::new_witness_program(version, &[0; 42]);
273                 assert!(ShutdownScript::try_from(witness_program).is_err());
274
275                 let version = NonZeroU8::new(version.to_u8()).unwrap();
276                 assert!(ShutdownScript::new_witness_program(version, &[0; 42]).is_err());
277         }
278 }