f - Define method for legacy format rather than using From
[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
12 use std::convert::TryFrom;
13
14 /// A script pubkey for shutting down a channel as defined by [BOLT #2].
15 ///
16 /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md
17 pub struct ShutdownScript(ShutdownScriptImpl);
18
19 /// An error occurring when converting from [`Script`] to [`ShutdownScript`].
20 #[derive(Debug)]
21 pub struct InvalidShutdownScript(Script);
22
23 enum ShutdownScriptImpl {
24         /// [`PublicKey`] used to form a P2WPKH script pubkey. Used to support backward-compatible
25         /// serialization.
26         Legacy(PublicKey),
27
28         /// [`Script`] adhering to a script pubkey format specified in BOLT #2.
29         Bolt2(Script),
30 }
31
32 impl ShutdownScript {
33         /// Generates a P2WPKH script pubkey from the given [`PublicKey`].
34         pub fn new_p2wpkh_from_pubkey(pubkey: PublicKey) -> Self {
35                 Self(ShutdownScriptImpl::Legacy(pubkey))
36         }
37
38         /// Generates a P2PKH script pubkey from the given [`PubkeyHash`].
39         pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Self {
40                 Self(ShutdownScriptImpl::Bolt2(Script::new_p2pkh(pubkey_hash)))
41         }
42
43         /// Generates a P2SH script pubkey from the given [`ScriptHash`].
44         pub fn new_p2sh(script_hash: &ScriptHash) -> Self {
45                 Self(ShutdownScriptImpl::Bolt2(Script::new_p2sh(script_hash)))
46         }
47
48         /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`].
49         pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self {
50                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wpkh(pubkey_hash)))
51         }
52
53         /// Generates a P2WSH script pubkey from the given [`WScriptHash`].
54         pub fn new_p2wsh(script_hash: &WScriptHash) -> Self {
55                 Self(ShutdownScriptImpl::Bolt2(Script::new_v0_wsh(script_hash)))
56         }
57
58         /// Generates a P2WSH script pubkey from the given segwit version and program.
59         ///
60         /// # Panics
61         ///
62         /// This function may panic if given a segwit program with an invalid length.
63         pub fn new_witness_program(version: u5, program: &[u8]) -> Self {
64                 let script = Script::new_witness_program(version, program);
65                 Self::try_from(script).expect("Invalid segwit program")
66         }
67
68         /// Converts the shutdown script into the underlying [`Script`].
69         pub fn into_inner(self) -> Script {
70                 self.into()
71         }
72 }
73
74 impl TryFrom<Script> for ShutdownScript {
75         type Error = InvalidShutdownScript;
76
77         fn try_from(script: Script) -> Result<Self, Self::Error> {
78                 Self::try_from((script, &InitFeatures::known()))
79         }
80 }
81
82 impl TryFrom<(Script, &InitFeatures)> for ShutdownScript {
83         type Error = InvalidShutdownScript;
84
85         fn try_from((script, features): (Script, &InitFeatures)) -> Result<Self, Self::Error> {
86                 if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wpkh() || script.is_v0_p2wsh() {
87                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))
88                 } else if features.supports_shutdown_anysegwit() && script.is_witness_program() && script.as_bytes()[0] != SEGWIT_V0.into_u8() {
89                         Ok(Self(ShutdownScriptImpl::Bolt2(script)))  // option_shutdown_anysegwit
90                 } else {
91                         Err(InvalidShutdownScript(script))
92                 }
93         }
94 }
95
96 impl Into<Script> for ShutdownScript {
97         fn into(self) -> Script {
98                 match self.0 {
99                         ShutdownScriptImpl::Legacy(pubkey) =>
100                                 Script::new_v0_wpkh(&WPubkeyHash::hash(&pubkey.serialize())),
101                         ShutdownScriptImpl::Bolt2(script_pubkey) => script_pubkey,
102                 }
103         }
104 }
105
106 #[cfg(test)]
107 mod shutdown_script_tests {
108         use super::ShutdownScript;
109         use bitcoin::bech32::u5;
110         use bitcoin::blockdata::opcodes;
111         use bitcoin::blockdata::script::{Builder, Script};
112         use bitcoin::secp256k1::Secp256k1;
113         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
114         use std::convert::TryFrom;
115
116         fn pubkey() -> bitcoin::util::ecdsa::PublicKey {
117                 let secp_ctx = Secp256k1::signing_only();
118                 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();
119                 bitcoin::util::ecdsa::PublicKey::new(PublicKey::from_secret_key(&secp_ctx, &secret_key))
120         }
121
122         fn redeem_script() -> Script {
123                 let pubkey = pubkey();
124                 Builder::new()
125                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
126                         .push_key(&pubkey)
127                         .push_key(&pubkey)
128                         .push_opcode(opcodes::all::OP_PUSHNUM_2)
129                         .push_opcode(opcodes::all::OP_CHECKMULTISIG)
130                         .into_script()
131         }
132
133         #[test]
134         fn generates_p2wpkh_from_pubkey() {
135                 let pubkey = pubkey();
136                 let pubkey_hash = pubkey.wpubkey_hash().unwrap();
137                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
138
139                 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(pubkey.key);
140                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
141         }
142
143         #[test]
144         fn generates_p2pkh_from_pubkey_hash() {
145                 let pubkey_hash = pubkey().pubkey_hash();
146                 let p2pkh_script = Script::new_p2pkh(&pubkey_hash);
147
148                 let shutdown_script = ShutdownScript::new_p2pkh(&pubkey_hash);
149                 assert_eq!(shutdown_script.into_inner(), p2pkh_script);
150                 assert!(ShutdownScript::try_from(p2pkh_script).is_ok());
151         }
152
153         #[test]
154         fn generates_p2sh_from_script_hash() {
155                 let script_hash = redeem_script().script_hash();
156                 let p2sh_script = Script::new_p2sh(&script_hash);
157
158                 let shutdown_script = ShutdownScript::new_p2sh(&script_hash);
159                 assert_eq!(shutdown_script.into_inner(), p2sh_script);
160                 assert!(ShutdownScript::try_from(p2sh_script).is_ok());
161         }
162
163         #[test]
164         fn generates_p2wpkh_from_pubkey_hash() {
165                 let pubkey_hash = pubkey().wpubkey_hash().unwrap();
166                 let p2wpkh_script = Script::new_v0_wpkh(&pubkey_hash);
167
168                 let shutdown_script = ShutdownScript::new_p2wpkh(&pubkey_hash);
169                 assert_eq!(shutdown_script.into_inner(), p2wpkh_script);
170                 assert!(ShutdownScript::try_from(p2wpkh_script).is_ok());
171         }
172
173         #[test]
174         fn generates_p2wsh_from_script_hash() {
175                 let script_hash = redeem_script().wscript_hash();
176                 let p2wsh_script = Script::new_v0_wsh(&script_hash);
177
178                 let shutdown_script = ShutdownScript::new_p2wsh(&script_hash);
179                 assert_eq!(shutdown_script.into_inner(), p2wsh_script);
180                 assert!(ShutdownScript::try_from(p2wsh_script).is_ok());
181         }
182
183         #[test]
184         fn fails_from_unsupported_script() {
185                 let op_return = Script::new_op_return(&[0; 42]);
186                 assert!(ShutdownScript::try_from(op_return).is_err());
187         }
188
189         #[test]
190         fn fails_from_invalid_segwit_v0_program() {
191                 let witness_program = Script::new_witness_program(u5::try_from_u8(0).unwrap(), &[0; 2]);
192                 assert!(ShutdownScript::try_from(witness_program).is_err());
193         }
194 }