1
2pub extern crate bitcoin;
3
4#[macro_use] extern crate serde;
5#[macro_use] extern crate lazy_static;
6
7#[macro_use] mod util;
8
9pub mod address;
10pub mod arkoor;
11pub mod connectors;
12pub mod encode;
13pub mod error;
14pub mod forfeit;
15pub mod lightning;
16pub mod mailbox;
17pub mod musig;
18pub mod board;
19pub mod rounds;
20pub mod tree;
21pub mod vtxo;
22pub mod integration;
23
24pub use crate::address::Address;
25pub use crate::encode::{ProtocolEncoding, WriteExt, ReadExt, ProtocolDecodingError};
26pub use crate::vtxo::{Vtxo, VtxoId, VtxoPolicy};
27
28#[cfg(test)]
29mod napkin;
30#[cfg(any(test, feature = "test-util"))]
31pub mod test;
32
33
34use std::time::Duration;
35
36use bitcoin::{Amount, FeeRate, Network, Script, ScriptBuf, TxOut, Weight};
37use bitcoin::secp256k1::{self, schnorr, PublicKey};
38
39use bitcoin_ext::{
40 BlockDelta, TxOutExt, P2PKH_DUST_VB, P2SH_DUST_VB, P2TR_DUST_VB, P2WPKH_DUST_VB, P2WSH_DUST_VB
41};
42
43lazy_static! {
44 pub static ref SECP: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new();
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct ArkInfo {
50 pub network: Network,
52 pub server_pubkey: PublicKey,
54 pub round_interval: Duration,
56 pub nb_round_nonces: usize,
58 pub vtxo_exit_delta: BlockDelta,
60 pub vtxo_expiry_delta: BlockDelta,
62 pub htlc_send_expiry_delta: BlockDelta,
64 pub htlc_expiry_delta: BlockDelta,
66 pub max_vtxo_amount: Option<Amount>,
68 pub max_arkoor_depth: u16,
70 pub required_board_confirmations: usize,
72 pub max_user_invoice_cltv_delta: u16,
75 pub min_board_amount: Amount,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
81pub struct VtxoIdInput {
82 pub vtxo_id: VtxoId,
83 pub ownership_proof: schnorr::Signature,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
93pub struct VtxoRequest {
94 pub amount: Amount,
95 #[serde(with = "crate::encode::serde")]
96 pub policy: VtxoPolicy,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
100pub struct SignedVtxoRequest {
101 pub vtxo: VtxoRequest,
103 pub cosign_pubkey: Option<PublicKey>,
106}
107
108
109#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
110#[error("invalid offboard request: {0}")]
111pub struct InvalidOffboardRequestError(&'static str);
112
113
114#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
115pub struct OffboardRequest {
116 pub script_pubkey: ScriptBuf,
117 #[serde(rename = "amount_sat", with = "bitcoin::amount::serde::as_sat")]
118 pub amount: Amount,
119}
120
121impl OffboardRequest {
122 pub fn calculate_fee(
127 script_pubkey: &Script,
128 fee_rate: FeeRate,
129 ) -> Result<Amount, InvalidOffboardRequestError> {
130 let vb = if script_pubkey.is_p2pkh() {
136 P2PKH_DUST_VB
137 } else if script_pubkey.is_p2sh() {
138 P2SH_DUST_VB
139 } else if script_pubkey.is_p2wpkh() {
140 P2WPKH_DUST_VB
141 } else if script_pubkey.is_p2wsh() {
142 P2WSH_DUST_VB
143 } else if script_pubkey.is_p2tr() {
144 P2TR_DUST_VB
145 } else if script_pubkey.is_op_return() {
146 if script_pubkey.len() > 83 {
147 return Err(InvalidOffboardRequestError("OP_RETURN over 83 bytes"));
148 } else {
149 bitcoin::consensus::encode::VarInt(script_pubkey.len() as u64).size() as u64
150 + script_pubkey.len() as u64
151 + 8 + 36 + 4 + 1 + 1 }
158 } else {
159 return Err(InvalidOffboardRequestError("non-standard scriptPubkey"));
160 };
161 Ok(fee_rate * Weight::from_vb(vb).expect("no overflow"))
162 }
163
164 pub fn validate(&self) -> Result<(), InvalidOffboardRequestError> {
166 if self.to_txout().is_standard() {
167 Ok(())
168 } else {
169 Err(InvalidOffboardRequestError("non-standard output"))
170 }
171 }
172
173 pub fn to_txout(&self) -> TxOut {
175 TxOut {
176 script_pubkey: self.script_pubkey.clone(),
177 value: self.amount,
178 }
179 }
180
181 pub fn fee(&self, fee_rate: FeeRate) -> Result<Amount, InvalidOffboardRequestError> {
183 Ok(Self::calculate_fee(&self.script_pubkey, fee_rate)?)
184 }
185}
186
187pub mod scripts {
188 use bitcoin::{opcodes, ScriptBuf, TapSighash, TapTweakHash, Transaction};
189 use bitcoin::hashes::{sha256, ripemd160, Hash};
190 use bitcoin::secp256k1::{schnorr, PublicKey, XOnlyPublicKey};
191
192 use bitcoin_ext::{BlockDelta, BlockHeight, TAPROOT_KEYSPEND_WEIGHT};
193
194 use crate::musig;
195
196 pub fn delayed_sign(delay_blocks: BlockDelta, pubkey: XOnlyPublicKey) -> ScriptBuf {
198 let csv = bitcoin::Sequence::from_height(delay_blocks);
199 bitcoin::Script::builder()
200 .push_int(csv.to_consensus_u32() as i64)
201 .push_opcode(opcodes::all::OP_CSV)
202 .push_opcode(opcodes::all::OP_DROP)
203 .push_x_only_key(&pubkey)
204 .push_opcode(opcodes::all::OP_CHECKSIG)
205 .into_script()
206 }
207
208 pub fn timelock_sign(timelock_height: BlockHeight, pubkey: XOnlyPublicKey) -> ScriptBuf {
210 let lt = bitcoin::absolute::LockTime::from_height(timelock_height).unwrap();
211 bitcoin::Script::builder()
212 .push_int(lt.to_consensus_u32() as i64)
213 .push_opcode(opcodes::all::OP_CLTV)
214 .push_opcode(opcodes::all::OP_DROP)
215 .push_x_only_key(&pubkey)
216 .push_opcode(opcodes::all::OP_CHECKSIG)
217 .into_script()
218 }
219
220 pub fn delay_timelock_sign(delay_blocks: BlockDelta, timelock_height: BlockHeight, pubkey: XOnlyPublicKey) -> ScriptBuf {
222 let csv = bitcoin::Sequence::from_height(delay_blocks);
223 let lt = bitcoin::absolute::LockTime::from_height(timelock_height).unwrap();
224 bitcoin::Script::builder()
225 .push_int(lt.to_consensus_u32().try_into().unwrap())
226 .push_opcode(opcodes::all::OP_CLTV)
227 .push_opcode(opcodes::all::OP_DROP)
228 .push_int(csv.to_consensus_u32().try_into().unwrap())
229 .push_opcode(opcodes::all::OP_CSV)
230 .push_opcode(opcodes::all::OP_DROP)
231 .push_x_only_key(&pubkey)
232 .push_opcode(opcodes::all::OP_CHECKSIG)
233 .into_script()
234 }
235
236 pub fn hash_and_sign(hash: sha256::Hash, pubkey: XOnlyPublicKey) -> ScriptBuf {
237 let hash_160 = ripemd160::Hash::hash(&hash[..]);
238
239 bitcoin::Script::builder()
240 .push_opcode(opcodes::all::OP_HASH160)
241 .push_slice(hash_160.as_byte_array())
242 .push_opcode(opcodes::all::OP_EQUALVERIFY)
243 .push_x_only_key(&pubkey)
244 .push_opcode(opcodes::all::OP_CHECKSIG)
245 .into_script()
246 }
247
248 pub fn hash_delay_sign(hash: sha256::Hash, delay_blocks: BlockDelta, pubkey: XOnlyPublicKey) -> ScriptBuf {
249 let hash_160 = ripemd160::Hash::hash(&hash[..]);
250 let csv = bitcoin::Sequence::from_height(delay_blocks);
251
252 bitcoin::Script::builder()
253 .push_int(csv.to_consensus_u32().try_into().unwrap())
254 .push_opcode(opcodes::all::OP_CSV)
255 .push_opcode(opcodes::all::OP_DROP)
256 .push_opcode(opcodes::all::OP_HASH160)
257 .push_slice(hash_160.as_byte_array())
258 .push_opcode(opcodes::all::OP_EQUALVERIFY)
259 .push_x_only_key(&pubkey)
260 .push_opcode(opcodes::all::OP_CHECKSIG)
261 .into_script()
262 }
263
264 pub fn fill_taproot_sigs(tx: &mut Transaction, sigs: &[schnorr::Signature]) {
269 assert_eq!(tx.input.len(), sigs.len());
270 for (input, sig) in tx.input.iter_mut().zip(sigs.iter()) {
271 assert!(input.witness.is_empty());
272 input.witness.push(&sig[..]);
273 debug_assert_eq!(TAPROOT_KEYSPEND_WEIGHT, input.witness.size());
274 }
275 }
276
277 pub fn verify_partial_sig(
279 sighash: TapSighash,
280 tweak: TapTweakHash,
281 signer: (PublicKey, &musig::PublicNonce),
282 other: (PublicKey, &musig::PublicNonce),
283 partial_signature: &musig::PartialSignature,
284 ) -> bool {
285 let agg_nonce = musig::nonce_agg(&[&signer.1, &other.1]);
286 let agg_pk = musig::tweaked_key_agg([signer.0, other.0], tweak.to_byte_array()).0;
287
288 let session = musig::Session::new(&agg_pk, agg_nonce, &sighash.to_byte_array());
289 session.partial_verify(
290 &agg_pk, partial_signature, signer.1, musig::pubkey_to(signer.0),
291 )
292 }
293}