Update bitcoin crate to 0.29.0
[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::features::InitFeatures;
11 use ln::msgs::DecodeError;
12 use util::ser::{Readable, Writeable, Writer};
13
14 use core::convert::TryFrom;
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/lightning/bolts/blob/master/02-peer-protocol.md
20 #[derive(Clone, PartialEq)]
21 pub struct ShutdownScript(ShutdownScriptImpl);
22
23 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
24 #[derive(Clone, Debug)]
25 pub struct InvalidShutdownScript {
26         /// The script that did not meet the requirements from [BOLT #2].
27         ///
28         /// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
29         pub script: Script
30 }
31
32 #[derive(Clone, PartialEq)]
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_p2wpkh(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_p2wsh(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: WitnessVersion, program: &[u8]) -> Result<Self, InvalidShutdownScript> {
88                 let script = Builder::new()
89                         .push_int(version as i64)
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.to_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_p2wpkh(&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::blockdata::opcodes;
178         use bitcoin::blockdata::script::{Builder, Script};
179         use bitcoin::secp256k1::Secp256k1;
180         use bitcoin::secp256k1::{PublicKey, SecretKey};
181         use ln::features::InitFeatures;
182         use core::convert::TryFrom;
183         use bitcoin::util::address::WitnessVersion;
184
185         fn pubkey() -> bitcoin::util::key::PublicKey {
186                 let secp_ctx = Secp256k1::signing_only();
187                 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();
188                 bitcoin::util::key::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
189         }
190
191         fn redeem_script() -> Script {
192                 let pubkey = pubkey();
193                 Builder::new()
194                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
195                         .push_key(&pubkey)
196                         .push_key(&pubkey)
197                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
198                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
199                         .into_script()
200         }
201
202         #[test]
203         fn generates_p2wpkh_from_pubkey() {
204                 let pubkey = pubkey();
205                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
206                 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
207
208                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.inner);
209                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
210                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
211                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
212         }
213
214         #[test]
215         fn generates_p2wpkh_from_pubkey_hash() {
216                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
217                 let p2wpkh_script = Script::new_v0_p2wpkh(&pubkey_hash);
218
219                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
220                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
221                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
222                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
223                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
224         }
225
226         #[test]
227         fn generates_p2wsh_from_script_hash() {
228                 let script_hash = redeem_script().wscript_hash();
229                 let p2wsh_script = Script::new_v0_p2wsh(&script_hash);
230
231                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
232                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
233                 assert!(shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
234                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
235                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
236         }
237
238         #[test]
239         fn generates_segwit_from_non_v0_witness_program() {
240                 let witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 40]);
241                 let shutdown_script = ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 40]).unwrap();
242                 assert!(shutdown_script.is_compatible(&InitFeatures::known()));
243                 assert!(!shutdown_script.is_compatible(&InitFeatures::known().clear_shutdown_anysegwit()));
244                 assert_eq!(shutdown_script.into_inner(), witness_program);
245         }
246
247         #[test]
248         fn fails_from_unsupported_script() {
249                 let op_return = Script::new_op_return(&[0; 42]);
250                 assert!(ShutdownScript::try_from(op_return).is_err());
251         }
252
253         #[test]
254         fn fails_from_invalid_segwit_v0_witness_program() {
255                 let witness_program = Script::new_witness_program(WitnessVersion::V0, &[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 witness_program = Script::new_witness_program(WitnessVersion::V16, &[0; 42]);
262                 assert!(ShutdownScript::try_from(witness_program).is_err());
263
264                 assert!(ShutdownScript::new_witness_program(WitnessVersion::V16, &[0; 42]).is_err());
265         }
266 }