dc733dd25a1f0ca154c773f1987d4861e4d30a23
[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::{Script, ScriptBuf};
5 use bitcoin::hashes::Hash;
6 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
7 use bitcoin::secp256k1::PublicKey;
8 use bitcoin::address::WitnessProgram;
9
10 use crate::ln::channelmanager;
11 use crate::ln::features::InitFeatures;
12 use crate::ln::msgs::DecodeError;
13 use crate::util::ser::{Readable, Writeable, Writer};
14
15 use core::convert::TryFrom;
16 use crate::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, Eq)]
22 pub struct ShutdownScript(ShutdownScriptImpl);
23
24 /// An error occurring when converting from [`ScriptBuf`] 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: ScriptBuf
31 }
32
33 #[derive(Clone, PartialEq, Eq)]
34 enum ShutdownScriptImpl {
35         /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
36         /// serialization.
37         Legacy(PublicKey),
38
39         /// [`ScriptBuf`] adhering to a script pubkey format specified in BOLT #2.
40         Bolt2(ScriptBuf),
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
49 impl Readable for ShutdownScript {
50         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
51                 Ok(ShutdownScript(ShutdownScriptImpl::read(r)?))
52         }
53 }
54
55 impl_writeable_tlv_based_enum!(ShutdownScriptImpl, ;
56         (0, Legacy),
57         (1, Bolt2),
58 );
59
60 impl ShutdownScript {
61         /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
62         pub(crate) fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
63                 Self(ShutdownScriptImpl::Legacy(pubkey))
64         }
65
66         /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
67         pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
68                 Self(ShutdownScriptImpl::Bolt2(ScriptBuf::new_v0_p2wpkh(pubkey_hash)))
69         }
70
71         /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
72         pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
73                 Self(ShutdownScriptImpl::Bolt2(ScriptBuf::new_v0_p2wsh(script_hash)))
74         }
75
76         /// Generates a witness script pubkey from the given segwit version and program.
77         ///
78         /// Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
79         /// [`ShutdownScript::new_p2wsh`] instead.
80         ///
81         /// # Errors
82         ///
83         /// This function may return an error if `program` is invalid for the segwit `version`.
84         pub fn new_witness_program(witness_program: &WitnessProgram) -> Result<Self, InvalidShutdownScript> {
85                 Self::try_from(ScriptBuf::new_witness_program(witness_program))
86         }
87
88         /// Converts the shutdown script into the underlying [`ScriptBuf`].
89         pub fn into_inner(self) -> ScriptBuf {
90                 self.into()
91         }
92
93         /// Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it.
94         pub fn as_legacy_pubkey(&self) -> Option<&PublicKey> {
95                 match &self.0 {
96                         ShutdownScriptImpl::Legacy(pubkey) => Some(pubkey),
97                         ShutdownScriptImpl::Bolt2(_) => None,
98                 }
99         }
100
101         /// Returns whether the shutdown script is compatible with the features as defined by BOLT #2.
102         ///
103         /// Specifically, checks for compliance with feature `option_shutdown_anysegwit`.
104         pub fn is_compatible(&self, features: &InitFeatures) -> bool {
105                 match &self.0 {
106                         ShutdownScriptImpl::Legacy(_) => true,
107                         ShutdownScriptImpl::Bolt2(script) => is_bolt2_compliant(script, features),
108                 }
109         }
110 }
111
112 /// Check if a given script is compliant with BOLT 2's shutdown script requirements for the given
113 /// counterparty features.
114 pub(crate) fn is_bolt2_compliant(script: &Script, features: &InitFeatures) -> bool {
115         if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
116                 true
117         } else if features.supports_shutdown_anysegwit() {
118                 script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.to_u8()
119         } else {
120                 false
121         }
122 }
123
124 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
125 // non-witness shutdown scripts which this rejects.
126 impl TryFrom<ScriptBuf> for ShutdownScript {
127         type Error = InvalidShutdownScript;
128
129         fn try_from(script: ScriptBuf) -> Result<Self, Self::Error> {
130                 Self::try_from((script, &channelmanager::provided_init_features(&crate::util::config::UserConfig::default())))
131         }
132 }
133
134 // Note that this is only for our own shutdown scripts. Counterparties are still allowed to send us
135 // non-witness shutdown scripts which this rejects.
136 impl TryFrom<(ScriptBuf, &InitFeatures)> for ShutdownScript {
137         type Error = InvalidShutdownScript;
138
139         fn try_from((script, features): (ScriptBuf, &InitFeatures)) -> Result<Self, Self::Error> {
140                 if is_bolt2_compliant(&script, features) && script.is_witness_program() {
141                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))
142                 } else {
143                         Err(InvalidShutdownScript { script })
144                 }
145         }
146 }
147
148 impl Into<ScriptBuf> for ShutdownScript {
149         fn into(self) -> ScriptBuf {
150                 match self.0 {
151                         ShutdownScriptImpl::Legacy(pubkey) =>
152                                 ScriptBuf::new_v0_p2wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
153                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
154                 }
155         }
156 }
157
158 impl core::fmt::Display for ShutdownScript{
159         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
160                 match &self.0 {
161                         ShutdownScriptImpl::Legacy(_) => self.clone().into_inner().fmt(f),
162                         ShutdownScriptImpl::Bolt2(script) => script.fmt(f),
163                 }
164         }
165 }
166
167 #[cfg(test)]
168 mod shutdown_script_tests {
169         use super::ShutdownScript;
170         use bitcoin::blockdata::opcodes;
171         use bitcoin::blockdata::script::{Builder, ScriptBuf};
172         use bitcoin::secp256k1::Secp256k1;
173         use bitcoin::secp256k1::{PublicKey, SecretKey};
174         use crate::ln::features::InitFeatures;
175         use core::convert::TryFrom;
176         use bitcoin::address::{WitnessProgram, WitnessVersion};
177
178         fn pubkey() -> bitcoin::key::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::key::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
182         }
183
184         fn redeem_script() -> ScriptBuf {
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         fn any_segwit_features() -> InitFeatures {
196                 let mut features = InitFeatures::empty();
197                 features.set_shutdown_any_segwit_optional();
198                 features
199         }
200
201         #[test]
202         fn generates_p2wpkh_from_pubkey() {
203                 let pubkey = pubkey();
204                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
205                 let p2wpkh_script = ScriptBuf::new_v0_p2wpkh(&pubkey_hash);
206
207                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.inner);
208                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
209                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
210                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
211         }
212
213         #[test]
214         fn generates_p2wpkh_from_pubkey_hash() {
215                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
216                 let p2wpkh_script = ScriptBuf::new_v0_p2wpkh(&pubkey_hash);
217
218                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
219                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
220                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
221                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
222                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
223         }
224
225         #[test]
226         fn generates_p2wsh_from_script_hash() {
227                 let script_hash = redeem_script().wscript_hash();
228                 let p2wsh_script = ScriptBuf::new_v0_p2wsh(&script_hash);
229
230                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
231                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
232                 assert!(shutdown_script.is_compatible(&InitFeatures::empty()));
233                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
234                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
235         }
236
237         #[test]
238         fn generates_segwit_from_non_v0_witness_program() {
239                 let witness_program = WitnessProgram::new(WitnessVersion::V16, &[0; 40]).unwrap();
240                 let script = ScriptBuf::new_witness_program(&witness_program);
241                 let shutdown_script = ShutdownScript::new_witness_program(&witness_program).unwrap();
242                 assert!(shutdown_script.is_compatible(&any_segwit_features()));
243                 assert!(!shutdown_script.is_compatible(&InitFeatures::empty()));
244                 assert_eq!(shutdown_script.into_inner(), script);
245         }
246
247         #[test]
248         fn fails_from_unsupported_script() {
249                 let op_return = ScriptBuf::new_op_return(&[0; 42]);
250                 assert!(ShutdownScript::try_from(op_return).is_err());
251         }
252 }