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