09363b6b51749f033bb482db1ac7b50b28ffaaf2
[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::PublicKey;
8 use bitcoin::util::address::WitnessVersion;
9
10 use ln::channelmanager;
11 use ln::features::InitFeatures;
12 use ln::msgs::DecodeError;
13 use util::ser::{Readable, Writeable, Writer};
14
15 use core::convert::TryFrom;
16 use io;
17
18 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
19 ///
20 /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
21 #[derive(Clone, PartialEq)]
22 pub struct ShutdownScript(ShutdownScriptImpl);
23
24 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
25 #[derive(Clone, Debug)]
26 pub struct InvalidShutdownScript {
27         /// The script that did not meet the requirements from [BOLT #2].
28         ///
29         /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
30         pub script: Script
31 }
32
33 #[derive(Clone, PartialEq)]
34 enum ShutdownScriptImpl {
35         /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
36         /// serialization.
37         Legacy(PublicKey),
38
39         /// [`Script`] adhering to a script pubkey format specified in BOLT #2.
40         Bolt2(Script),
41 }
42
43 impl Writeable for ShutdownScript {
44         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
45                 self.0.write(w)
46         }
47
48         fn serialized_length(&self) -> usize {
49                 self.0.serialized_length()
50         }
51 }
52
53 impl Readable for ShutdownScript {
54         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
55                 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
56         }
57 }
58
59 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
60         (0, Legacy),
61         (1, Bolt2),
62 );
63
64 impl ShutdownScript {
65         /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
66         pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
67                 Self(ShutdownScriptImpl::Legacy(pubkey))
68         }
69
70         /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
71         pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
72                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wpkh(pubkey_hash)))
73         }
74
75         /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
76         pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
77                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_p2wsh(script_hash)))
78         }
79
80         /// Generates a witness script pubkey from the given segwit version and program.
81         ///
82         /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
83         /// [`ShutdownScript::new_p2wsh`] instead.
84         ///
85         /// # Errors
86         ///
87         /// This function may return an error if `program` is invalid for the segwit `version`.
88         pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
89                 let script = Builder::new()
90                         .push_int(version as i64)
91                         .push_slice(&program)
92                         .into_script();
93                 Self::try_from(script)
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 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
121 /// counterparty features.
122 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
123         if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
124                 true
125         } else if features.supports_shutdown_anysegwit() {
126                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.to_u8()
127         } else {
128                 false
129         }
130 }
131
132 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
133 // non-witness shutdown scripts which this rejects.
134 impl TryFrom<Script> for ShutdownScript {
135         type Error = InvalidShutdownScript;
136
137         fn try_from(script: Script) -> Result<Self, Self::Error> {
138                 Self::try_from((script, &channelmanager::provided_init_features()))
139         }
140 }
141
142 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
143 // non-witness shutdown scripts which this rejects.
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) && script.is_witness_program() {
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_p2wpkh(&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::blockdata::opcodes;
179         use bitcoin::blockdata::script::{Builder, Script};
180         use bitcoin::secp256k1::Secp256k1;
181         use bitcoin::secp256k1::{PublicKey, SecretKey};
182         use ln::features::InitFeatures;
183         use core::convert::TryFrom;
184         use bitcoin::util::address::WitnessVersion;
185
186         fn pubkey() -> bitcoin::util::key::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::key::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         fn any_segwit_features() -> InitFeatures {
204                 let mut features = InitFeatures::empty();
205                 features.set_shutdown_any_segwit_optional();
206                 features
207         }
208
209         #[test]
210         fn generates_p2wpkh_from_pubkey() {
211                 let pubkey = pubkey();
212                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
213                 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
214
215                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.inner);
216                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
217                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
218                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
219         }
220
221         #[test]
222         fn generates_p2wpkh_from_pubkey_hash() {
223                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
224                 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
225
226                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
227                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
228                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
229                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
230                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
231         }
232
233         #[test]
234         fn generates_p2wsh_from_script_hash() {
235                 let script_hash = redeem_script().wscript_hash();
236                 let p2wsh_script = Script::new_v0_p2wsh(&script_hash);
237
238                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
239                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
240                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
241                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
242                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
243         }
244
245         #[test]
246         fn generates_segwit_from_non_v0_witness_program() {
247                 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 40]);
248                 let shutdown_script = ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 40]).unwrap();
249                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
250                 assert!(!shutdown_script.is_compatible(&InitFeatures::empty()));
251                 assert_eq!(shutdown_script.into_inner(), witness_program);
252         }
253
254         #[test]
255         fn fails_from_unsupported_script() {
256                 let op_return = Script::new_op_return(&[0; 42]);
257                 assert!(ShutdownScript::try_from(op_return).is_err());
258         }
259
260         #[test]
261         fn fails_from_invalid_segwit_v0_witness_program() {
262                 let witness_program = Script::new_witness_program(WitnessVersion::V0, &[0; 2]);
263                 assert!(ShutdownScript::try_from(witness_program).is_err());
264         }
265
266         #[test]
267         fn fails_from_invalid_segwit_non_v0_witness_program() {
268                 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 42]);
269                 assert!(ShutdownScript::try_from(witness_program).is_err());
270
271                 assert!(ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 42]).is_err());
272         }
273 }